oda-engine 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/README.md +151 -2
  2. package/bin/nowhere.mjs +352 -0
  3. package/lib/account.mjs +57 -0
  4. package/lib/agentModules.mjs +57 -0
  5. package/lib/devServer.mjs +351 -0
  6. package/lib/headless.mjs +231 -0
  7. package/lib/headlessPreview.mjs +212 -0
  8. package/lib/keys.mjs +517 -0
  9. package/lib/make.mjs +855 -0
  10. package/lib/mcp.mjs +537 -0
  11. package/lib/open.mjs +22 -0
  12. package/lib/preview.mjs +87 -0
  13. package/lib/previewRpc.mjs +134 -0
  14. package/lib/project.mjs +359 -0
  15. package/lib/publishFlow.mjs +131 -0
  16. package/lib/resources.mjs +50 -0
  17. package/lib/rules.mjs +60 -0
  18. package/lib/scaffold.mjs +42 -0
  19. package/lib/setup.mjs +59 -0
  20. package/lib/tools.mjs +668 -0
  21. package/package.json +51 -4
  22. package/template/game.config.json +9 -0
  23. package/template/scene.json +4 -0
  24. package/template/src/main.ts +11 -0
  25. package/vendor/DOCS.md +447 -0
  26. package/vendor/agent/appRun.mjs +520 -0
  27. package/vendor/agent/assets/brief.mjs +242 -0
  28. package/vendor/agent/assets/collider.mjs +531 -0
  29. package/vendor/agent/assets/environments/index.mjs +12 -0
  30. package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
  31. package/vendor/agent/assets/fetch.mjs +168 -0
  32. package/vendor/agent/assets/footprint.mjs +13 -0
  33. package/vendor/agent/assets/gltf.mjs +547 -0
  34. package/vendor/agent/assets/hdr.mjs +269 -0
  35. package/vendor/agent/assets/imageOps.mjs +171 -0
  36. package/vendor/agent/assets/images/codex.mjs +307 -0
  37. package/vendor/agent/assets/images/fal.mjs +75 -0
  38. package/vendor/agent/assets/images/gemini.mjs +84 -0
  39. package/vendor/agent/assets/images/index.mjs +25 -0
  40. package/vendor/agent/assets/images/openai.mjs +75 -0
  41. package/vendor/agent/assets/images/stability.mjs +71 -0
  42. package/vendor/agent/assets/images/views.mjs +31 -0
  43. package/vendor/agent/assets/import.mjs +1352 -0
  44. package/vendor/agent/assets/inspect.mjs +465 -0
  45. package/vendor/agent/assets/jobs.mjs +196 -0
  46. package/vendor/agent/assets/ktx2.mjs +290 -0
  47. package/vendor/agent/assets/ledger.mjs +466 -0
  48. package/vendor/agent/assets/net.mjs +254 -0
  49. package/vendor/agent/assets/prices.json +39 -0
  50. package/vendor/agent/assets/providers/fal.mjs +115 -0
  51. package/vendor/agent/assets/providers/index.mjs +22 -0
  52. package/vendor/agent/assets/providers/meshy.mjs +119 -0
  53. package/vendor/agent/assets/providers/tripo.mjs +188 -0
  54. package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
  55. package/vendor/agent/assets/sources/index.mjs +23 -0
  56. package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
  57. package/vendor/agent/assets/sources/polypizza.mjs +121 -0
  58. package/vendor/agent/assets/splat.mjs +631 -0
  59. package/vendor/agent/assets/targets.mjs +122 -0
  60. package/vendor/agent/assets/tile.mjs +261 -0
  61. package/vendor/agent/assets/unzip.mjs +180 -0
  62. package/vendor/agent/blender/cleanup.py +360 -0
  63. package/vendor/agent/blender/convert.py +167 -0
  64. package/vendor/agent/blender/find.mjs +192 -0
  65. package/vendor/agent/blender/nw_export.py +104 -0
  66. package/vendor/agent/blender/nw_rubric.py +426 -0
  67. package/vendor/agent/blender/run.mjs +193 -0
  68. package/vendor/agent/blender/runner.py +252 -0
  69. package/vendor/agent/blender/sheet.py +743 -0
  70. package/vendor/agent/depth.mjs +134 -0
  71. package/vendor/agent/director/board.mjs +451 -0
  72. package/vendor/agent/director/contracts.mjs +663 -0
  73. package/vendor/agent/director/director.mjs +2365 -0
  74. package/vendor/agent/director/estimate.mjs +200 -0
  75. package/vendor/agent/director/gate.mjs +802 -0
  76. package/vendor/agent/director/limits.json +16 -0
  77. package/vendor/agent/director/methods.mjs +457 -0
  78. package/vendor/agent/director/policy.json +33 -0
  79. package/vendor/agent/director/prompts.mjs +244 -0
  80. package/vendor/agent/director/reading.mjs +341 -0
  81. package/vendor/agent/director/router.mjs +184 -0
  82. package/vendor/agent/director/seams.mjs +243 -0
  83. package/vendor/agent/director/session.mjs +643 -0
  84. package/vendor/agent/director/store.mjs +119 -0
  85. package/vendor/agent/director/taskGate.mjs +110 -0
  86. package/vendor/agent/director/teamLedger.mjs +118 -0
  87. package/vendor/agent/director/triage.mjs +63 -0
  88. package/vendor/agent/downloads.cjs +363 -0
  89. package/vendor/agent/flow.mjs +78 -0
  90. package/vendor/agent/guard.mjs +613 -0
  91. package/vendor/agent/host.mjs +1736 -0
  92. package/vendor/agent/language.mjs +58 -0
  93. package/vendor/agent/ledger.mjs +360 -0
  94. package/vendor/agent/locale.cjs +186 -0
  95. package/vendor/agent/loop/capacity.mjs +74 -0
  96. package/vendor/agent/loop/compose.mjs +127 -0
  97. package/vendor/agent/loop/gate.mjs +205 -0
  98. package/vendor/agent/loop/judge.mjs +189 -0
  99. package/vendor/agent/loop/levels.mjs +273 -0
  100. package/vendor/agent/loop/state.mjs +358 -0
  101. package/vendor/agent/notes.cjs +278 -0
  102. package/vendor/agent/pace.mjs +258 -0
  103. package/vendor/agent/panels.mjs +431 -0
  104. package/vendor/agent/prompt.mjs +342 -0
  105. package/vendor/agent/reference/board.mjs +410 -0
  106. package/vendor/agent/reference/compose.mjs +364 -0
  107. package/vendor/agent/reference/decode.mjs +56 -0
  108. package/vendor/agent/reference/facts.mjs +1874 -0
  109. package/vendor/agent/reference/png.mjs +107 -0
  110. package/vendor/agent/reference/records.mjs +63 -0
  111. package/vendor/agent/reference/web.mjs +252 -0
  112. package/vendor/agent/roles/artist.mjs +69 -0
  113. package/vendor/agent/roles/builder.mjs +79 -0
  114. package/vendor/agent/roles/checks.mjs +223 -0
  115. package/vendor/agent/roles/common.mjs +188 -0
  116. package/vendor/agent/roles/critic.mjs +171 -0
  117. package/vendor/agent/roles/index.mjs +39 -0
  118. package/vendor/agent/roles/modeller.mjs +142 -0
  119. package/vendor/agent/roles/qa.mjs +58 -0
  120. package/vendor/agent/roles/rubrics.mjs +79 -0
  121. package/vendor/agent/roles/sound.mjs +69 -0
  122. package/vendor/agent/rounds.cjs +333 -0
  123. package/vendor/agent/shared.mjs +284 -0
  124. package/vendor/agent/stopGate.mjs +574 -0
  125. package/vendor/agent/subagents.mjs +129 -0
  126. package/vendor/agent/tools/assets.mjs +499 -0
  127. package/vendor/agent/tools/blender.mjs +754 -0
  128. package/vendor/agent/tools/cards.mjs +479 -0
  129. package/vendor/agent/tools/choices.mjs +479 -0
  130. package/vendor/agent/tools/compose.mjs +74 -0
  131. package/vendor/agent/tools/environment.mjs +488 -0
  132. package/vendor/agent/tools/eyes.mjs +733 -0
  133. package/vendor/agent/tools/generate.mjs +338 -0
  134. package/vendor/agent/tools/guide.mjs +46 -0
  135. package/vendor/agent/tools/harness.mjs +193 -0
  136. package/vendor/agent/tools/image.mjs +643 -0
  137. package/vendor/agent/tools/index.mjs +162 -0
  138. package/vendor/agent/tools/look.mjs +578 -0
  139. package/vendor/agent/tools/loop.mjs +858 -0
  140. package/vendor/agent/tools/others.mjs +123 -0
  141. package/vendor/agent/tools/pictures.mjs +535 -0
  142. package/vendor/agent/tools/reference.mjs +366 -0
  143. package/vendor/agent/transcripts.mjs +118 -0
  144. package/vendor/agent-loop.mjs +602 -0
  145. package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
  146. package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
  147. package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
  148. package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
  149. package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
  150. package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
  151. package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
  152. package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
  153. package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
  154. package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
  155. package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
  156. package/vendor/auth.cjs +570 -0
  157. package/vendor/build.cjs +953 -0
  158. package/vendor/catalog.json +455 -0
  159. package/vendor/connectors.cjs +688 -0
  160. package/vendor/eyes.mjs +733 -0
  161. package/vendor/gameExports.json +1390 -0
  162. package/vendor/git.cjs +222 -0
  163. package/vendor/models.json +57 -0
  164. package/vendor/publish.cjs +1018 -0
  165. package/vendor/refBoard.cjs +301 -0
  166. package/vendor/schema/dist/assets.d.ts +335 -0
  167. package/vendor/schema/dist/assets.js +439 -0
  168. package/vendor/schema/dist/brief.d.ts +357 -0
  169. package/vendor/schema/dist/brief.js +302 -0
  170. package/vendor/schema/dist/common.d.ts +9 -0
  171. package/vendor/schema/dist/common.js +13 -0
  172. package/vendor/schema/dist/config.d.ts +406 -0
  173. package/vendor/schema/dist/config.js +355 -0
  174. package/vendor/schema/dist/contract.d.ts +599 -0
  175. package/vendor/schema/dist/contract.js +1146 -0
  176. package/vendor/schema/dist/index.d.ts +14 -0
  177. package/vendor/schema/dist/index.js +21 -0
  178. package/vendor/schema/dist/look.d.ts +463 -0
  179. package/vendor/schema/dist/look.js +681 -0
  180. package/vendor/schema/dist/lookStats.d.ts +230 -0
  181. package/vendor/schema/dist/lookStats.js +768 -0
  182. package/vendor/schema/dist/pilot.d.ts +32 -0
  183. package/vendor/schema/dist/pilot.js +44 -0
  184. package/vendor/schema/dist/publish.d.ts +214 -0
  185. package/vendor/schema/dist/publish.js +291 -0
  186. package/vendor/schema/dist/scene.d.ts +75 -0
  187. package/vendor/schema/dist/scene.js +120 -0
  188. package/vendor/schema/dist/skyLight.d.ts +141 -0
  189. package/vendor/schema/dist/skyLight.js +436 -0
  190. package/vendor/schema/dist/style.d.ts +131 -0
  191. package/vendor/schema/dist/style.js +155 -0
  192. package/vendor/schema/package.json +1 -0
  193. package/vendor/selectionPrompt.mjs +51 -0
  194. package/vendor/useTools.mjs +195 -0
  195. package/vendor/userMessage.mjs +26 -0
  196. package/web-dist/assets/GaussianSplatUtils-CptQkDVX.js +1 -0
  197. package/web-dist/assets/KTX2Loader-C53LJqss.js +2 -0
  198. package/web-dist/assets/SPZLoader-BQ3tjaTv.js +1 -0
  199. package/web-dist/assets/gaussianSplat-_9tcWegB.js +1 -0
  200. package/web-dist/assets/index-Baka-ZO7.js +693 -0
  201. package/web-dist/assets/index-CcjyyQco.css +1 -0
  202. package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
  203. package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
  204. package/web-dist/index.html +34 -0
