roamwright 0.61.22 → 0.61.23

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.
@@ -1,7 +1,7 @@
1
1
  // Self-hosted Three.js and Roamwright engine vendor bundling helpers.
2
2
  // Bundles the locked Three.js core module and tree-shaken Roamwright groups (engine, worker, jobs, optional)
3
3
  // into `vendor/` so a world update can reuse cached engine and Three.js bundles across deployments.
4
- import { copyFileSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs';
4
+ import { copyFileSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
5
  import { createRequire } from 'node:module';
6
6
  import { basename, dirname, join, relative, resolve } from 'node:path';
7
7
  import { walkReach } from './module-graph.mjs';
@@ -102,6 +102,152 @@ export function pruneEngine(files, vendorRoot = 'vendor/roamwright') {
102
102
  }
103
103
  }
104
104
 
105
+ /**
106
+ * Assigns non-startup, non-worker optional engine subpaths into separate vendor groups so each land loads only its own
107
+ * optional modules rather than one monolithic `optional` bundle:
108
+ * - `optional-land-<i>`: reached solely by land `i` and imported statically by it
109
+ * - `optional`: statically imported by a land and shared across more than one land
110
+ * - `optional-lazy`: dynamically imported only (scenes, interiors, crawlers, and lazy features)
111
+ *
112
+ * @param {Iterable<string>} all All engine subpaths imported by the world.
113
+ * @param {object} [options]
114
+ * @param {Set<string>} [options.excluded] Engine subpaths already assigned to `worker`, `jobs`, or `engine` startup groups.
115
+ * @param {Array<Set<string>>} [options.lands=[]] Per-land full engine subpath sets (static + dynamic reach).
116
+ * @param {Array<Set<string>>} [options.staticLands] Per-land static engine subpath sets (defaults to `lands`).
117
+ * @returns {Map<string, string>} Map from engine subpath to optional vendor group name.
118
+ */
119
+ export function partitionOptionalEngine(all, { excluded = new Set(), lands = [], staticLands = lands } = {}) {
120
+ const groups = new Map();
121
+ for (const id of all) {
122
+ if (excluded.has(id)) continue;
123
+ let fullCount = 0;
124
+ let staticCount = 0;
125
+ let firstStaticLand = -1;
126
+ for (let i = 0; i < lands.length; i++) {
127
+ if (lands[i].has(id)) fullCount++;
128
+ }
129
+ for (let i = 0; i < staticLands.length; i++) {
130
+ if (staticLands[i].has(id)) {
131
+ if (firstStaticLand < 0) firstStaticLand = i;
132
+ staticCount++;
133
+ }
134
+ }
135
+ if (staticCount === 1 && fullCount === 1) groups.set(id, `optional-land-${firstStaticLand}`);
136
+ else if (staticCount > 0) groups.set(id, 'optional');
137
+ else groups.set(id, 'optional-lazy');
138
+ }
139
+ return groups;
140
+ }
141
+
142
+ async function linkEngineGroups({ directory, groups, shaders, revision, rollup, terser, resolveModule }) {
143
+ const entryPrefix = 'engine-group:';
144
+ const groupNames = [...groups.keys()];
145
+ const optionalNames = groupNames.filter(name => name.startsWith('optional'));
146
+ const chunkFor = new Map();
147
+ const bundle = await rollup({
148
+ input: Object.fromEntries(groupNames.map(group => [group, entryPrefix + group])),
149
+ treeshake: 'recommended',
150
+ external: id => id === THREE_URL,
151
+ makeAbsoluteExternalsRelative: false,
152
+ onwarn(warning, warn) {
153
+ if (warning.code !== 'UNUSED_EXTERNAL_IMPORT') warn(warning);
154
+ },
155
+ plugins: [
156
+ {
157
+ name: 'engine-groups',
158
+ resolveId(id, importer) {
159
+ if (id.startsWith(entryPrefix)) return id;
160
+ if (id === 'three') return { id: THREE_URL, external: true };
161
+ if (id.startsWith('roamwright/')) return resolveModule(id);
162
+ if (importer && !importer.startsWith(entryPrefix)) return resolve(dirname(importer), id);
163
+ return null;
164
+ },
165
+ load(id) {
166
+ if (id.startsWith(entryPrefix)) return groups.get(id.slice(entryPrefix.length)).join('\n');
167
+ if (shaders[id] !== undefined) return shaders[id];
168
+ return readFileSync(id, 'utf8');
169
+ },
170
+ buildEnd() {
171
+ // Strict 4-level DAG (shared-worker -> shared-jobs -> shared-engine -> shared-optional)
172
+ // keeps worker chunks free of browser-only modules and avoids shared-chunk fragmentation.
173
+ const reachFrom = group => {
174
+ const seen = new Set();
175
+ const entry = entryPrefix + group;
176
+ if (!groups.has(group)) return seen;
177
+ const queue = [entry];
178
+ while (queue.length) {
179
+ const id = queue.pop();
180
+ if (seen.has(id)) continue;
181
+ seen.add(id);
182
+ const info = this.getModuleInfo(id);
183
+ if (!info) continue;
184
+ for (const dep of info.importedIds) {
185
+ if (dep !== THREE_URL && !seen.has(dep)) queue.push(dep);
186
+ }
187
+ }
188
+ return seen;
189
+ };
190
+ const inWorker = reachFrom('worker');
191
+ const inJobs = reachFrom('jobs');
192
+ const inEngine = reachFrom('engine');
193
+ const inOptional = optionalNames.map(name => reachFrom(name));
194
+ for (const id of this.getModuleIds()) {
195
+ if (id.startsWith(entryPrefix) || id === THREE_URL) continue;
196
+ const isW = inWorker.has(id);
197
+ const isJ = inJobs.has(id);
198
+ const isE = inEngine.has(id);
199
+ let optCount = 0;
200
+ for (let i = 0; i < inOptional.length; i++) {
201
+ if (inOptional[i].has(id)) optCount++;
202
+ }
203
+ if (isW && (isJ || isE || optCount > 0)) chunkFor.set(id, 'shared-worker');
204
+ else if (!isW && isJ && (isE || optCount > 0)) chunkFor.set(id, 'shared-jobs');
205
+ else if (!isW && !isJ && isE && optCount > 0) chunkFor.set(id, 'shared-engine');
206
+ else if (!isW && !isJ && !isE && optCount > 1) chunkFor.set(id, 'shared-optional');
207
+ }
208
+ },
209
+ },
210
+ ],
211
+ });
212
+ try {
213
+ const { output } = await bundle.generate({
214
+ format: 'esm',
215
+ entryFileNames: '[name]-[hash].js',
216
+ chunkFileNames: '[name]-[hash].js',
217
+ hashCharacters: 'hex',
218
+ hoistTransitiveImports: false,
219
+ manualChunks: id => chunkFor.get(id),
220
+ plugins: [
221
+ terser({
222
+ ecma: 2022,
223
+ module: true,
224
+ compress: { passes: 2, module: true },
225
+ mangle: { module: true },
226
+ format: { comments: false, preamble: `/* Three.js r${revision} */` },
227
+ maxWorkers: 2,
228
+ }),
229
+ ],
230
+ });
231
+ mkdirSync(directory, { recursive: true });
232
+ const files = new Set(output.map(chunk => chunk.fileName));
233
+ const outputs = {};
234
+ for (const chunk of output) {
235
+ const file = join(directory, chunk.fileName);
236
+ const entryPoint = chunk.facadeModuleId?.startsWith(entryPrefix) ? chunk.facadeModuleId : undefined;
237
+ const imports = (paths, kind) =>
238
+ paths.map(path => (files.has(path) ? { path: join(directory, path), kind } : { path, kind, external: true }));
239
+ outputs[file] = {
240
+ entryPoint,
241
+ imports: [...imports(chunk.imports, 'import-statement'), ...imports(chunk.dynamicImports, 'dynamic-import')],
242
+ };
243
+ writeFileSync(file, chunk.code);
244
+ }
245
+ return outputs;
246
+ } finally {
247
+ await bundle.close();
248
+ }
249
+ }
250
+
105
251
  /**
106
252
  * Bundles the tree-shaken Roamwright engine subpaths used by a world into grouped ESM files under
107
253
  * `vendor/roamwright/<version>/`, returning an esbuild rewrite plugin and preload manifest.
@@ -113,6 +259,9 @@ export function pruneEngine(files, vendorRoot = 'vendor/roamwright') {
113
259
  * @param {Set<string>} options.startup Engine subpaths required at page startup.
114
260
  * @param {Set<string>} options.workerStartup Engine subpaths required at worker startup.
115
261
  * @param {Set<string>} options.workerJobs Engine subpaths required by lazy worker jobs.
262
+ * @param {Map<string, string> | null} [options.optionalGroups=null] Optional group names for non-startup, non-worker subpaths.
263
+ * @param {Function | null} [options.rollup=null] Rollup's `rollup` function for DAG chunk linking (falls back to esbuild).
264
+ * @param {Function | null} [options.terser=null] `@rollup/plugin-terser` factory paired with `rollup`.
116
265
  * @param {string | number} options.revision Three.js `REVISION` stamped into the bundle banner.
117
266
  * @param {(sources: Record<string, string>) => Record<string, string>} options.compactShaders Shader compactor callback.
118
267
  * @param {(specifier: string) => string} [options.resolveModule] Module resolver from the consumer root.
@@ -120,7 +269,19 @@ export function pruneEngine(files, vendorRoot = 'vendor/roamwright') {
120
269
  */
121
270
  export async function buildRoamwright(
122
271
  esbuild,
123
- { all, used, startup, workerStartup, workerJobs, revision, compactShaders, resolveModule = defaultRequire.resolve },
272
+ {
273
+ all,
274
+ used,
275
+ startup,
276
+ workerStartup,
277
+ workerJobs,
278
+ optionalGroups = null,
279
+ rollup = null,
280
+ terser = null,
281
+ revision,
282
+ compactShaders,
283
+ resolveModule = defaultRequire.resolve,
284
+ },
124
285
  ) {
125
286
  const root = dirname(resolveModule('roamwright'));
126
287
  const { version } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
@@ -131,7 +292,13 @@ export async function buildRoamwright(
131
292
  {
132
293
  id,
133
294
  prefix: `m${index}_`,
134
- group: workerStartup.has(id) ? 'worker' : workerJobs.has(id) ? 'jobs' : startup.has(id) ? 'engine' : 'optional',
295
+ group: workerStartup.has(id)
296
+ ? 'worker'
297
+ : workerJobs.has(id)
298
+ ? 'jobs'
299
+ : startup.has(id)
300
+ ? 'engine'
301
+ : (optionalGroups?.get(id) ?? 'optional'),
135
302
  },
136
303
  ]),
137
304
  );
