castle-web-cli 0.4.237 → 0.4.238

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 (216) hide show
  1. package/dist/bundle.d.ts +24 -0
  2. package/dist/bundle.js +447 -4
  3. package/dist/bundleLatin1.d.ts +6 -0
  4. package/dist/bundleLatin1.js +333 -0
  5. package/dist/castle-host/host.d.ts +10 -1
  6. package/dist/castle-host/host.js +78 -9
  7. package/dist/castleJson.d.ts +2 -0
  8. package/dist/castleJson.js +1 -0
  9. package/dist/deckExports.d.ts +35 -0
  10. package/dist/deckExports.js +365 -0
  11. package/dist/importCheckHook.d.ts +1 -0
  12. package/dist/importCheckHook.js +1 -1
  13. package/dist/index.js +5 -0
  14. package/dist/init.js +2 -1
  15. package/dist/save-deck.js +4 -0
  16. package/kits/base/castle.json +1 -1
  17. package/kits/base/sdk/README.md +47 -0
  18. package/kits/base/sdk/castle.d.ts +3 -1
  19. package/kits/base/sdk/castle.js +1 -0
  20. package/kits/base/sdk/commands.d.ts +25 -1
  21. package/kits/base/sdk/commands.js +29 -1
  22. package/kits/base/sdk/hub.d.ts +17 -0
  23. package/kits/base/sdk/hub.js +33 -9
  24. package/kits/base/sdk/localCache.d.ts +27 -0
  25. package/kits/base/sdk/localCache.js +115 -0
  26. package/kits/base/sdk/localCacheStore.d.ts +15 -0
  27. package/kits/base/sdk/localCacheStore.js +358 -0
  28. package/kits/base/sdk/transport.d.ts +1 -0
  29. package/kits/base/sdk/transport.js +4 -5
  30. package/kits/hub-game/CLAUDE.md +22 -2
  31. package/kits/hub-game/castle.json +4 -1
  32. package/kits/hub-game/code/client/act.js +66 -91
  33. package/kits/hub-game/code/client/actCore.js +134 -0
  34. package/kits/hub-game/code/client/car.js +35 -0
  35. package/kits/hub-game/code/client/chrome.js +207 -381
  36. package/kits/hub-game/code/client/crowdNames.js +2 -2
  37. package/kits/hub-game/code/client/emoteWheel.js +109 -0
  38. package/kits/hub-game/code/client/hats.js +2 -0
  39. package/kits/hub-game/code/client/hookLayer.js +99 -48
  40. package/kits/hub-game/code/client/hostGo.js +77 -0
  41. package/kits/hub-game/code/client/hubControls.js +125 -0
  42. package/kits/hub-game/code/client/hubEntry.js +187 -0
  43. package/kits/hub-game/code/client/hudSurface.js +148 -0
  44. package/kits/hub-game/code/client/hudTree.js +96 -0
  45. package/kits/hub-game/code/client/idle.js +59 -13
  46. package/kits/hub-game/code/client/invites.js +13 -4
  47. package/kits/hub-game/code/client/menuIcons.js +8 -0
  48. package/kits/hub-game/code/client/noTrips.js +38 -0
  49. package/kits/hub-game/code/client/qualityEntry.js +6 -1
  50. package/kits/hub-game/code/client/rehello.js +3 -1
  51. package/kits/hub-game/code/client/riders.js +26 -0
  52. package/kits/hub-game/code/client/role.js +79 -0
  53. package/kits/hub-game/code/client/safeLayout.js +32 -3
  54. package/kits/hub-game/code/client/sound.js +10 -3
  55. package/kits/hub-game/code/client/soundscape.js +2 -2
  56. package/kits/hub-game/code/client/soundscapeAmbience.js +38 -8
  57. package/kits/hub-game/code/client/soundscapeBaked.js +24 -5
  58. package/kits/hub-game/code/client/soundscapeCues.js +2 -1
  59. package/kits/hub-game/code/client/state.js +19 -0
  60. package/kits/hub-game/code/client/stuck.js +2 -1
  61. package/kits/hub-game/code/client/talkSurface.js +178 -0
  62. package/kits/hub-game/code/client/talkTree.js +238 -0
  63. package/kits/hub-game/code/client/tiers.js +8 -5
  64. package/kits/hub-game/code/client/uiDom.js +600 -0
  65. package/kits/hub-game/code/client/uiTree.js +359 -0
  66. package/kits/hub-game/code/client/vehicle.js +154 -0
  67. package/kits/hub-game/code/client/wear.js +27 -5
  68. package/kits/hub-game/code/client/worldLabels.js +3 -2
  69. package/kits/hub-game/code/client/yours.js +10 -3
  70. package/kits/hub-game/code/server/actors.js +4 -3
  71. package/kits/hub-game/code/server/analytics.js +56 -6
  72. package/kits/hub-game/code/server/decor.js +56 -16
  73. package/kits/hub-game/code/server/hub.js +258 -46
  74. package/kits/hub-game/code/server/idle.js +118 -5
  75. package/kits/hub-game/code/server/manifest.js +46 -4
  76. package/kits/hub-game/code/server/npcs.js +4 -2
  77. package/kits/hub-game/code/server/players.js +3 -0
  78. package/kits/hub-game/code/server/role.js +142 -0
  79. package/kits/hub-game/code/server/standing.js +6 -4
  80. package/kits/hub-game/code/server/vehicle.js +126 -0
  81. package/kits/hub-game/code/shared/car.js +52 -0
  82. package/kits/hub-game/code/shared/deckFlags.js +34 -0
  83. package/kits/hub-game/code/shared/deviceClass.js +39 -0
  84. package/kits/hub-game/code/shared/expression.js +9 -0
  85. package/kits/hub-game/code/systems/hub.js +272 -84
  86. package/kits/hub-game/docs/analytics.md +11 -2
  87. package/kits/hub-game/docs/contract.md +352 -14
  88. package/kits/hub-game/docs/vehicle-preset.md +132 -0
  89. package/kits/hub-game/models/hats/baker-cap.pxmodel +89 -0
  90. package/kits/hub-game/models/hats/chef-toque.pxmodel +60 -0
  91. package/kits/hub-game/models/hats/delivery-cap.pxmodel +105 -0
  92. package/kits/hub-game/models/hats/fire-helmet.pxmodel +87 -0
  93. package/kits/hub-game/models/hats/hard-hat.pxmodel +71 -0
  94. package/kits/hub-game/models/hats/nurse-cap.pxmodel +61 -0
  95. package/kits/hub-game/models/hats/police-cap.pxmodel +105 -0
  96. package/kits/hub-game/models/hats/teacher-beret.pxmodel +52 -0
  97. package/kits/hub-game/models/role/square/top-apron.pxmodel +109 -0
  98. package/kits/hub-game/models/role/square/top-cardigan.pxmodel +141 -0
  99. package/kits/hub-game/models/role/square/top-coat.pxmodel +157 -0
  100. package/kits/hub-game/models/role/square/top-scrubs.pxmodel +93 -0
  101. package/kits/hub-game/models/role/square/top-tabard.pxmodel +109 -0
  102. package/kits/hub-game/models/role/square/top-vest.pxmodel +109 -0
  103. package/kits/hub-game/models/role/tool-bag.pxmodel +75 -0
  104. package/kits/hub-game/models/role/tool-bell.pxmodel +71 -0
  105. package/kits/hub-game/models/role/tool-hose.pxmodel +60 -0
  106. package/kits/hub-game/models/role/tool-parcel.pxmodel +61 -0
  107. package/kits/hub-game/models/role/tool-torch.pxmodel +55 -0
  108. package/kits/hub-game/models/role/tool-tray.pxmodel +75 -0
  109. package/kits/hub-game/models/role/top-apron.pxmodel +70 -0
  110. package/kits/hub-game/models/role/top-cardigan.pxmodel +102 -0
  111. package/kits/hub-game/models/role/top-coat.pxmodel +79 -0
  112. package/kits/hub-game/models/role/top-scrubs.pxmodel +54 -0
  113. package/kits/hub-game/models/role/top-tabard.pxmodel +70 -0
  114. package/kits/hub-game/models/role/top-vest.pxmodel +70 -0
  115. package/kits/hub-game/package-lock.json +1 -1
  116. package/kits/hub-game/package.json +1 -1
  117. package/kits/hub-game/scripts/check.mjs +7 -4
  118. package/kits/hub-game/scripts/fixtures/car-vectors.json +279 -0
  119. package/kits/hub-game/scripts/fixtures/decor-keyless-draw.json +2 -1
  120. package/kits/hub-game/scripts/fixtures/hud-surface.json +670 -0
  121. package/kits/hub-game/scripts/fixtures/talk-surface.json +3930 -0
  122. package/kits/hub-game/scripts/gen-hats.mjs +46 -2
  123. package/kits/hub-game/scripts/gen-role.mjs +80 -0
  124. package/kits/hub-game/scripts/test-act-core.mjs +167 -0
  125. package/kits/hub-game/scripts/test-actions-client.mjs +34 -0
  126. package/kits/hub-game/scripts/test-actors.mjs +48 -0
  127. package/kits/hub-game/scripts/test-analytics.mjs +99 -5
  128. package/kits/hub-game/scripts/test-apply-deck.mjs +122 -0
  129. package/kits/hub-game/scripts/test-back-visibility.mjs +3 -1
  130. package/kits/hub-game/scripts/test-ballot.mjs +2 -0
  131. package/kits/hub-game/scripts/test-car.mjs +43 -0
  132. package/kits/hub-game/scripts/test-decor-client.mjs +2 -1
  133. package/kits/hub-game/scripts/test-decor.mjs +77 -0
  134. package/kits/hub-game/scripts/test-device-class.mjs +83 -0
  135. package/kits/hub-game/scripts/test-emote-wheel.mjs +374 -0
  136. package/kits/hub-game/scripts/test-hats.mjs +5 -4
  137. package/kits/hub-game/scripts/test-host-go.mjs +265 -0
  138. package/kits/hub-game/scripts/test-hub-controls.mjs +108 -0
  139. package/kits/hub-game/scripts/test-hub-entry.mjs +531 -0
  140. package/kits/hub-game/scripts/test-hub-ops.mjs +75 -0
  141. package/kits/hub-game/scripts/test-hud-clear.mjs +12 -2
  142. package/kits/hub-game/scripts/test-hud-rate.mjs +6 -2
  143. package/kits/hub-game/scripts/test-hud-surface.mjs +272 -0
  144. package/kits/hub-game/scripts/test-idle.mjs +347 -1
  145. package/kits/hub-game/scripts/test-interest-cells.mjs +8 -1
  146. package/kits/hub-game/scripts/test-invites-client.mjs +42 -1
  147. package/kits/hub-game/scripts/test-manifest.mjs +30 -0
  148. package/kits/hub-game/scripts/test-no-trips.mjs +42 -0
  149. package/kits/hub-game/scripts/test-placement-cache.mjs +1 -1
  150. package/kits/hub-game/scripts/test-quality.mjs +13 -0
  151. package/kits/hub-game/scripts/test-rehello.mjs +258 -3
  152. package/kits/hub-game/scripts/test-resume-pose-server.mjs +203 -0
  153. package/kits/hub-game/scripts/test-resync.mjs +183 -0
  154. package/kits/hub-game/scripts/test-role-client.mjs +421 -0
  155. package/kits/hub-game/scripts/test-role.mjs +350 -0
  156. package/kits/hub-game/scripts/test-safe-layout.mjs +50 -1
  157. package/kits/hub-game/scripts/test-soundscape.mjs +124 -7
  158. package/kits/hub-game/scripts/test-standing.mjs +15 -1
  159. package/kits/hub-game/scripts/test-talk-surface.mjs +296 -0
  160. package/kits/hub-game/scripts/test-tiers.mjs +13 -0
  161. package/kits/hub-game/scripts/test-ui-dom-dom.mjs +96 -0
  162. package/kits/hub-game/scripts/test-ui-tree.mjs +711 -0
  163. package/kits/hub-game/scripts/test-vehicle-client.mjs +159 -0
  164. package/kits/hub-game/scripts/test-vehicle.mjs +135 -0
  165. package/kits/hub-game/scripts/test-yours.mjs +33 -0
  166. package/kits/hub-game/tools/hubScene/export.mjs +613 -0
  167. package/kits/hub-game/tools/hubScene/hubdata.mjs +921 -0
  168. package/kits/hub-game/tools/hubScene/merge-root.mjs +39 -0
  169. package/kits/hub-game/tools/hubScene/nodeworld.mjs +227 -0
  170. package/kits/hub-game/tools/hubScene/test/export-fixture.mjs +798 -0
  171. package/kits/hub-game/tools/hubScene/test/fixture.json +637 -0
  172. package/kits/hub-game/tools/hubScene/test/paint-export.mjs +40 -0
  173. package/kits/hub-game/tools/hubScene/test/upload.test.mjs +655 -0
  174. package/kits/hub-game/tools/hubScene/upload.mjs +636 -0
  175. package/kits/hub-game/tools/hubScene/validate-manifest.mjs +291 -0
  176. package/kits/multiplayer-3d/castle.json +4 -4
  177. package/kits/multiplayer-3d/code/client/resumeGate.js +30 -2
  178. package/kits/multiplayer-3d/code/client/steer.js +3 -1
  179. package/kits/multiplayer-3d/code/systems/multiplayer.js +30 -2
  180. package/kits/multiplayer-3d/package-lock.json +1 -1
  181. package/kits/multiplayer-3d/scripts/test-resume-gate.mjs +74 -2
  182. package/kits/physics-3d/CLAUDE.md +1 -1
  183. package/kits/physics-3d/behaviors/Player.jsx +37 -27
  184. package/kits/physics-3d/castle.json +2 -2
  185. package/kits/physics-3d/docs/engine-geometry-memory.md +23 -0
  186. package/kits/physics-3d/engine3d/memoryprofile.js +17 -0
  187. package/kits/physics-3d/engine3d/playerRun.js +6 -1
  188. package/kits/physics-3d/engine3d/pxmodel.js +6 -1
  189. package/kits/physics-3d/engine3d/world3d.js +6 -3
  190. package/kits/physics-3d/package.json +1 -1
  191. package/kits/physics-3d/play/behaviors/Player.js +40 -28
  192. package/kits/physics-3d/scripts/test-memory-profile.mjs +237 -0
  193. package/kits/physics-3d/systems/physics3d.js +5 -2
  194. package/kits/real-time/castle.json +2 -2
  195. package/kits/real-time/code/client/messages.js +5 -0
  196. package/kits/real-time/code/server/session.js +28 -1
  197. package/kits/real-time/package-lock.json +1 -1
  198. package/package.json +5 -4
  199. package/vendor/three/LICENSE +21 -0
  200. package/vendor/three/build/three.core.js +58773 -0
  201. package/vendor/three/build/three.module.js +18251 -0
  202. package/vendor/three/examples/jsm/controls/OrbitControls.js +1860 -0
  203. package/vendor/three/examples/jsm/controls/TransformControls.js +1918 -0
  204. package/vendor/three/examples/jsm/exporters/GLTFExporter.js +3595 -0
  205. package/vendor/three/examples/jsm/geometries/RoundedBoxGeometry.js +216 -0
  206. package/vendor/three/examples/jsm/math/MeshSurfaceSampler.js +315 -0
  207. package/vendor/three/examples/jsm/postprocessing/EffectComposer.js +363 -0
  208. package/vendor/three/examples/jsm/postprocessing/MaskPass.js +195 -0
  209. package/vendor/three/examples/jsm/postprocessing/OutputPass.js +139 -0
  210. package/vendor/three/examples/jsm/postprocessing/Pass.js +191 -0
  211. package/vendor/three/examples/jsm/postprocessing/RenderPass.js +183 -0
  212. package/vendor/three/examples/jsm/postprocessing/ShaderPass.js +135 -0
  213. package/vendor/three/examples/jsm/shaders/CopyShader.js +52 -0
  214. package/vendor/three/examples/jsm/shaders/OutputShader.js +103 -0
  215. package/vendor/three/examples/jsm/utils/BufferGeometryUtils.js +1435 -0
  216. package/vendor/three/package.json +134 -0