@@ -0,0 +1,953 @@
1
+ const fs = require('node:fs')
2
+ const path = require('node:path')
3
+
4
+ // Bundles a game project's src/main.ts into one ESM string the renderer can
5
+ // import from a blob URL. `three` and `@nowhere/sdk` are not bundled in:
6
+ // they resolve to globalThis.__nw_modules, which the studio fills with ITS OWN
7
+ // instances before importing, so the game and the viewport share one three.js
8
+ // (two copies break instanceof checks and double every GPU cache).
9
+ //
10
+ // That shim is CommonJS to esbuild, so it never knew what those modules
11
+ // export: a game that imported atan2 from three/tsl, which three does not
12
+ // have, built clean and failed as it loaded (2026-10-20). So a build that
13
+ // passes is bundled once more against stand-ins that export exactly what the
14
+ // studio's three, three/tsl and SDK export (gameExports.json, written by
15
+ // scripts/build-game-exports.mjs from the installed three and the SDK's
16
+ // source), and every named import that is not there fails the build with
17
+ // where it is and what to use instead. A namespace member that is not there
18
+ // (THREE.X) is only undefined where it is read, so it fails the build only
19
+ // where it certainly throws (runsOnLoad) and is a warning everywhere
20
+ // else. three's addons, when a project's three can be found for them, are
21
+ // bundled as before, and esbuild checks what they import the same way; their
22
+ // own imports of three are checked against the studio's three like the game's.
23
+
24
+ const SHARED = /^(three(\/(webgpu|tsl))?|@nowhere\/sdk)$/
25
+ const MODULES = ['three/webgpu', 'three/tsl', '@nowhere/sdk']
26
+ const EXPORTS_FILE = path.join(__dirname, 'gameExports.json')
27
+
28
+ let esbuild = null
29
+ function lib() {
30
+ // Lazy: keeps app startup off the hook for esbuild's native binary load.
31
+ if (!esbuild) esbuild = require('esbuild')
32
+ return esbuild
33
+ }
34
+
35
+ /**
36
+ * What the studio hands a game for each shared module, read from the
37
+ * installed three and the SDK's source with esbuild (its metafile lists an
38
+ * entry's exports): { three: version, modules: { name: [export names] } },
39
+ * or null where they cannot be found (a packaged app, which reads
40
+ * gameExports.json instead).
41
+ */
42
+ async function readRuntimeExports() {
43
+ const resolve = (id) => {
44
+ try {
45
+ return require.resolve(id)
46
+ } catch {
47
+ return null
48
+ }
49
+ }
50
+ const files = { 'three/webgpu': resolve('three/webgpu'), 'three/tsl': resolve('three/tsl'), '@nowhere/sdk': resolve('@nowhere/sdk') }
51
+ if (Object.values(files).some((f) => !f)) return null
52
+ const namesOf = async (file) => {
53
+ const result = await lib().build({
54
+ entryPoints: [file],
55
+ bundle: true,
56
+ write: false,
57
+ metafile: true,
58
+ format: 'esm',
59
+ platform: 'neutral',
60
+ outdir: 'out',
61
+ logLevel: 'silent',
62
+ // Only the entry's own exports matter: whatever it imports stays out.
63
+ plugins: [
64
+ {
65
+ name: 'nw-entry-only',
66
+ setup(b) {
67
+ b.onResolve({ filter: /^[^./]/ }, (args) => (args.kind === 'entry-point' ? null : { path: args.path, external: true }))
68
+ },
69
+ },
70
+ ],
71
+ })
72
+ const out = Object.values(result.metafile.outputs).find((o) => o.entryPoint)
73
+ return [...(out?.exports ?? [])].sort()
74
+ }
75
+ let version = null
76
+ try {
77
+ let dir = path.dirname(files['three/webgpu'])
78
+ while (!fs.existsSync(path.join(dir, 'package.json'))) dir = path.dirname(dir)
79
+ version = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).version ?? null
80
+ } catch {
81
+ version = null
82
+ }
83
+ const modules = {}
84
+ for (const name of MODULES) modules[name] = await namesOf(files[name])
85
+ return { three: version, modules }
86
+ }
87
+
88
+ let exportsTable = null
89
+ /** The export lists as sets, `three` being three/webgpu as the studio maps
90
+ * it; from gameExports.json, else read from the installed modules; null
91
+ * when neither is there, and then the build checks nothing more. */
92
+ function sharedExports() {
93
+ exportsTable ??= (async () => {
94
+ let raw = null
95
+ try {
96
+ raw = JSON.parse(fs.readFileSync(EXPORTS_FILE, 'utf8'))
97
+ } catch {
98
+ raw = await readRuntimeExports().catch(() => null)
99
+ }
100
+ if (!raw?.modules || !MODULES.every((m) => Array.isArray(raw.modules[m]))) return null
101
+ const sets = Object.fromEntries(MODULES.map((m) => [m, new Set(raw.modules[m])]))
102
+ sets.three = sets['three/webgpu']
103
+ return { three: raw.three ?? null, sets }
104
+ })()
105
+ return exportsTable
106
+ }
107
+
108
+ // What to use instead of a name a game reached for that three does not have:
109
+ // the ones models write from older three.js and from GLSL, and those of the
110
+ // names r186 dropped that a game might write. The rest it dropped (blur,
111
+ // getDirection, getShadowMaterial, getShadowRenderObjectFunction) were three's
112
+ // own plumbing, and lookalikes covers them.
113
+ const INSTEAD = {
114
+ 'three/tsl': {
115
+ atan2: 'atan(y, x), which is atan2 when given two arguments',
116
+ timerLocal: 'time (seconds since the start)',
117
+ timerGlobal: 'time',
118
+ timerDelta: 'deltaTime',
119
+ lerp: 'mix(a, b, t)',
120
+ tslFn: 'Fn',
121
+ cond: 'select(condition, a, b)',
122
+ loop: 'Loop',
123
+ fmod: 'mod',
124
+ modInt: 'mod',
125
+ remainder: 'mod',
126
+ random: 'hash(seed)',
127
+ noise: 'mx_noise_float (or mx_fractal_noise_float)',
128
+ perlin: 'mx_noise_float',
129
+ simplex: 'mx_noise_float',
130
+ normalMatrix: 'modelNormalMatrix',
131
+ append: 'Stack(node) (or .toStack()), its name since r176',
132
+ viewportResolution: 'screenSize',
133
+ rangeFog: "fog(color, rangeFogFactor(near, far)) in a material; the planet's own fog is the look's (look_apply)",
134
+ densityFog: "fog(color, densityFogFactor(density)) in a material; the planet's own fog is the look's (look_apply)",
135
+ PCFSoftShadowFilter: "PCFShadowFilter (r186 removed the soft one), or the SDK's softShadowFilter as the shadow's filterNode",
136
+ textureCubeUV: 'pmremTexture(texture, direction, roughness)',
137
+ screen: 'blendScreen(base, blend)',
138
+ bloom: "emissiveNode with an intensity above 1, and the planet's look (look_apply), whose bloom the host draws",
139
+ gaussianBlur: "nothing: the host owns post-processing (the planet's look, set with look_apply)",
140
+ rgbShift: "nothing: the host owns post-processing (the planet's look, set with look_apply)",
141
+ },
142
+ three: {
143
+ ShaderChunk: 'TSL nodes: WebGPU compiles no GLSL, so the shader chunks and onBeforeCompile never take part there',
144
+ ShaderLib: 'TSL nodes: WebGPU compiles no GLSL, so the shader chunks and onBeforeCompile never take part there',
145
+ UniformsLib: 'TSL nodes: WebGPU compiles no GLSL, so the shader chunks and onBeforeCompile never take part there',
146
+ WebGLRenderer: 'nothing: the studio owns the renderer (WebGPURenderer)',
147
+ EffectComposer: "nothing: the host owns post-processing; set the planet's look with look_apply (tone mapping, bloom, AO, fog, grade, vignette)",
148
+ OrbitControls: "the SDK's player and its camera() (World spawnPlayer)",
149
+ },
150
+ }
151
+
152
+ /** Up to three of `names` that look like `want`: the same but for case, or
153
+ * containing it, or two edits from it. */
154
+ function lookalikes(want, names) {
155
+ const lower = want.toLowerCase()
156
+ const near = (a, b) => {
157
+ if (Math.abs(a.length - b.length) > 2) return false
158
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i)
159
+ for (let i = 1; i <= a.length; i++) {
160
+ let prev = row[0]
161
+ row[0] = i
162
+ for (let j = 1; j <= b.length; j++) {
163
+ const keep = row[j]
164
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1))
165
+ prev = keep
166
+ }
167
+ }
168
+ return row[b.length] <= 2
169
+ }
170
+ const found = []
171
+ for (const name of names) {
172
+ const l = name.toLowerCase()
173
+ if (l === lower || (lower.length >= 4 && l.includes(lower)) || (lower.length >= 4 && near(l, lower))) found.push(name)
174
+ if (found.length >= 3) break
175
+ }
176
+ return found
177
+ }
178
+
179
+ /** One line for an import a shared module does not have. A named import
180
+ * (or a member that certainly throws) fails the build; `member` is a
181
+ * namespace member read where it may never run, said as a warning. */
182
+ function missingImport(location, module, name, table, projectRoot, member = null) {
183
+ const where = location ? `${relativeFile(location.file, projectRoot)}:${location.line}:${location.column} ` : ''
184
+ // three's own name for its version: 0.186.1 is r186.
185
+ const r = `r${/^0\.(\d+)/.exec(table.three ?? '')?.[1] ?? '186'}`
186
+ const of = module === 'three' || module === 'three/webgpu' ? `${module} (three ${r})` : module === 'three/tsl' ? `three/tsl (three ${r})` : '@nowhere/sdk'
187
+ const instead = INSTEAD[module]?.[name] ?? (module === 'three/webgpu' ? INSTEAD.three[name] : undefined)
188
+ const alike = instead ? [] : lookalikes(name, table.sets[module] ?? [])
189
+ const hint = instead ? ` Use ${instead}.` : alike.length ? ` Did you mean ${alike.join(', ')}?` : ''
190
+ const guide = module === '@nowhere/sdk' ? ' The SDK guide (nw_docs) lists what it has.' : module === 'three/tsl' ? ' The tsl-r185 skill lists the TSL names that exist.' : ''
191
+ if (member) {
192
+ return `${where}${of} has no export "${name}", so ${member} is undefined there, and what uses it fails when that code runs. The game still builds, as it is not certain to fail as the game starts (it is inside a function, a branch or a condition, or only passed along); replace it all the same.${hint}${guide}`
193
+ }
194
+ return `${where}${of} has no export "${name}", so the game would fail as it loads (the studio and every planet run these modules as they are).${hint}${guide}`
195
+ }
196
+
197
+ const relativeFile = (file, projectRoot) => (path.isAbsolute(file) ? path.relative(projectRoot, file) : file)
198
+
199
+ // ---- where a namespace member that is not there is used
200
+ //
201
+ // `import { X }` of a name that is not there fails as the module links,
202
+ // wherever X is used. `THREE.X` through `import * as THREE` is only
203
+ // undefined, and only a problem where the code using it runs: the creator's
204
+ // dunes game (2026-10-20) read THREE.ShaderChunk inside an onBeforeCompile
205
+ // callback, which WebGPU never calls, and ran; failing its build broke a game
206
+ // that worked. So such a member fails the build only where it certainly
207
+ // throws: called, constructed, read into or extended from, in code that runs
208
+ // whenever the game does (a module's top level, or createGame's own body in
209
+ // src/main.ts), outside any function, class, branch, loop or condition.
210
+ // Everywhere else it is a warning (nw_check, nw_logs). The scan below knows
211
+ // just enough of JS and TS to tell those apart, and says "may not run"
212
+ // whenever it is unsure: that costs a warning, never a build.
213
+
214
+ /** Contexts that hold statements: a condition seen in one lasts to its end. */
215
+ const STATEMENT = new Set(['top', 'fn', 'block', 'ctl', 'class', 'type'])
216
+ /** The parenthesised heads whose body is a branch or a loop. */
217
+ const CONTROL = new Set(['if', 'for', 'while', 'switch', 'catch', 'with'])
218
+ /** Keywords a block follows. */
219
+ const BLOCK_AFTER = new Set(['else', 'try', 'finally', 'do'])
220
+ /** Keywords after which an expression starts (a regex, an object literal). */
221
+ const EXPRESSION_AFTER = new Set(['return', 'typeof', 'instanceof', 'in', 'of', 'new', 'delete', 'void', 'throw', 'case', 'yield', 'await', 'extends'])
222
+ /** Keywords that read as a value (a `/` after them divides). */
223
+ const VALUE_WORDS = new Set(['this', 'super', 'null', 'true', 'false', 'undefined'])
224
+ const KEYWORDS = new Set([...CONTROL, ...BLOCK_AFTER, ...EXPRESSION_AFTER, ...VALUE_WORDS, 'function', 'class', 'const', 'let', 'var', 'export', 'import', 'default', 'break', 'continue', 'debugger', 'async', 'static', 'get', 'set'])
225
+ const ID_START = /[A-Za-z_$# -￿]/
226
+ const ID_PART = /[\w$ -￿]/
227
+ const SPACE = /\s/
228
+
229
+ /** The index of the next character that is not space or a comment. */
230
+ function nextSignificant(src, i) {
231
+ while (i < src.length) {
232
+ if (SPACE.test(src[i])) i++
233
+ else if (src[i] === '/' && src[i + 1] === '/') {
234
+ const end = src.indexOf('\n', i)
235
+ i = end < 0 ? src.length : end
236
+ } else if (src[i] === '/' && src[i + 1] === '*') {
237
+ const end = src.indexOf('*/', i + 2)
238
+ i = end < 0 ? src.length : end + 2
239
+ } else break
240
+ }
241
+ return i
242
+ }
243
+
244
+ /**
245
+ * For each index in `at` (sorted; where a namespace member's name starts in
246
+ * src), whether the code there runs whenever the module does: true only at a
247
+ * module's top level, or in createGame's own body when `entry`, with no
248
+ * function, class, branch, loop, parameter list or condition (?:, &&, ||,
249
+ * ??, ?.) between, as far as the scan can tell. A source it cannot follow
250
+ * answers false for all.
251
+ */
252
+ function runsOnLoad(src, at, entry) {
253
+ const stack = [{ kind: 'top', close: '', sure: true, cond: false }]
254
+ const seen = new Map()
255
+ let prev = ''
256
+ let prevType = ''
257
+ let prevPrev = ''
258
+ let lastParen = null
259
+ let pendingGame = 0
260
+ let pendingClass = 0
261
+ let returnType = 0
262
+ let confused = false
263
+ let next = 0
264
+ const innermost = () => stack[stack.length - 1]
265
+ const statement = () => {
266
+ for (let k = stack.length - 1; k > 0; k--) if (STATEMENT.has(stack[k].kind)) return stack[k]
267
+ return stack[0]
268
+ }
269
+ const token = (text, type) => {
270
+ prevPrev = prev
271
+ prev = text
272
+ prevType = type
273
+ }
274
+ const popArrows = () => {
275
+ while (innermost().kind === 'arrow') stack.pop()
276
+ }
277
+ const close = (ch) => {
278
+ popArrows()
279
+ if (stack.length < 2 || innermost().close !== ch) {
280
+ confused = true
281
+ return null
282
+ }
283
+ return stack.pop()
284
+ }
285
+ const endStatement = () => {
286
+ popArrows()
287
+ const f = innermost()
288
+ if (STATEMENT.has(f.kind)) f.cond = false
289
+ if (pendingGame === stack.length) pendingGame = 0
290
+ if (returnType === stack.length) returnType = 0
291
+ if (pendingClass === stack.length) pendingClass = 0
292
+ }
293
+ const condition = () => {
294
+ statement().cond = true
295
+ }
296
+ /** At a line break: does the statement end here (no ; needed)? */
297
+ const lineBreak = (i) => {
298
+ const f = innermost()
299
+ if (f.kind !== 'arrow' && !STATEMENT.has(f.kind)) return
300
+ const ends =
301
+ ['id', 'num', 'str', 'tmpl', 'regex'].includes(prevType) ||
302
+ [')', ']', '}', '++', '--'].includes(prev) ||
303
+ (prevType === 'kw' && (VALUE_WORDS.has(prev) || ['break', 'continue', 'return', 'debugger'].includes(prev)))
304
+ if (!ends) return
305
+ const j = nextSignificant(src, i)
306
+ const c = src[j]
307
+ if (c !== undefined && /[.?:([`,=+\-*/%&|^<>]/.test(c) && !((c === '+' || c === '-') && src[j + 1] === c)) return
308
+ if (/^(instanceof|in|as|satisfies)(?![\w$])/.test(src.slice(j, j + 12))) return
309
+ endStatement()
310
+ }
311
+ const reach = (i) => {
312
+ while (next < at.length && at[next] <= i) {
313
+ seen.set(at[next], { frames: stack.map((f) => ({ f, sure: f.sure, cond: f.cond })) })
314
+ next++
315
+ }
316
+ }
317
+ /** Scans a template literal's text from i: to its end, or into a ${. */
318
+ const template = (i) => {
319
+ while (i < src.length) {
320
+ const c = src[i]
321
+ if (c === '\\') i += 2
322
+ else if (c === '`') {
323
+ token('`', 'tmpl')
324
+ return i + 1
325
+ } else if (c === '$' && src[i + 1] === '{') {
326
+ stack.push({ kind: 'tmpl', close: '}', sure: true, cond: false })
327
+ token('${', 'punct')
328
+ return i + 2
329
+ } else i++
330
+ }
331
+ confused = true
332
+ return i
333
+ }
334
+
335
+ let i = 0
336
+ while (i < src.length) {
337
+ const c = src[i]
338
+ if (c === '\n') {
339
+ lineBreak(i + 1)
340
+ i++
341
+ continue
342
+ }
343
+ if (SPACE.test(c)) {
344
+ i++
345
+ continue
346
+ }
347
+ if (c === '/' && (src[i + 1] === '/' || src[i + 1] === '*')) {
348
+ const end = src[i + 1] === '/' ? src.indexOf('\n', i) : src.indexOf('*/', i + 2)
349
+ i = end < 0 ? src.length : src[i + 1] === '/' ? end : end + 2
350
+ continue
351
+ }
352
+ reach(i)
353
+ if (c === '"' || c === "'") {
354
+ let j = i + 1
355
+ while (j < src.length && src[j] !== c && src[j] !== '\n') j += src[j] === '\\' ? 2 : 1
356
+ i = j + 1
357
+ token('""', 'str')
358
+ continue
359
+ }
360
+ if (c === '`') {
361
+ i = template(i + 1)
362
+ continue
363
+ }
364
+ if (ID_START.test(c)) {
365
+ let j = i + 1
366
+ while (j < src.length && ID_PART.test(src[j])) j++
367
+ const word = src.slice(i, j)
368
+ i = j
369
+ const property = prev === '.' || prev === '?.'
370
+ if (!property) {
371
+ if (word === 'class') pendingClass = stack.length
372
+ if (word === 'createGame' && entry && stack.length === 1 && ['function', 'const', 'let', 'var'].includes(prev)) pendingGame = 1
373
+ if (word === 'else') {
374
+ const k = nextSignificant(src, i)
375
+ if (src[k] !== '{' && !/^if(?![\w$])/.test(src.slice(k, k + 3))) condition()
376
+ }
377
+ }
378
+ token(word, !property && KEYWORDS.has(word) ? 'kw' : 'id')
379
+ continue
380
+ }
381
+ if (/\d/.test(c) || (c === '.' && /\d/.test(src[i + 1] ?? ''))) {
382
+ let j = i + 1
383
+ while (j < src.length && /[\w.]/.test(src[j])) j++
384
+ i = j
385
+ token('0', 'num')
386
+ continue
387
+ }
388
+ if (c === '/') {
389
+ const regex = prev === '' || (prevType === 'punct' && ![')', ']', '}', '++', '--'].includes(prev)) || (prevType === 'kw' && EXPRESSION_AFTER.has(prev))
390
+ if (regex) {
391
+ let j = i + 1
392
+ let inClass = false
393
+ while (j < src.length && src[j] !== '\n') {
394
+ if (src[j] === '\\') j += 2
395
+ else if (src[j] === '[') (inClass = true), j++
396
+ else if (src[j] === ']') (inClass = false), j++
397
+ else if (src[j] === '/' && !inClass) break
398
+ else j++
399
+ }
400
+ j++
401
+ while (j < src.length && ID_PART.test(src[j])) j++
402
+ i = j
403
+ token('/re/', 'regex')
404
+ } else {
405
+ i++
406
+ token('/', 'punct')
407
+ }
408
+ continue
409
+ }
410
+ const two = src.slice(i, i + 2)
411
+ if (c === '(') {
412
+ // A function's parameter list: its defaults run only when it is called.
413
+ const params = prev === 'function' || (prevPrev === 'function' && prevType === 'id')
414
+ stack.push({ kind: 'paren', close: ')', sure: !params, cond: false, opener: prev, openerPrev: prevPrev, after: null })
415
+ token('(', 'punct')
416
+ i++
417
+ continue
418
+ }
419
+ if (c === ')') {
420
+ const f = close(')')
421
+ i++
422
+ if (f) {
423
+ const k = nextSignificant(src, i)
424
+ f.after = src[k] === '=' && src[k + 1] === '>' ? '=>' : src[k] ?? ''
425
+ f.control = CONTROL.has(f.opener) || (f.opener === 'await' && f.openerPrev === 'for')
426
+ // if (x) stmt, without braces: that statement is a branch.
427
+ if (f.control && f.opener !== 'switch' && f.opener !== 'catch' && f.after !== '{') condition()
428
+ if (!f.control && f.after === ':') returnType = stack.length
429
+ lastParen = f
430
+ }
431
+ token(')', 'punct')
432
+ continue
433
+ }
434
+ if (c === '[') {
435
+ stack.push({ kind: 'bracket', close: ']', sure: true, cond: false })
436
+ token('[', 'punct')
437
+ i++
438
+ continue
439
+ }
440
+ if (c === ']') {
441
+ close(']')
442
+ token(']', 'punct')
443
+ i++
444
+ continue
445
+ }
446
+ if (c === '{') {
447
+ const depth = stack.length
448
+ let kind
449
+ if (pendingClass === depth) {
450
+ kind = 'class'
451
+ pendingClass = 0
452
+ } else if (returnType === depth) {
453
+ // ): { a: T } is a type; the body follows a whole type.
454
+ if ([':', '|', '&', '<', ',', '(', '=>'].includes(prev)) kind = 'type'
455
+ else {
456
+ kind = 'fn'
457
+ returnType = 0
458
+ }
459
+ } else if (prev === '=>') kind = 'fn'
460
+ else if (prev === ')') kind = lastParen?.control ? 'ctl' : 'fn'
461
+ else if (BLOCK_AFTER.has(prev)) kind = 'ctl'
462
+ else if (prevType === 'kw' && EXPRESSION_AFTER.has(prev)) kind = 'object'
463
+ else if (prevType === 'id' || prevType === 'kw' || prev === '>' || prev === ']') kind = 'fn'
464
+ else if (prev === '' || prev === ';' || prev === '{' || prev === '}') kind = STATEMENT.has(innermost().kind) ? 'block' : 'object'
465
+ else if (prev === ':') kind = STATEMENT.has(innermost().kind) ? 'ctl' : 'object'
466
+ else kind = 'object'
467
+ let sure = kind === 'block' || kind === 'object'
468
+ if (kind === 'fn' && pendingGame === depth) {
469
+ sure = true
470
+ pendingGame = 0
471
+ }
472
+ stack.push({ kind, close: '}', sure, cond: false })
473
+ token('{', 'punct')
474
+ i++
475
+ continue
476
+ }
477
+ if (c === '}') {
478
+ popArrows()
479
+ if (innermost().kind === 'tmpl') {
480
+ stack.pop()
481
+ i = template(i + 1)
482
+ continue
483
+ }
484
+ close('}')
485
+ token('}', 'punct')
486
+ i++
487
+ continue
488
+ }
489
+ if (c === ';') {
490
+ endStatement()
491
+ token(';', 'punct')
492
+ i++
493
+ continue
494
+ }
495
+ if (c === ',') {
496
+ popArrows()
497
+ token(',', 'punct')
498
+ i++
499
+ continue
500
+ }
501
+ if (two === '=>') {
502
+ i += 2
503
+ token('=>', 'punct')
504
+ if (src[nextSignificant(src, i)] !== '{') stack.push({ kind: 'arrow', close: '', sure: false, cond: false })
505
+ continue
506
+ }
507
+ if (c === '?') {
508
+ // ?: and ?? and ?. all may skip what follows (and a TS a?: is taken as one too).
509
+ condition()
510
+ const len = src[i + 1] === '?' ? (src[i + 2] === '=' ? 3 : 2) : src[i + 1] === '.' && !/\d/.test(src[i + 2] ?? '') ? 2 : 1
511
+ token(len === 2 && src[i + 1] === '.' ? '?.' : '?', 'punct')
512
+ i += len
513
+ continue
514
+ }
515
+ if (two === '&&' || two === '||') {
516
+ condition()
517
+ i += src[i + 2] === '=' ? 3 : 2
518
+ token(two, 'punct')
519
+ continue
520
+ }
521
+ if (two === '++' || two === '--') {
522
+ i += 2
523
+ token(two, 'punct')
524
+ continue
525
+ }
526
+ if (c === '.' && src.slice(i, i + 3) === '...') {
527
+ i += 3
528
+ token('...', 'punct')
529
+ continue
530
+ }
531
+ i++
532
+ token(c, 'punct')
533
+ }
534
+ reach(Infinity)
535
+ if (confused || stack.length !== 1) return at.map(() => false)
536
+ return at.map((index) => {
537
+ const s = seen.get(index)
538
+ if (!s) return false
539
+ // A use inside parentheses that turned out to be parameters (a method's
540
+ // or an arrow's, or one with a return type) runs only when called.
541
+ return s.frames.every(({ f, sure, cond }) => sure && !cond && !(f.kind === 'paren' && ['{', '=>', ':'].includes(f.after)))
542
+ })
543
+ }
544
+
545
+ /** Whether `ns.name` (name at index `at`, `length` long), being undefined,
546
+ * throws where it is: called, constructed, read into or extended from.
547
+ * Also its text, `ns.name`, or null where it is not written that way. */
548
+ function memberUse(src, at, length) {
549
+ let k = at - 1
550
+ while (k >= 0 && SPACE.test(src[k])) k--
551
+ if (src[k] !== '.') return { throws: false, text: null }
552
+ k--
553
+ while (k >= 0 && SPACE.test(src[k])) k--
554
+ const nsEnd = k + 1
555
+ while (k >= 0 && ID_PART.test(src[k])) k--
556
+ const ns = src.slice(k + 1, nsEnd)
557
+ const text = ns ? `${ns}.${src.slice(at, at + length)}` : null
558
+ while (k >= 0 && SPACE.test(src[k])) k--
559
+ const before = /(?:^|[^\w$])(new|extends)$/.test(src.slice(Math.max(0, k - 8), k + 1))
560
+ let j = nextSignificant(src, at + length)
561
+ // TS's non-null assertion changes nothing at run time.
562
+ if (src[j] === '!' && src[j + 1] !== '=') j = nextSignificant(src, j + 1)
563
+ const after = src[j] === '(' || src[j] === '[' || src[j] === '`' || (src[j] === '.' && src[j + 1] !== '.')
564
+ return { throws: before || after, text }
565
+ }
566
+
567
+ /** The index of esbuild's location (line from 1, column from 0 in UTF-8 bytes) in src, or -1. */
568
+ function indexAt(src, line, column) {
569
+ let start = 0
570
+ for (let l = 1; l < line; l++) {
571
+ const nl = src.indexOf('\n', start)
572
+ if (nl < 0) return -1
573
+ start = nl + 1
574
+ }
575
+ const end = src.indexOf('\n', start)
576
+ const text = src.slice(start, end < 0 ? src.length : end)
577
+ return start + Buffer.from(text).subarray(0, column).toString().length
578
+ }
579
+
580
+ /** Each missing namespace member in `uses` ([{ location, module, name }]),
581
+ * as { line, fails }: fails where it certainly throws (above). */
582
+ function judgeMembers(uses, entry, projectRoot, table) {
583
+ const byFile = new Map()
584
+ for (const u of uses) {
585
+ const file = u.location?.file ? path.resolve(projectRoot, u.location.file) : null
586
+ if (!byFile.has(file)) byFile.set(file, [])
587
+ byFile.get(file).push(u)
588
+ }
589
+ const judged = []
590
+ for (const [file, list] of byFile) {
591
+ let src = null
592
+ try {
593
+ src = file ? fs.readFileSync(file, 'utf8') : null
594
+ } catch {
595
+ src = null
596
+ }
597
+ const at = list.map((u) => (src ? indexAt(src, u.location.line, u.location.column) : -1))
598
+ const valid = [...new Set(at.filter((x) => x >= 0))].sort((a, b) => a - b)
599
+ const runs = src ? runsOnLoad(src, valid, file === path.resolve(entry)) : []
600
+ const runsAt = new Map(valid.map((x, k) => [x, runs[k]]))
601
+ list.forEach((u, k) => {
602
+ const use = at[k] >= 0 ? memberUse(src, at[k], u.location.length || u.name.length) : { throws: false, text: null }
603
+ const fails = runsAt.get(at[k]) === true && use.throws
604
+ judged.push({ fails, line: missingImport(u.location, u.module, u.name, table, projectRoot, fails ? null : use.text ?? `"${u.name}"`) })
605
+ })
606
+ }
607
+ return judged
608
+ }
609
+
610
+ /** The game bundled again against stand-ins for the shared modules that
611
+ * export exactly their names: { errors, warnings }, the lines for each
612
+ * import that is not there. A named import is an error; a namespace member
613
+ * is one only where it certainly throws, and else a warning. */
614
+ async function checkSharedImports(entry, projectRoot) {
615
+ const table = await sharedExports()
616
+ if (!table) return { errors: [], warnings: [] }
617
+ const stub = (module) => {
618
+ const names = [...(table.sets[module] ?? [])].filter((n) => n !== 'default')
619
+ // Any name, reserved words too, can be exported this way. The default
620
+ // import works at run time (the shim's module.exports), so it stays.
621
+ return `const v = 0\nexport { ${names.map((n) => `v as ${n}`).join(', ')} }\nexport default {}\n`
622
+ }
623
+ const SHIM = /^No matching export in "nw-check:([^"]+)" for import "([^"]+)"$/
624
+ const MEMBER = /^Import "([^"]+)" will always be undefined because there is no matching export in "nw-check:([^"]+)"$/
625
+ let errors = []
626
+ let warnings = []
627
+ try {
628
+ const result = await lib().build({
629
+ entryPoints: [entry],
630
+ bundle: true,
631
+ format: 'esm',
632
+ write: false,
633
+ absWorkingDir: projectRoot,
634
+ target: 'es2022',
635
+ logLevel: 'silent',
636
+ plugins: [
637
+ {
638
+ name: 'nw-check-shared-exports',
639
+ setup(b) {
640
+ b.onResolve({ filter: SHARED }, (args) => ({ path: args.path, namespace: 'nw-check' }))
641
+ b.onLoad({ filter: /.*/, namespace: 'nw-check' }, (args) => ({ contents: stub(args.path), loader: 'js' }))
642
+ },
643
+ },
644
+ ],
645
+ })
646
+ warnings = result.warnings ?? []
647
+ } catch (err) {
648
+ errors = err.errors ?? []
649
+ warnings = err.warnings ?? []
650
+ }
651
+ const failing = []
652
+ for (const e of errors) {
653
+ const m = SHIM.exec(e.text)
654
+ if (m) failing.push(missingImport(e.location, m[1], m[2], table, projectRoot))
655
+ }
656
+ const members = []
657
+ for (const w of warnings) {
658
+ const m = MEMBER.exec(w.text)
659
+ if (m) members.push({ location: w.location, module: m[2], name: m[1] })
660
+ }
661
+ const judged = judgeMembers(members, entry, projectRoot, table)
662
+ const warning = []
663
+ for (const j of judged) (j.fails ? failing : warning).push(j.line)
664
+ return { errors: [...new Set(failing)], warnings: [...new Set(warning)] }
665
+ }
666
+
667
+ /** esbuild's own message, with what a game can import said where it could not find a module. */
668
+ function describeError(e, projectRoot) {
669
+ // esbuild reports paths already relative to absWorkingDir; resolving one
670
+ // of those against path.relative's cwd produced a ../../.. path pointing
671
+ // at a file in the studio's own source, which is where it then sent
672
+ // whoever was trying to fix the error.
673
+ const loc = e.location ? `${relativeFile(e.location.file, projectRoot)}:${e.location.line}:${e.location.column}` : ''
674
+ let text = e.text
675
+ const missing = /^Could not resolve "([^"]+)"/.exec(text)
676
+ if (missing && !/^[./]/.test(missing[1])) {
677
+ text = /^three\//.test(missing[1])
678
+ ? `"${missing[1]}" is not one of the modules a game gets: the studio gives it three (three/webgpu), three/tsl and @nowhere/sdk, and none of three's addons. Write it with those, or copy the addon's file into src/ and import it from there.`
679
+ : `Could not resolve "${missing[1]}": a game can import its own files under src/, three, three/webgpu, three/tsl and @nowhere/sdk, and nothing else is installed for it.`
680
+ }
681
+ return `${loc} ${text}`.trim()
682
+ }
683
+
684
+ // ---- WebGL habits in a game's own source
685
+ //
686
+ // three r186 draws with WebGPU, where a material is a TSL node graph. What
687
+ // models write from years of WebGL three.js (an onBeforeCompile patch, a
688
+ // ShaderMaterial, an EffectComposer, GLSL strings) builds and runs, and then
689
+ // does nothing at all, or draws a flat black material in its place, with
690
+ // nothing said. So the build reads the game's own files for those habits and
691
+ // warns with the TSL way, in the same words as the SDK's material watch
692
+ // (WEBGL_ONLY in packages/sdk/src/diagnose.ts; shader-check holds the two
693
+ // tables equal). They are warnings: the game still builds, as it did.
694
+
695
+ /** The TSL way for each habit, as the SDK's WEBGL_ONLY says it. */
696
+ const WEBGL_ONLY = {
697
+ onBeforeCompile:
698
+ 'use the node slots of a Mesh*NodeMaterial (colorNode, normalNode, positionNode, emissiveNode, roughnessNode, opacityNode)',
699
+ ShaderMaterial: 'use MeshBasicNodeMaterial with colorNode, or NodeMaterial with fragmentNode and vertexNode',
700
+ ShaderChunk: 'write TSL functions: there is no GLSL source to patch',
701
+ gl_FragColor: 'write TSL nodes (Fn, vec3, mix) instead of GLSL strings',
702
+ EffectComposer: "set the planet's look in game.config.json with look_apply (tone mapping, bloom, AO, fog, grade, vignette)",
703
+ customProgramCacheKey: 'remove it: node materials rebuild when their nodes change',
704
+ }
705
+ const capital = (s) => s.charAt(0).toUpperCase() + s.slice(1)
706
+
707
+ /** The habits looked for, each with the sentence said where it is. */
708
+ const WEBGL_HABITS = [
709
+ {
710
+ habit: 'onBeforeCompile',
711
+ pattern: /\.onBeforeCompile\s*=/g,
712
+ say: () => `sets material.onBeforeCompile, which WebGPU never calls, so its GLSL patch does nothing. ${capital(WEBGL_ONLY.onBeforeCompile)}.`,
713
+ },
714
+ {
715
+ habit: 'ShaderMaterial',
716
+ pattern: /new\s+(?:[A-Za-z_$][\w$]*\.)?(?:Raw)?ShaderMaterial\s*\(/g,
717
+ say: (m) => `makes a ${/RawShaderMaterial/.test(m) ? 'RawShaderMaterial' : 'ShaderMaterial'}: WebGPU compiles no GLSL, so it is drawn flat black. ${capital(WEBGL_ONLY.ShaderMaterial)}.`,
718
+ },
719
+ {
720
+ habit: 'EffectComposer',
721
+ pattern: /\b(?:EffectComposer|RenderPass|ShaderPass|UnrealBloomPass)\b/g,
722
+ say: (m) => `uses ${m}, which does nothing here: the host draws the planet's post-processing. ${capital(WEBGL_ONLY.EffectComposer)}.`,
723
+ },
724
+ {
725
+ habit: 'customProgramCacheKey',
726
+ pattern: /\bcustomProgramCacheKey\b/g,
727
+ say: () => `sets customProgramCacheKey, which only WebGL reads. ${capital(WEBGL_ONLY.customProgramCacheKey)}.`,
728
+ },
729
+ {
730
+ habit: 'gl_FragColor',
731
+ pattern: /gl_FragColor|gl_Position|#include\s*<\w+>/g,
732
+ say: (m) => `has GLSL (${m}), which WebGPU never compiles. ${capital(WEBGL_ONLY.gl_FragColor)}.`,
733
+ },
734
+ ]
735
+ /** At most this many habit warnings for one build. */
736
+ const WEBGL_WARNINGS_MAX = 20
737
+ const SOURCE_FILE = /\.(?:[cm]?[jt]sx?)$/
738
+
739
+ /**
740
+ * src with its comments blanked out (each character a space, line breaks
741
+ * kept, so every line and column stays where it was) and its strings and
742
+ * template literals kept: GLSL lives in strings. A `/` is a regex where an
743
+ * expression may start (the same rule runsOnLoad uses).
744
+ */
745
+ function blankComments(src) {
746
+ const out = src.split('')
747
+ const blank = (from, to) => {
748
+ for (let k = from; k < to; k++) if (out[k] !== '\n') out[k] = ' '
749
+ }
750
+ // Template literals nest through ${ }: the depth of braces inside each.
751
+ const templates = []
752
+ let i = 0
753
+ let prev = ''
754
+ while (i < src.length) {
755
+ const c = src[i]
756
+ if (templates.length > 0 && templates[templates.length - 1] === 0) {
757
+ // Inside a template literal's text.
758
+ if (c === '\\') i += 2
759
+ else if (c === '`') {
760
+ templates.pop()
761
+ i++
762
+ prev = '"'
763
+ } else if (c === '$' && src[i + 1] === '{') {
764
+ templates[templates.length - 1] = 1
765
+ i += 2
766
+ prev = '{'
767
+ } else i++
768
+ continue
769
+ }
770
+ if (c === '/' && src[i + 1] === '/') {
771
+ const end = src.indexOf('\n', i)
772
+ blank(i, end < 0 ? src.length : end)
773
+ i = end < 0 ? src.length : end
774
+ continue
775
+ }
776
+ if (c === '/' && src[i + 1] === '*') {
777
+ const end = src.indexOf('*/', i + 2)
778
+ blank(i, end < 0 ? src.length : end + 2)
779
+ i = end < 0 ? src.length : end + 2
780
+ continue
781
+ }
782
+ if (c === '"' || c === "'") {
783
+ let j = i + 1
784
+ while (j < src.length && src[j] !== c && src[j] !== '\n') j += src[j] === '\\' ? 2 : 1
785
+ i = j + 1
786
+ prev = '"'
787
+ continue
788
+ }
789
+ if (c === '`') {
790
+ templates.push(0)
791
+ i++
792
+ continue
793
+ }
794
+ if (templates.length > 0 && (c === '{' || c === '}')) {
795
+ // Braces inside a ${ }: at 0 again, the template's text goes on.
796
+ templates[templates.length - 1] += c === '{' ? 1 : -1
797
+ i++
798
+ prev = c
799
+ continue
800
+ }
801
+ if (c === '/') {
802
+ const regex = prev === '' || /[(,=:[!&|?{};+\-*%<>~^]$/.test(prev) || /^(return|typeof|case|do|else|in|of|new|delete|void|throw|yield|await)$/.test(prev)
803
+ if (regex) {
804
+ let j = i + 1
805
+ let inClass = false
806
+ while (j < src.length && src[j] !== '\n') {
807
+ if (src[j] === '\\') j += 2
808
+ else if (src[j] === '[') (inClass = true), j++
809
+ else if (src[j] === ']') (inClass = false), j++
810
+ else if (src[j] === '/' && !inClass) break
811
+ else j++
812
+ }
813
+ i = j + 1
814
+ prev = 'x'
815
+ continue
816
+ }
817
+ }
818
+ if (ID_START.test(c)) {
819
+ let j = i + 1
820
+ while (j < src.length && ID_PART.test(src[j])) j++
821
+ prev = src.slice(i, j)
822
+ i = j
823
+ continue
824
+ }
825
+ if (!SPACE.test(c)) prev = c
826
+ i++
827
+ }
828
+ return out.join('')
829
+ }
830
+
831
+ /**
832
+ * Warnings for the WebGL habits in the project's own files that esbuild
833
+ * bundled (`inputs`: the metafile's, relative to projectRoot; only those
834
+ * under src/), the entry's first: one per file, line and habit, at most
835
+ * WEBGL_WARNINGS_MAX, as "src/x.ts:L:C <what it does here, and the TSL way>".
836
+ * GLSL strings in a file that already patches a material (onBeforeCompile,
837
+ * ShaderMaterial) are that patch's body, said once by its warning.
838
+ */
839
+ function webglOnlyWarnings(entry, projectRoot, inputs) {
840
+ const mainRel = path.relative(projectRoot, entry).split(path.sep).join('/')
841
+ const files = [...new Set(inputs.map((f) => String(f).split(path.sep).join('/')))]
842
+ .filter((f) => f.startsWith('src/') && SOURCE_FILE.test(f))
843
+ .sort((a, b) => (a === mainRel ? -1 : b === mainRel ? 1 : a < b ? -1 : a > b ? 1 : 0))
844
+ const warnings = []
845
+ for (const rel of files) {
846
+ let src
847
+ try {
848
+ src = fs.readFileSync(path.join(projectRoot, rel), 'utf8')
849
+ } catch {
850
+ continue
851
+ }
852
+ const text = blankComments(src)
853
+ const lineStarts = [0]
854
+ for (let k = 0; k < text.length; k++) if (text[k] === '\n') lineStarts.push(k + 1)
855
+ const where = (index) => {
856
+ let lo = 0
857
+ let hi = lineStarts.length - 1
858
+ while (lo < hi) {
859
+ const mid = (lo + hi + 1) >> 1
860
+ if (lineStarts[mid] <= index) lo = mid
861
+ else hi = mid - 1
862
+ }
863
+ // Columns from 0, as esbuild's (the import lines above) are.
864
+ return { line: lo + 1, column: index - lineStarts[lo] }
865
+ }
866
+ const found = []
867
+ const seen = new Set()
868
+ for (const h of WEBGL_HABITS) {
869
+ for (const m of text.matchAll(h.pattern)) {
870
+ const at = where(m.index)
871
+ const key = `${at.line}:${h.habit}`
872
+ if (seen.has(key)) continue
873
+ seen.add(key)
874
+ found.push({ habit: h.habit, index: m.index, line: `${rel}:${at.line}:${at.column} ${h.say(m[0])}` })
875
+ }
876
+ }
877
+ const patched = found.some((f) => f.habit === 'onBeforeCompile' || f.habit === 'ShaderMaterial')
878
+ for (const f of found.sort((a, b) => a.index - b.index)) {
879
+ if (patched && f.habit === 'gl_FragColor') continue
880
+ warnings.push(f.line)
881
+ if (warnings.length >= WEBGL_WARNINGS_MAX) return warnings
882
+ }
883
+ }
884
+ return warnings
885
+ }
886
+
887
+ /**
888
+ * @param {string} projectRoot
889
+ * @param {{ sourcemap?: boolean }} [options] sourcemap: an inline map, the
890
+ * mappings only (no sources), so the studio can say "src/tracks.ts:151"
891
+ * for an error a game throws (apps/studio/src/three/gameErrors.ts). The
892
+ * preview's builds only: a published bundle has no use for one.
893
+ * @returns {Promise<{ok:true, code:string, warnings?:string[]} | {ok:false, error:string}>}
894
+ * warnings: a missing namespace member where it may never run, then the
895
+ * WebGL habits in the game's own files (both above).
896
+ */
897
+ async function buildGame(projectRoot, { sourcemap = false } = {}) {
898
+ const entry = path.join(projectRoot, 'src', 'main.ts')
899
+ let code
900
+ let inputs = []
901
+ try {
902
+ const result = await lib().build({
903
+ entryPoints: [entry],
904
+ bundle: true,
905
+ format: 'esm',
906
+ write: false,
907
+ absWorkingDir: projectRoot,
908
+ target: 'es2022',
909
+ logLevel: 'silent',
910
+ // Which of the project's files went in: what webglOnlyWarnings reads.
911
+ metafile: true,
912
+ ...(sourcemap ? { sourcemap: 'inline', sourcesContent: false } : {}),
913
+ plugins: [
914
+ {
915
+ name: 'nw-shared-modules',
916
+ setup(b) {
917
+ b.onResolve({ filter: SHARED }, (args) => ({ path: args.path, namespace: 'nw-shared' }))
918
+ b.onLoad({ filter: /.*/, namespace: 'nw-shared' }, (args) => ({
919
+ contents: `module.exports = globalThis.__nw_modules[${JSON.stringify(args.path)}]`,
920
+ loader: 'js',
921
+ }))
922
+ },
923
+ },
924
+ ],
925
+ })
926
+ code = result.outputFiles[0].text
927
+ inputs = Object.keys(result.metafile?.inputs ?? {})
928
+ } catch (err) {
929
+ const messages = err.errors?.map((e) => describeError(e, projectRoot))
930
+ return { ok: false, error: messages?.join('\n') || err.message }
931
+ }
932
+ let checked = { errors: [], warnings: [] }
933
+ try {
934
+ checked = await checkSharedImports(entry, projectRoot)
935
+ } catch {
936
+ // A check that cannot run is no reason to refuse a build that passed.
937
+ checked = { errors: [], warnings: [] }
938
+ }
939
+ if (checked.errors.length > 0) return { ok: false, error: checked.errors.join('\n') }
940
+ let habits = []
941
+ try {
942
+ habits = webglOnlyWarnings(entry, projectRoot, inputs)
943
+ } catch {
944
+ // Like the check above: never a reason to refuse a build that passed.
945
+ habits = []
946
+ }
947
+ // What may throw later, and what does nothing on WebGPU, for nw_check and
948
+ // nw_logs to say; the game builds.
949
+ const warnings = [...checked.warnings, ...habits]
950
+ return warnings.length > 0 ? { ok: true, code, warnings } : { ok: true, code }
951
+ }
952
+
953
+ module.exports = { buildGame, readRuntimeExports, webglOnlyWarnings, EXPORTS_FILE, WEBGL_ONLY }