@@ -162,39 +329,45 @@ export async function buildRoamwright(
162
329
  const list = m.names.map(name => `${name} as ${m.prefix}${name}`).join(', ');
163
330
  groups.get(m.group).push(`export { ${list} } from ${JSON.stringify(m.id)};`);
164
331
  }
165
- const bundles = await esbuild.build({
166
- entryPoints: [...groups.keys()].map(group => ({ in: 'engine-group:' + group, out: group })),
167
- outdir: directory,
168
- entryNames: '[name]-[hash]',
169
- chunkNames: 'shared-[hash]',
170
- banner: { js: `/* Three.js r${revision} */` },
171
- format: 'esm',
172
- target: 'es2022',
173
- bundle: true,
174
- splitting: true,
175
- treeShaking: true,
176
- minify: true,
177
- legalComments: 'none',
178
- metafile: true,
179
- plugins: [
180
- {
181
- name: 'engine-groups',
182
- setup(build) {
183
- build.onLoad({ filter: /\.js$/ }, args => (shaders[args.path] === undefined ? undefined : { contents: shaders[args.path] }));
184
- build.onResolve({ filter: /^engine-group:/ }, args => ({
185
- path: args.path.slice('engine-group:'.length),
186
- namespace: 'engine-group',
187
- }));
188
- build.onLoad({ filter: /.*/, namespace: 'engine-group' }, args => ({
189
- contents: groups.get(args.path).join('\n'),
190
- resolveDir: root,
191
- }));
192
- build.onResolve({ filter: /^three$/ }, () => ({ path: THREE_URL, external: true }));
193
- },
194
- },
195
- ],
196
- });
197
- const outputs = bundles.metafile.outputs;
332
+ const outputs =
333
+ rollup && terser
334
+ ? await linkEngineGroups({ directory, groups, shaders, revision, rollup, terser, resolveModule })
335
+ : (
336
+ await esbuild.build({
337
+ entryPoints: [...groups.keys()].map(group => ({ in: 'engine-group:' + group, out: group })),
338
+ outdir: directory,
339
+ entryNames: '[name]-[hash]',
340
+ chunkNames: 'shared-[hash]',
341
+ banner: { js: `/* Three.js r${revision} */` },
342
+ format: 'esm',
343
+ target: 'es2022',
344
+ bundle: true,
345
+ splitting: true,
346
+ treeShaking: true,
347
+ minify: true,
348
+ legalComments: 'none',
349
+ metafile: true,
350
+ plugins: [
351
+ {
352
+ name: 'engine-groups',
353
+ setup(build) {
354
+ build.onLoad({ filter: /\.js$/ }, args =>
355
+ shaders[args.path] === undefined ? undefined : { contents: shaders[args.path] },
356
+ );
357
+ build.onResolve({ filter: /^engine-group:/ }, args => ({
358
+ path: args.path.slice('engine-group:'.length),
359
+ namespace: 'engine-group',
360
+ }));
361
+ build.onLoad({ filter: /.*/, namespace: 'engine-group' }, args => ({
362
+ contents: groups.get(args.path).join('\n'),
363
+ resolveDir: root,
364
+ }));
365
+ build.onResolve({ filter: /^three$/ }, () => ({ path: THREE_URL, external: true }));
366
+ },
367
+ },
368
+ ],
369
+ })
370
+ ).metafile.outputs;
198
371
  const entries = new Map();
199
372
  for (const [file, output] of Object.entries(outputs)) {
200
373
  if (output.entryPoint) entries.set(output.entryPoint.slice('engine-group:'.length), file);