package/dist/bundle.d.ts CHANGED
@@ -1,4 +1,28 @@
1
1
  import { type Plugin } from 'vite';
2
+ export declare class InlineAssets {
3
+ private readonly token;
4
+ private readonly marker;
5
+ private readonly payloads;
6
+ private readonly indexOf;
7
+ /** A chunk evaluates a marker: this build is void, and the deck needs its URIs in rolldown. */
8
+ evaluated: boolean;
9
+ /** Swaps payloads for markers in the deck's own build (a worker keeps its URIs). */
10
+ plugin(): Plugin;
11
+ private markerFor;
12
+ /** The built text with every marker's payload back in place. */
13
+ restore(text: string): string;
14
+ }
15
+ /**
16
+ * True if, in this chunk (not yet minified), the minifier provably cannot
17
+ * compute with any marker. A marker must be the value of a `var` the chunk
18
+ * declares once and gives it only once (how rolldown writes an asset module's
19
+ * export), or be used as that var's reads may: as an argument to a
20
+ * call or constructor the minifier does not know, or assigned to a property
21
+ * -- directly, or inside a template, a concatenation, or an array or object
22
+ * literal that is itself used so. Anything else, including a check that fails,
23
+ * counts as not inert.
24
+ */
25
+ export declare function markersInert(code: string, token: string): boolean;
2
26
  export declare function bundleProject(dir: string): Promise<string>;
3
27
  /** Above this a chunk risks being too big for WebView's code cache (~4-5 MB). */
4
28
  export declare const CHUNK_WARN_BYTES: number;
package/dist/bundle.js CHANGED
@@ -1,11 +1,444 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
- import { createHash } from 'crypto';
3
+ import { createHash, randomBytes } from 'crypto';
4
4
  import { build, parseAst } from 'vite';
5
5
  import { viteSingleFile } from 'vite-plugin-singlefile';
6
6
  import { sceneFilesPlugin, importsAliasPlugin, forksOverlayPlugin, sdkAliasPlugin, singleFileBuildCompatPlugin, castleWorkerOptions, } from './vitePlugins.js';
7
7
  import { castleChunkBoot } from './chunkLoader.js';
8
+ import { countWideCharacters, latin1Html, latin1JavaScript, warnWideCharacters } from './bundleLatin1.js';
9
+ // ---------------------------------------------------------------------------
10
+ // Inlined assets kept out of rolldown.
11
+ //
12
+ // A published deck carries every asset it imports as a data: URI, and rolldown
13
+ // holds each one through parsing, minifying and rendering: a large deck's save
14
+ // peaked at about 20x its bundle size, mostly in rolldown's native memory. So
15
+ // Vite still writes each data: URI (its MIME and encoding choices stay its
16
+ // own), but where Vite writes one into a module -- an imported asset's
17
+ // `export default "data:..."`, or `new URL("data:...", '' + import.meta.url)`
18
+ // -- its payload becomes a short marker, and the finished bundle gets the
19
+ // payload back by a string splice.
20
+ //
21
+ // The marker keeps the `data:<mime>;base64,` header and stays a string, so the
22
+ // minifier inlines, dedupes and quotes it as it would the whole URI; only
23
+ // base64 payloads are swapped, whose characters print verbatim in any quote.
24
+ // What a short string cannot stand in for is the minifier working something
25
+ // out from it: `png.length > 100 ? a : b` folds at build time, to a different
26
+ // answer, and the minifier sees through more than it seems to (const
27
+ // aliases, one-use arrows and IIFEs, a const array's elements). So before the
28
+ // minifier runs, each chunk is checked against a short list of uses the
29
+ // minifier provably cannot compute with -- the URI handed to a call or a
30
+ // constructor it does not know, or stored on an object -- and a deck that
31
+ // uses an asset any other way (or has more code than the check can afford to
32
+ // parse) is built again with its URIs left in place.
33
+ //
34
+ // The single file only. The chunked bundle names each chunk by a hash of its
35
+ // code, which would hash the markers, so it keeps every URI in rolldown.
36
+ const VITE_DATA_URI = /(^export default |new URL\()"(data:[\w.+-]+\/[\w.+-]+(?:;[\w.+-]+=[\w.+-]+)*;base64,)([A-Za-z0-9+/]+={0,2})"(?=$|, '' \+ import\.meta\.url\))/g;
37
+ /** Smaller payloads stay inline: too small to matter. */
38
+ const INLINE_ASSET_MIN_PAYLOAD = 1024;
39
+ /**
40
+ * Checking a chunk parses it, and a save runs under a 768 MB heap: Town's
41
+ * 9.2 MB chunk (the largest deck in experiments/, unminified) costs about
42
+ * 300 MB of heap, and puts the save's heap peak near 540 MB. A larger chunk is
43
+ * not checked, and builds the old way.
44
+ */
45
+ const INLINE_ASSET_MAX_CHECKED_CODE = 10 * 1024 * 1024;
46
+ export class InlineAssets {
47
+ token = `CASTLE${randomBytes(6).toString('hex')}x`;
48
+ marker = new RegExp(`${this.token}(\\d+)x`, 'g');
49
+ payloads = [];
50
+ indexOf = new Map();
51
+ /** A chunk evaluates a marker: this build is void, and the deck needs its URIs in rolldown. */
52
+ evaluated = false;
53
+ /** Swaps payloads for markers in the deck's own build (a worker keeps its URIs). */
54
+ plugin() {
55
+ let minified = false;
56
+ return {
57
+ name: 'castle-inline-assets',
58
+ enforce: 'post',
59
+ apply: 'build',
60
+ configResolved(config) {
61
+ minified = config.build.minify === 'oxc';
62
+ },
63
+ transform: {
64
+ order: 'post',
65
+ filter: { code: '"data:' },
66
+ handler: (code) => {
67
+ if (!minified)
68
+ return null;
69
+ let swapped = false;
70
+ const out = code.replace(VITE_DATA_URI, (whole, before, header, payload) => {
71
+ if (payload.length < INLINE_ASSET_MIN_PAYLOAD)
72
+ return whole;
73
+ swapped = true;
74
+ return `${before}"${header}${this.markerFor(payload)}"`;
75
+ });
76
+ return swapped ? { code: out, map: null } : null;
77
+ },
78
+ },
79
+ renderChunk: (code) => {
80
+ if (this.payloads.length === 0 || !code.includes(this.token))
81
+ return null;
82
+ if (code.length > INLINE_ASSET_MAX_CHECKED_CODE || !markersInert(code, this.token)) {
83
+ this.evaluated = true;
84
+ throw new Error('Bundle: a chunk may evaluate an inline asset; building with assets inline.');
85
+ }
86
+ return null;
87
+ },
88
+ };
89
+ }
90
+ markerFor(payload) {
91
+ let index = this.indexOf.get(payload);
92
+ if (index === undefined) {
93
+ index = this.payloads.length;
94
+ this.payloads.push(payload);
95
+ this.indexOf.set(payload, index);
96
+ }
97
+ return `${this.token}${index}x`;
98
+ }
99
+ /** The built text with every marker's payload back in place. */
100
+ restore(text) {
101
+ if (this.payloads.length === 0)
102
+ return text;
103
+ return text.replace(this.marker, (_, index) => {
104
+ const payload = this.payloads[Number(index)];
105
+ if (payload === undefined)
106
+ throw new Error(`Bundle: unknown inline asset marker ${index}.`);
107
+ return payload;
108
+ });
109
+ }
110
+ }
111
+ // The globals an asset URI may be handed to, as a callee, a constructor or a
112
+ // method's receiver: browser APIs that load or hold a URL, which the minifier
113
+ // does not evaluate. Any other global (`Array`, `String`, `encodeURIComponent`,
114
+ // ...) it may, so it is not on this list.
115
+ const OPAQUE_GLOBALS = new Set([
116
+ 'document', 'navigator', 'location', 'history', 'console', 'localStorage',
117
+ 'sessionStorage', 'performance', 'caches', 'indexedDB', 'fetch', 'Request', 'Response', 'Headers',
118
+ 'URL', 'Image', 'Audio', 'Worker', 'SharedWorker', 'Blob', 'File', 'FontFace', 'EventSource',
119
+ 'WebSocket', 'XMLHttpRequest', 'Path2D', 'VideoFrame', 'ImageDecoder', 'createImageBitmap',
120
+ 'setTimeout', 'setInterval', 'queueMicrotask', 'requestAnimationFrame', 'Promise',
121
+ ]);
122
+ // Names for the global object: `window.Array` is `Array`, so a chain from one
123
+ // is judged by the global it names.
124
+ const GLOBAL_ALIASES = new Set(['window', 'self', 'globalThis']);
125
+ /**
126
+ * True if, in this chunk (not yet minified), the minifier provably cannot
127
+ * compute with any marker. A marker must be the value of a `var` the chunk
128
+ * declares once and gives it only once (how rolldown writes an asset module's
129
+ * export), or be used as that var's reads may: as an argument to a
130
+ * call or constructor the minifier does not know, or assigned to a property
131
+ * -- directly, or inside a template, a concatenation, or an array or object
132
+ * literal that is itself used so. Anything else, including a check that fails,
133
+ * counts as not inert.
134
+ */
135
+ export function markersInert(code, token) {
136
+ try {
137
+ return checkMarkers(parseAst(code), token);
138
+ }
139
+ catch {
140
+ return false;
141
+ }
142
+ }
143
+ function checkMarkers(ast, token) {
144
+ // Every binding: how often it is declared, how, and whether it is ever assigned.
145
+ // `constructed`: the `new` (or class) expressions a var/let/const of the name is given;
146
+ // `known`: some declaration of it is anything else the minifier could see
147
+ // into (see opaqueBinding).
148
+ const declarations = new Map();
149
+ // How often each name is assigned, and to what (the last one seen).
150
+ const assigned = new Map();
151
+ const assignedFrom = new Map();
152
+ // Names assigned anywhere outside a function body.
153
+ const assignedAtTop = new Set();
154
+ const assign = (target) => forEachBinding(target, (name) => assigned.set(name, (assigned.get(name) ?? 0) + 1));
155
+ const declare = (pattern, kind, init) => forEachBinding(pattern, (name) => {
156
+ const seen = declarations.get(name);
157
+ const variable = kind === 'const' || kind === 'let' || kind === 'var';
158
+ // `var C = class {}` is how rolldown writes a class declaration.
159
+ const constructed = variable && (init?.type === 'NewExpression' || init?.type === 'ClassExpression');
160
+ const known = variable ? !constructed : kind !== 'function' && kind !== 'param' && kind !== 'class';
161
+ declarations.set(name, {
162
+ count: (seen?.count ?? 0) + 1,
163
+ known: (seen?.known ?? false) || known,
164
+ fn: kind === 'function' && (seen?.fn ?? true),
165
+ constructed: constructed && init ? [...(seen?.constructed ?? []), init] : (seen?.constructed ?? []),
166
+ init,
167
+ kind,
168
+ });
169
+ });
170
+ const markers = new Set();
171
+ const scan = (node, inFunction) => {
172
+ switch (node.type) {
173
+ case 'Literal':
174
+ if (typeof node.value === 'string' && node.value.includes(token))
175
+ markers.add(node);
176
+ break;
177
+ case 'TemplateLiteral':
178
+ if (node.quasis.some((q) => q.value.raw.includes(token)))
179
+ markers.add(node);
180
+ break;
181
+ case 'VariableDeclaration':
182
+ for (const d of node.declarations)
183
+ declare(d.id, node.kind, d.init ?? null);
184
+ break;
185
+ case 'FunctionDeclaration':
186
+ if (node.id)
187
+ declare(node.id, 'function', null);
188
+ declare(node.params, 'param', null);
189
+ break;
190
+ case 'FunctionExpression':
191
+ case 'ArrowFunctionExpression':
192
+ if (node.id)
193
+ declare(node.id, 'name', null);
194
+ declare(node.params, 'param', null);
195
+ break;
196
+ case 'ClassDeclaration':
197
+ case 'ClassExpression':
198
+ if (node.id)
199
+ declare(node.id, 'class', null);
200
+ break;
201
+ case 'CatchClause':
202
+ if (node.param)
203
+ declare(node.param, 'param', null);
204
+ break;
205
+ case 'AssignmentExpression':
206
+ assign(node.left);
207
+ if (!inFunction)
208
+ forEachBinding(node.left, (name) => assignedAtTop.add(name));
209
+ if (node.left.type === 'Identifier')
210
+ assignedFrom.set(node.left.name, node.right);
211
+ break;
212
+ case 'UpdateExpression':
213
+ assign(node.argument);
214
+ break;
215
+ case 'ForInStatement':
216
+ case 'ForOfStatement':
217
+ assign(node.left);
218
+ break;
219
+ }
220
+ const body = inFunction || /Function/.test(node.type);
221
+ for (const key of Object.keys(node)) {
222
+ const value = node[key];
223
+ for (const child of Array.isArray(value) ? value : [value])
224
+ if (isNode(child))
225
+ scan(child, body);
226
+ }
227
+ };
228
+ scan(ast, false);
229
+ if (markers.size === 0)
230
+ return true;
231
+ // The vars that hold a marker: given it where declared, or (in a module
232
+ // rolldown initializes lazily) declared bare and assigned it once, inside
233
+ // the module's init function. The minifier can inline the first kind into a
234
+ // read; the second it never can, as a read may come before the assignment,
235
+ // so where those are read does not matter.
236
+ const holding = new Set();
237
+ const lazy = new Set();
238
+ for (const [name, d] of declarations) {
239
+ if (d.count !== 1 || d.kind !== 'var')
240
+ continue;
241
+ const writes = assigned.get(name) ?? 0;
242
+ const value = d.init ?? (writes === 1 ? assignedFrom.get(name) : undefined);
243
+ if (!value || !markers.has(value) || writes !== (d.init ? 0 : 1))
244
+ continue;
245
+ if (!d.init && assignedAtTop.has(name))
246
+ continue;
247
+ holding.add(name);
248
+ if (!d.init)
249
+ lazy.add(name);
250
+ }
251
+ // A callee the minifier cannot see into or evaluate.
252
+ // A binding the minifier cannot know the value of: a function declared or
253
+ // passed in, a class, or an object a constructor it cannot evaluate made.
254
+ // Anything else -- even a call's result, which may be a constant -- it might.
255
+ const deciding = new Set();
256
+ const opaqueBinding = (name) => {
257
+ const d = declarations.get(name);
258
+ if (!d)
259
+ return OPAQUE_GLOBALS.has(name);
260
+ if (d.fn)
261
+ return true;
262
+ if (d.known || deciding.has(name))
263
+ return false;
264
+ deciding.add(name);
265
+ try {
266
+ return d.constructed.every((init) => init.type === 'ClassExpression' || isConstructed(init));
267
+ }
268
+ finally {
269
+ deciding.delete(name);
270
+ }
271
+ };
272
+ // A callee (or constructor) the minifier cannot see into or evaluate: an
273
+ // opaque binding, or a method reached from one, from `this`, or from an
274
+ // object an opaque constructor made.
275
+ const opaqueCallee = (callee) => {
276
+ // The chain from its root: `a.b.c` is [a, b, c].
277
+ const chain = [];
278
+ let n = unparen(callee);
279
+ while (n?.type === 'MemberExpression') {
280
+ if (n.computed || n.property.type !== 'Identifier')
281
+ return false;
282
+ chain.unshift(n.property);
283
+ n = unparen(n.object);
284
+ }
285
+ if (!n)
286
+ return false;
287
+ chain.unshift(n);
288
+ // Look through the global object: `window.self.Array` is the global
289
+ // `Array`, whatever the chunk itself declares by that name.
290
+ let global = false;
291
+ while (chain.length > 1 && chain[0].type === 'Identifier' && GLOBAL_ALIASES.has(chain[0].name) &&
292
+ (global || !declarations.has(chain[0].name))) {
293
+ chain.shift();
294
+ global = true;
295
+ }
296
+ const root = chain[0];
297
+ if (root.type === 'Identifier') {
298
+ const name = root.name;
299
+ return global ? OPAQUE_GLOBALS.has(name) : opaqueBinding(name) && !holding.has(name);
300
+ }
301
+ return chain.length > 1 && (root.type === 'ThisExpression' || isConstructed(root));
302
+ };
303
+ const isConstructed = (node) => node.type === 'NewExpression' && opaqueCallee(node.callee);
304
+ // Every marker and every read of a var holding one, with the expressions around it.
305
+ const ancestors = [];
306
+ let inert = true;
307
+ const visit = (node, key) => {
308
+ if (!inert)
309
+ return;
310
+ const parent = ancestors.at(-1);
311
+ const isMarker = markers.has(node);
312
+ const target = parent?.type === 'VariableDeclarator' && key === 'init' ? parent.id
313
+ : parent?.type === 'AssignmentExpression' && key === 'right' && parent.operator === '=' ? parent.left : null;
314
+ const holderInit = isMarker && target?.type === 'Identifier' &&
315
+ holding.has(target.name);
316
+ const isRead = node.type === 'Identifier' && holding.has(node.name) && !lazy.has(node.name) &&
317
+ readsBinding(parent, key);
318
+ if ((isMarker && !holderInit) || isRead) {
319
+ if (!inertUse(node, ancestors, opaqueCallee))
320
+ inert = false;
321
+ }
322
+ ancestors.push(node);
323
+ for (const childKey of Object.keys(node)) {
324
+ const value = node[childKey];
325
+ for (const child of Array.isArray(value) ? value : [value])
326
+ if (isNode(child))
327
+ visit(child, childKey);
328
+ }
329
+ ancestors.pop();
330
+ };
331
+ visit(ast, '');
332
+ return inert;
333
+ }
334
+ function isNode(value) {
335
+ return !!value && typeof value === 'object' && typeof value.type === 'string';
336
+ }
337
+ // Each name a binding pattern (or assignment target) binds.
338
+ function forEachBinding(pattern, bind) {
339
+ const n = pattern;
340
+ if (!n)
341
+ return;
342
+ switch (n.type) {
343
+ case 'Identifier':
344
+ bind(n.name);
345
+ break;
346
+ case 'AssignmentPattern':
347
+ forEachBinding(n.left, bind);
348
+ break;
349
+ case 'RestElement':
350
+ forEachBinding(n.argument, bind);
351
+ break;
352
+ case 'ArrayPattern':
353
+ for (const element of n.elements)
354
+ forEachBinding(element, bind);
355
+ break;
356
+ case 'ObjectPattern':
357
+ for (const property of n.properties)
358
+ forEachBinding(property.type === 'RestElement' ? property.argument : property.value, bind);
359
+ break;
360
+ case 'VariableDeclaration':
361
+ for (const d of n.declarations)
362
+ forEachBinding(d.id, bind);
363
+ break;
364
+ default:
365
+ if (Array.isArray(pattern))
366
+ for (const item of pattern)
367
+ forEachBinding(item, bind);
368
+ }
369
+ }
370
+ // An identifier that reads (or writes) a binding, not one that names a property or a label.
371
+ function readsBinding(parent, key) {
372
+ if (!parent)
373
+ return true;
374
+ switch (parent.type) {
375
+ case 'MemberExpression':
376
+ return key !== 'property' || !!parent.computed;
377
+ case 'Property':
378
+ case 'MethodDefinition':
379
+ case 'PropertyDefinition':
380
+ return key !== 'key' || !!parent.computed;
381
+ case 'VariableDeclarator':
382
+ return key !== 'id';
383
+ case 'LabeledStatement':
384
+ case 'BreakStatement':
385
+ case 'ContinueStatement':
386
+ return false;
387
+ default:
388
+ return true;
389
+ }
390
+ }
391
+ // Whether `node` (a marker, or a read of a var holding one) is used only where
392
+ // the minifier cannot compute with it. `ancestors` runs from the program to
393
+ // `node`'s parent.
394
+ function inertUse(node, ancestors, opaqueCallee) {
395
+ let child = node;
396
+ for (let at = ancestors.length - 1; at >= 0; at--) {
397
+ const parent = ancestors[at];
398
+ switch (parent.type) {
399
+ // The whole is the marker's value, or made from it: judge where it goes.
400
+ case 'ParenthesizedExpression':
401
+ case 'TemplateLiteral':
402
+ case 'ArrayExpression':
403
+ child = parent;
404
+ continue;
405
+ case 'BinaryExpression':
406
+ if (parent.operator !== '+')
407
+ return false;
408
+ child = parent;
409
+ continue;
410
+ case 'Property':
411
+ if (parent.value !== child || parent.computed || parent.kind !== 'init')
412
+ return false;
413
+ child = parent;
414
+ continue;
415
+ case 'ObjectExpression':
416
+ child = parent;
417
+ continue;
418
+ case 'CallExpression':
419
+ return parent.callee !== child && opaqueCallee(parent.callee);
420
+ case 'NewExpression':
421
+ return parent.callee !== child && opaqueCallee(parent.callee);
422
+ case 'AssignmentExpression':
423
+ return parent.right === child && parent.operator === '=' && unparen(parent.left)?.type === 'MemberExpression';
424
+ default:
425
+ return false;
426
+ }
427
+ }
428
+ return false;
429
+ }
8
430
  export async function bundleProject(dir) {
431
+ const inline = new InlineAssets();
432
+ try {
433
+ return await bundleSingleFile(dir, inline);
434
+ }
435
+ catch (err) {
436
+ if (!inline.evaluated)
437
+ throw err;
438
+ return bundleSingleFile(dir, null);
439
+ }
440
+ }
441
+ async function bundleSingleFile(dir, inline) {
9
442
  const result = await build({
10
443
  root: dir,
11
444
  worker: castleWorkerOptions(),
@@ -16,6 +449,7 @@ export async function bundleProject(dir) {
16
449
  viteSingleFile(),
17
450
  singleFileBuildCompatPlugin(),
18
451
  sceneFilesPlugin(),
452
+ inline?.plugin(),
19
453
  ],
20
454
  build: {
21
455
  write: false,
@@ -30,7 +464,11 @@ export async function bundleProject(dir) {
30
464
  throw new Error('Unexpected build result');
31
465
  for (const chunk of output.output) {
32
466
  if (chunk.type === 'asset' && chunk.fileName.endsWith('.html')) {
33
- return chunk.source;
467
+ // Before the splice: the payloads are ASCII, which latin1Html leaves as
468
+ // it is, and it is cheaper over the page without them.
469
+ const html = latin1Html(chunk.source);
470
+ warnWideCharacters(countWideCharacters(html));
471
+ return inline ? inline.restore(html) : html;
34
472
  }
35
473
  }
36
474
  throw new Error('No HTML output found from build');
@@ -490,13 +928,16 @@ export async function bundleProjectChunked(dir) {
490
928
  visit(dep);
491
929
  };
492
930
  visit(entry);
931
+ let remainingWideCharacters = 0;
493
932
  const chunks = built.map((c) => {
494
933
  const { code: body, urls } = rewriteChunkCalls(c.name, c.code.replace(/"?__VITE_PRELOAD__"?/g, 'void 0'), c.imports);
495
934
  for (const target of urls) {
496
935
  if (!wasm.has(target))
497
936
  throw new Error(`Chunked bundle: ${c.name} names an unknown asset ${target}.`);
498
937
  }
499
- const bytes = Buffer.from(wrapChunk(c.name, body), 'utf8');
938
+ const code = latin1JavaScript(wrapChunk(c.name, body));
939
+ remainingWideCharacters += countWideCharacters(code);
940
+ const bytes = Buffer.from(code, 'utf8');
500
941
  const sha256 = sha256Hex(bytes);
501
942
  return {
502
943
  kind: 'js',
@@ -554,7 +995,9 @@ export async function bundleProjectChunked(dir) {
554
995
  const tags = orderedInitial
555
996
  .map((name) => `<script defer crossorigin="anonymous" src="${url(name)}"></script>`)
556
997
  .join('');
557
- return template.replace(SLOT, () => boot + tags);
998
+ const rendered = latin1Html(template.replace(SLOT, () => boot + tags));
999
+ warnWideCharacters(remainingWideCharacters + countWideCharacters(rendered));
1000
+ return rendered;
558
1001
  },
559
1002
  };
560
1003
  }
@@ -0,0 +1,6 @@
1
+ export declare function countWideCharacters(source: string): number;
2
+ /** Preserve unknown syntax and tagged-template raw text; callers count leftovers. */
3
+ export declare function latin1JavaScript(source: string): string;
4
+ export declare function latin1Css(source: string): string;
5
+ export declare function latin1Html(source: string): string;
6
+ export declare function warnWideCharacters(count: number): void;