@null3d/vite-plugin 0.0.0-stage → 0.1.0

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 (52) hide show
  1. package/LICENSE-APACHE +176 -0
  2. package/LICENSE-MIT +21 -0
  3. package/README.md +87 -2
  4. package/THIRD-PARTY-NOTICES.txt +413 -0
  5. package/dist/shader-compiler.stamp.json +4 -0
  6. package/dist/shader-compiler.wasm +0 -0
  7. package/lib/assets.d.ts +94 -0
  8. package/lib/assets.js +189 -0
  9. package/lib/client.d.ts +21 -0
  10. package/lib/compile-pool.d.ts +25 -0
  11. package/lib/compile-pool.js +90 -0
  12. package/lib/compile-worker.js +11 -0
  13. package/lib/compiler-calls.d.ts +26 -0
  14. package/lib/compiler-calls.js +97 -0
  15. package/lib/compiler-stamp.d.ts +8 -0
  16. package/lib/compiler-stamp.js +34 -0
  17. package/lib/compress.d.ts +47 -0
  18. package/lib/compress.js +391 -0
  19. package/lib/declarations.d.ts +10 -0
  20. package/lib/declarations.js +80 -0
  21. package/lib/engine-shaders-local.d.ts +6 -0
  22. package/lib/engine-shaders-local.js +75 -0
  23. package/lib/engine-shaders.d.ts +61 -0
  24. package/lib/engine-shaders.js +170 -0
  25. package/lib/hash-pool.d.ts +24 -0
  26. package/lib/hash-pool.js +84 -0
  27. package/lib/hash-worker.js +53 -0
  28. package/lib/hot.d.ts +53 -0
  29. package/lib/hot.js +101 -0
  30. package/lib/index.d.ts +122 -0
  31. package/lib/index.js +972 -0
  32. package/lib/material-builds.d.ts +91 -0
  33. package/lib/material-builds.js +236 -0
  34. package/lib/offline.d.ts +92 -0
  35. package/lib/offline.js +304 -0
  36. package/lib/pack.d.ts +30 -0
  37. package/lib/pack.js +112 -0
  38. package/lib/package-files.d.ts +12 -0
  39. package/lib/package-files.js +39 -0
  40. package/lib/paragraphs.d.ts +19 -0
  41. package/lib/paragraphs.js +131 -0
  42. package/lib/shader-cache.d.ts +59 -0
  43. package/lib/shader-cache.js +213 -0
  44. package/lib/shader-compiler.d.ts +258 -0
  45. package/lib/shader-compiler.js +169 -0
  46. package/lib/shader-types.d.ts +261 -0
  47. package/lib/shader-types.js +4 -0
  48. package/lib/wgsl.d.ts +118 -0
  49. package/lib/wgsl.js +447 -0
  50. package/lib/worker-preload.d.ts +30 -0
  51. package/lib/worker-preload.js +84 -0
  52. package/package.json +69 -5
package/lib/index.js ADDED
@@ -0,0 +1,972 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, join, posix, relative, resolve, sep } from 'node:path';
5
+ import MagicString from 'magic-string';
6
+ import { ASSET_FOLDER, assetType, cachedFile, cacheFolder, OPTIMIZED_MODEL, optimizedModel, } from "./assets.js";
7
+ import { CompilerPool } from "./compile-pool.js";
8
+ import { compressAnswers, compressedFiles, fromLoopback } from "./compress.js";
9
+ import { writeWgslDeclaration } from "./declarations.js";
10
+ import { ENGINE_SHADERS_ENV, engineShaderFolder, engineShadersRoot, ensureEngineShaders, } from "./engine-shaders.js";
11
+ import { buildEngineShadersLocally } from "./engine-shaders-local.js";
12
+ import { HashPool } from "./hash-pool.js";
13
+ import { changedLiterals, HOT_CLIENT, HOT_CLIENT_ADDRESS, HOT_CLIENT_CODE, HOT_CLIENT_ID, HotState, hotKey, WGSL_UPDATE_EVENT, } from "./hot.js";
14
+ import { MATERIAL_BUILDS_ADDRESS, MaterialBuilds, ModuleBuilds } from "./material-builds.js";
15
+ import { engineModule, FILES_LIST, featuresOf, listedFiles, missingWorkerAssets, offlineFiles, workerFilesPlugin, } from "./offline.js";
16
+ import { ShaderPack } from "./pack.js";
17
+ import { null3dPackages } from "./package-files.js";
18
+ import { emitParagraphTables, shaderParagraphsPlugin, tableStemsOfFile } from "./paragraphs.js";
19
+ import { ShaderCache, shaderCacheOff } from "./shader-cache.js";
20
+ import { compileLiteral, compileTaggedWgsl, compileWgslFile, WGSL_TAG, } from "./wgsl.js";
21
+ import { directImports, workerPreloadPlugin } from "./worker-preload.js";
22
+ export { FILES_LIST } from "./offline.js";
23
+ /** Headers that make a page cross-origin isolated, which shared memory and worker threads need. */
24
+ export const ISOLATION_HEADERS = {
25
+ 'Cross-Origin-Opener-Policy': 'same-origin',
26
+ 'Cross-Origin-Embedder-Policy': 'require-corp',
27
+ };
28
+ /** Where `bun run dev-cert` writes the local HTTPS certificate. */
29
+ export const DEV_CERT_DIR = 'target/dev-cert';
30
+ /** Sets the isolation headers on every response, including `.wasm` files and worker scripts. */
31
+ export const isolationMiddleware = (_req, res, next) => {
32
+ for (const [name, value] of Object.entries(ISOLATION_HEADERS))
33
+ res.setHeader(name, value);
34
+ next();
35
+ };
36
+ /** Build files whose names carry a content hash, which never change under that name. */
37
+ const HASHED_ASSET = /^\/assets\/[^/?]+-[\w-]{8}\.\w+(\?|$)/;
38
+ /**
39
+ * Lets the browser keep hashed build files, as a host should. Each engine thread loads its own copy
40
+ * of its script and the core's loader; without this, the browser checks each copy with the server
41
+ * in turn, one round trip per thread.
42
+ */
43
+ export const immutableAssetsMiddleware = (req, res, next) => {
44
+ if (HASHED_ASSET.test(req.url ?? ''))
45
+ res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
46
+ next();
47
+ };
48
+ /**
49
+ * Takes `Origin` out of the Vary header of an answer to a request from the page's own origin, with
50
+ * the CORS header that the origin chose. Vite's CORS step marks every answer as varying by the
51
+ * request's Origin. The engine's page downloads the sketch module early with `fetch`, which sends no
52
+ * Origin, and the worker's import of it sends one. Without this, the browser cannot use the early
53
+ * copy and asks the server again, one round trip per such file. A request from the same origin needs
54
+ * no CORS header, and the browser names such a request in its Sec-Fetch-Site header.
55
+ */
56
+ export const sameOriginMiddleware = (req, res, next) => {
57
+ if (req.headers['sec-fetch-site'] !== 'same-origin')
58
+ return next();
59
+ const vary = String(res.getHeader('Vary') ?? '')
60
+ .split(',')
61
+ .map((field) => field.trim())
62
+ .filter((field) => field !== '' && field.toLowerCase() !== 'origin');
63
+ if (vary.length > 0)
64
+ res.setHeader('Vary', vary.join(', '));
65
+ else
66
+ res.removeHeader('Vary');
67
+ res.removeHeader('Access-Control-Allow-Origin');
68
+ next();
69
+ };
70
+ /**
71
+ * The HTTPS server's settings: the certificate, and HTTP/1.1 only unless `http2` asks for HTTP/2.
72
+ * Vite serves HTTPS over HTTP/2, where Safari on iPad sometimes stalls while a worker loads its
73
+ * modules: a development server sends each module as its own file, and every engine thread loads
74
+ * its own copies.
75
+ */
76
+ function httpsOptions(certificate, http2) {
77
+ return http2 ? certificate : { ...certificate, ALPNCallback: () => 'http/1.1' };
78
+ }
79
+ function readCertificate(root, certDir) {
80
+ const dir = resolve(root, certDir);
81
+ const cert = resolve(dir, 'cert.pem');
82
+ const key = resolve(dir, 'key.pem');
83
+ if (!existsSync(cert) || !existsSync(key)) {
84
+ throw new Error(`null3D: no HTTPS certificate in ${dir}. Put cert.pem and key.pem there, or set certDir to their folder. Docs: getting-started/hosting.`);
85
+ }
86
+ return { cert: readFileSync(cert), key: readFileSync(key) };
87
+ }
88
+ /** A script that a page passes by address, such as `new URL('./sketch.ts', import.meta.url)`. */
89
+ const SCRIPT_URL = /new\s+URL\(\s*(['"])(\.{1,2}\/[^'"]+?\.[cm]?[jt]sx?)\1\s*,\s*import\.meta\.url\s*\)/g;
90
+ /**
91
+ * Marks a copied shader file's address in a transformed module until the build knows where the
92
+ * module that names it lands. The mark is not a path, so no bundler resolves it; `generateBundle`
93
+ * replaces it with the address from that module's own place in the output.
94
+ */
95
+ const SHADER_URL_MARK = '__null3d_shader__';
96
+ /** Text just before a script address that a worker constructor takes; Vite builds those itself. */
97
+ const WORKER_BEFORE = /new\s+(?:Shared)?Worker\(\s*$/;
98
+ /** The engine core's files, which every production build ships. */
99
+ export const CORE_FILES = [
100
+ 'threaded/null3d.js',
101
+ 'threaded/null3d_bg.wasm',
102
+ 'single/null3d.js',
103
+ 'single/null3d_bg.wasm',
104
+ ];
105
+ /**
106
+ * The engine's early script, which starts the core's download as soon as a page's HTML arrives.
107
+ * A production build ships it as a file of its own, and each page whose scripts load the core gets
108
+ * a script tag for it.
109
+ */
110
+ export const EARLY_CORE_MODULE = '@null3d/engine/early-core';
111
+ /**
112
+ * The engine's import of one of its generated shader modules, as its own files write it: from a
113
+ * file at any depth inside the engine, so the path climbs one or more folders to `generated/`.
114
+ */
115
+ const ENGINE_GENERATED = /^(?:\.\.?\/)+generated\/([A-Za-z0-9_.-]+)$/;
116
+ /** The `lib` folder of an engine package, when the importer sits inside it. */
117
+ function engineLibFolder(importer) {
118
+ const marker = '/lib/';
119
+ const at = importer.lastIndexOf(marker);
120
+ return at < 0 ? undefined : importer.slice(0, at + marker.length);
121
+ }
122
+ /** Tells the developer where the engine's shaders come from, and why a first build waits. */
123
+ function reportShaderSource(message) {
124
+ console.log(message);
125
+ }
126
+ /** The chunks that a page's entry chunk imports, directly or through others, with the entry. */
127
+ function staticChunks(entry, bundle) {
128
+ const seen = new Map([[entry.fileName, entry]]);
129
+ for (const chunk of seen.values())
130
+ for (const name of chunk.imports) {
131
+ const imported = bundle[name];
132
+ if (imported?.type === 'chunk' && !seen.has(name))
133
+ seen.set(name, imported);
134
+ }
135
+ return [...seen.values()];
136
+ }
137
+ /**
138
+ * The script tag of the early script for a built page, or undefined when the page's scripts do not
139
+ * load the engine core. The core files are the WebAssembly files that the early script names, and a
140
+ * page loads the core when one of its chunks names one of them too. `htmlFile` is the page's path in
141
+ * the build, and `base` the build's public base.
142
+ */
143
+ export function earlyCoreTag(early, entry, bundle, htmlFile, base) {
144
+ const cores = Object.values(bundle)
145
+ .filter((file) => file.type === 'asset' && file.fileName.endsWith('.wasm'))
146
+ .map((file) => posix.basename(file.fileName))
147
+ .filter((name) => early.code.includes(name));
148
+ if (!staticChunks(entry, bundle).some((chunk) => cores.some((name) => chunk.code.includes(name))))
149
+ return undefined;
150
+ const relativeBase = base === '' || base.startsWith('.');
151
+ const path = posix.relative(posix.dirname(htmlFile), early.fileName);
152
+ const src = relativeBase
153
+ ? path.startsWith('.')
154
+ ? path
155
+ : `./${path}`
156
+ : `${base}${early.fileName}`;
157
+ return {
158
+ tag: 'script',
159
+ attrs: { type: 'module', async: true, src },
160
+ injectTo: 'head-prepend',
161
+ };
162
+ }
163
+ /** The file in which each null3D package lists the third-party code that it ships, with licences. */
164
+ const PACKAGE_NOTICES = 'THIRD-PARTY-NOTICES.txt';
165
+ /** The file that a production build writes beside the page, with every package's notices. */
166
+ export const NOTICES_FILE = 'null3d-third-party-notices.txt';
167
+ /** The null3D packages that run as tools on the developer's computer and put no code in a page. */
168
+ const TOOL_PACKAGES = new Set(['@null3d/cli', '@null3d/vite-plugin']);
169
+ /**
170
+ * The third-party notices of the null3D packages that the project depends on: the engine's first,
171
+ * then each add-on's, by name. The tools' notices stay out, since a page ships none of their code.
172
+ * Null when none has notices, as in a project without the engine.
173
+ */
174
+ export function thirdPartyNotices(root) {
175
+ const manifest = resolve(root, 'package.json');
176
+ if (!existsSync(manifest))
177
+ return null;
178
+ const { dependencies = {}, devDependencies = {} } = JSON.parse(readFileSync(manifest, 'utf8'));
179
+ const require = createRequire(manifest);
180
+ const names = Object.keys({ ...dependencies, ...devDependencies })
181
+ .filter((name) => name.startsWith('@null3d/') && !TOOL_PACKAGES.has(name))
182
+ .sort((a, b) => Number(b === '@null3d/engine') - Number(a === '@null3d/engine') || (a < b ? -1 : 1));
183
+ const texts = names.flatMap((name) => {
184
+ try {
185
+ const file = join(dirname(require.resolve(`${name}/package.json`)), PACKAGE_NOTICES);
186
+ return existsSync(file) ? [readFileSync(file, 'utf8').trimEnd()] : [];
187
+ }
188
+ catch {
189
+ return [];
190
+ }
191
+ });
192
+ return texts.length > 0 ? `${texts.join('\n\n')}\n` : null;
193
+ }
194
+ /** A test for files of the published null3D packages, installed or in a copy of the repository. */
195
+ function null3dPackageFiles() {
196
+ const packageOf = null3dPackages();
197
+ return (file) => packageOf(file) !== undefined;
198
+ }
199
+ /**
200
+ * Vite's inline limit with one change: no file of a null3D package becomes a data: address. The
201
+ * engine loads its workers' scripts, its WebAssembly and its shader files by address, and a strict
202
+ * Content-Security-Policy blocks a data: address, as does a worker's origin. `own` is the
203
+ * project's setting, which every other file keeps.
204
+ */
205
+ export function inlineLimit(own, isPackageFile = null3dPackageFiles()) {
206
+ return (file, content) => {
207
+ if (isPackageFile(file))
208
+ return false;
209
+ if (typeof own === 'function')
210
+ return own(file, content);
211
+ return own === undefined ? undefined : content.length < own;
212
+ };
213
+ }
214
+ /**
215
+ * True for a module that a page passes by address for a worker to import, such as a sketch or an
216
+ * add-on's task: a script file whose imports the build must resolve. The address of a script reaches
217
+ * a worker as it is, so a build that copied a TypeScript file with its types would hand the worker a
218
+ * file it cannot parse. Built output under `dist/` ships as it is, as the engine's core does.
219
+ */
220
+ function isImportedModule(path) {
221
+ const file = path.split('?')[0] ?? path;
222
+ if (file.includes('/dist/'))
223
+ return false;
224
+ return SCRIPT_FILE.test(file) && existsSync(file);
225
+ }
226
+ /**
227
+ * Empties the preload lists of the chunks that a worker imports. Vite's preload helper adds a link
228
+ * to the page's head for each file that a dynamic import needs, and it reads `document`, which a
229
+ * worker has not. A sketch module and a task module run in workers, with every chunk they import,
230
+ * so their lists go: an import still fetches its own file, as any worker's import does.
231
+ */
232
+ export function emptyWorkerPreloads(bundle, seeds) {
233
+ const seen = new Set();
234
+ const stack = [...seeds];
235
+ while (stack.length > 0) {
236
+ const file = stack.pop();
237
+ if (seen.has(file))
238
+ continue;
239
+ seen.add(file);
240
+ const chunk = bundle[file];
241
+ if (chunk?.type !== 'chunk')
242
+ continue;
243
+ stack.push(...chunk.imports, ...chunk.dynamicImports);
244
+ }
245
+ for (const file of seen) {
246
+ const chunk = bundle[file];
247
+ if (chunk?.type !== 'chunk' || !chunk.code.includes('__vite__mapDeps('))
248
+ continue;
249
+ chunk.code = chunk.code.replace(/__vite__mapDeps\(\s*\[[^\]]*\]\s*\)/g, '[]');
250
+ }
251
+ }
252
+ /**
253
+ * True when `address`, named by a module at `importer`, is one of the engine's generated shader
254
+ * device modules. The shader build writes those beside `shaders.ts` and its combination modules, and
255
+ * they hold shader text rather than a sketch. A build that read each one to look for `defineSketch`
256
+ * spent a pass over the whole set. Both files may sit in the installed package or in the cache that
257
+ * a project shares, so the names decide and the folder does not.
258
+ */
259
+ function isGeneratedShaderFile(importer, address) {
260
+ const name = importer.slice(importer.lastIndexOf('/') + 1);
261
+ return (/^shaders(?:-[a-z0-9-]+)?\.[cm]?[jt]s$/.test(name) &&
262
+ /^\.\/shaders-[a-z0-9-]+\.js$/.test(address));
263
+ }
264
+ /** A WGSL file that a module imports, without a query such as `?raw`. */
265
+ const WGSL_FILE = /\.wgsl$/;
266
+ /** A script module, whose code the plugin parses for tagged WGSL. */
267
+ const SCRIPT_FILE = /\.[cm]?[jt]sx?$/;
268
+ /** The parameter that keeps a dotted query from naming a module's extension. */
269
+ export const QUERY_EXTENSION_PARAM = 'null3d-query';
270
+ /**
271
+ * Keeps a module's query from deciding its type. Vite reads a dotted word at the end of a module's
272
+ * address as the extension, so a sketch at `sketch.ts?render-scale=0.5` parses as JavaScript and
273
+ * fails on its types. The middleware adds a parameter after such a query, which the sketch sees in
274
+ * `import.meta.url` and ignores, and Vite then reads the file's own extension.
275
+ */
276
+ export function queryExtensionMiddleware() {
277
+ return (req, _res, next) => {
278
+ const url = req.url ?? '';
279
+ const at = url.indexOf('?');
280
+ if (at < 0)
281
+ return next();
282
+ const path = url.slice(0, at);
283
+ const query = url.slice(at + 1);
284
+ if (!SCRIPT_FILE.test(path) || !/\.\w+$/.test(query))
285
+ return next();
286
+ req.url = `${url}&${QUERY_EXTENSION_PARAM}=1`;
287
+ next();
288
+ };
289
+ }
290
+ /** Modules of installed packages, which the plugin leaves as they are. */
291
+ const PACKAGE_MODULE = /\/node_modules\//;
292
+ /** A file's path from the project's root, as messages name it. */
293
+ function projectPath(root, file) {
294
+ return relative(root, file).split(sep).join('/');
295
+ }
296
+ /** Shows WGSL that did not compile in Vite's overlay on the dev server's pages, and in the terminal. */
297
+ function showError(environment, error) {
298
+ environment.logger.error(`${error.message}\n${error.frame}`, { timestamp: true });
299
+ environment.hot.send({
300
+ type: 'error',
301
+ err: { ...error, stack: '', plugin: 'null3d' },
302
+ });
303
+ }
304
+ /** Prints the warnings of WGSL that a hot update compiled, in the dev server's log. */
305
+ function showWarnings(environment, warnings) {
306
+ for (const warning of warnings)
307
+ environment.logger.warn(warning, { timestamp: true });
308
+ }
309
+ /** The modules of a changed file that Vite still updates: all but the one the plugin compiled. */
310
+ function otherModules(modules, file) {
311
+ return modules.filter((module) => module.id !== file);
312
+ }
313
+ /**
314
+ * The core files missing from the installed engine package, or null when the project does not
315
+ * install the engine.
316
+ */
317
+ export function missingCoreFiles(root) {
318
+ const require = createRequire(resolve(root, 'package.json'));
319
+ try {
320
+ require.resolve('@null3d/engine/package.json');
321
+ }
322
+ catch {
323
+ return null;
324
+ }
325
+ return CORE_FILES.filter((file) => {
326
+ try {
327
+ require.resolve(`@null3d/engine/wasm/${file}`);
328
+ return false;
329
+ }
330
+ catch {
331
+ return true;
332
+ }
333
+ });
334
+ }
335
+ /**
336
+ * The null3D Vite plugin: isolation headers on the dev and preview servers, optional HTTPS, WGSL
337
+ * compiled for WebGPU and WebGL2 in dev and in builds, hot updates of WGSL on the dev server, and a
338
+ * production build that compiles each sketch module, ships the engine core and starts its download
339
+ * from each page that loads it.
340
+ */
341
+ export default function null3d(options = {}) {
342
+ let building = false;
343
+ /** True for a production build of pages, which gets the early script. */
344
+ let buildingPages = false;
345
+ /** The early script's module, once a build of pages that imports the engine has added it. */
346
+ let earlyCoreId;
347
+ /** True once the build has looked for the early script. */
348
+ let earlyCoreSought = false;
349
+ let root = process.cwd();
350
+ let base = '/';
351
+ let assetsDir = 'assets';
352
+ /** True when the shader cache is ignored, by the environment or by Vite's `--force`. */
353
+ let noShaderCache = shaderCacheOff();
354
+ /** The third-party notices that a client build writes beside the page; null in other builds. */
355
+ let notices = null;
356
+ /** What each worker build's files hold, by file name, for the list of files for offline play. */
357
+ const workerFiles = new Map();
358
+ const packageOf = null3dPackages();
359
+ /** The optimized files that this build has written, so each texture goes in once. */
360
+ const emitted = new Map();
361
+ /** The chunks emitted for the scripts that a worker imports, by their rollup reference. */
362
+ const workerChunks = new Set();
363
+ /** The modules of the scripts that a worker imports, which those chunks are built from. */
364
+ const workerModules = new Set();
365
+ /** Hashes the generated shader files on worker threads, so the build goes on meanwhile. */
366
+ const hasher = new HashPool();
367
+ /**
368
+ * The generated shader files that the build copies instead of bundling, by their output name:
369
+ * each is named by a hash of its bytes and copied on its own, so the build never holds the
370
+ * whole set in memory.
371
+ */
372
+ const copiedShaders = new Map();
373
+ /**
374
+ * The content hash of each generated shader file by its path, which the pool computes. A page
375
+ * build and its workers reach the same files, so each file is hashed once for the whole build,
376
+ * and a second name for it waits for the same hash.
377
+ */
378
+ const copiedShaderHashes = new Map();
379
+ /** The hash of a generated shader file, read on the pool when a module first names it. */
380
+ const copiedShaderHash = (file) => {
381
+ let hash = copiedShaderHashes.get(file);
382
+ if (hash === undefined) {
383
+ hash = hasher.hash(file);
384
+ copiedShaderHashes.set(file, hash);
385
+ }
386
+ return hash;
387
+ };
388
+ /** A copied shader file's path in the output, whatever the assets folder is called. */
389
+ const assetPath = (name) => (assetsDir === '' ? name : posix.join(assetsDir, name));
390
+ /** Compiles WGSL on worker threads, so the dev server answers other requests meanwhile. */
391
+ const compiler = new CompilerPool();
392
+ /** Keeps each compiled shader in the project's cache, so a later build skips the compile. */
393
+ const shaders = new ShaderCache(() => root, compiler, { disabled: () => noShaderCache });
394
+ /** Custom materials' builds, which load on first use from modules of their own by device. */
395
+ const materialBuilds = new MaterialBuilds();
396
+ /** What the dev server's pages run, to judge each change of WGSL. */
397
+ const hot = new HotState();
398
+ /** The key of a project module's WGSL on the dev server, which builds and packages lack. */
399
+ const keyOf = (id, path, literal) => building || PACKAGE_MODULE.test(id) ? undefined : hotKey(path, literal);
400
+ /** Sends hot updates to the dev server's pages. */
401
+ const sendUpdates = (environment, updates) => {
402
+ environment.logger.info(`null3D hot update ${updates.map((u) => u.key).join(', ')}`, {
403
+ timestamp: true,
404
+ });
405
+ environment.hot.send({ type: 'custom', event: WGSL_UPDATE_EVENT, data: { updates } });
406
+ };
407
+ /**
408
+ * Resolves the engine's import of one of its generated shader modules into the set on this
409
+ * machine: the release asset's, or the one built here. The engine's built files name the
410
+ * modules as the build names them, while the set holds a TypeScript module with its source
411
+ * extension, and a module that the package carries itself stays with it.
412
+ */
413
+ const resolveGenerated = async (source, importer) => {
414
+ const name = ENGINE_GENERATED.exec(source)?.[1];
415
+ if (!name || !importer)
416
+ return null;
417
+ const lib = engineLibFolder(importer);
418
+ if (!lib)
419
+ return null;
420
+ const folder = await engineShaderFolder(lib, {
421
+ fetch: (artifact) => ensureEngineShaders(artifact, reportShaderSource),
422
+ build: () => buildEngineShadersLocally(lib, reportShaderSource),
423
+ });
424
+ if (!folder)
425
+ return null;
426
+ const built = join(folder, name);
427
+ if (existsSync(built))
428
+ return built;
429
+ const asSource = join(folder, name.replace(/\.js$/, '.ts'));
430
+ return existsSync(asSource) ? asSource : null;
431
+ };
432
+ const plugin = {
433
+ name: 'null3d',
434
+ // Runs before Vite's own asset handling, which would copy a sketch file as raw text, and
435
+ // before TypeScript becomes JavaScript, so tagged WGSL sits where the source file has it.
436
+ enforce: 'pre',
437
+ config(config, { mode }) {
438
+ const root = config.root ?? process.cwd();
439
+ const https = options.https
440
+ ? httpsOptions(readCertificate(root, options.certDir ?? DEV_CERT_DIR), !!options.http2)
441
+ : undefined;
442
+ return {
443
+ // Development checks stay in dev builds; release builds drop them as dead code.
444
+ define: {
445
+ __NULL3D_DEV__: JSON.stringify(mode !== 'production'),
446
+ // Without the option, a build that defines the constant itself keeps its value.
447
+ ...(options.urlSwitches === undefined
448
+ ? {}
449
+ : { __NULL3D_URL_SWITCHES__: JSON.stringify(options.urlSwitches) }),
450
+ },
451
+ server: { headers: { ...ISOLATION_HEADERS }, ...(https ? { https, host: true } : {}) },
452
+ preview: { headers: { ...ISOLATION_HEADERS }, ...(https ? { https, host: true } : {}) },
453
+ worker: {
454
+ format: 'es',
455
+ plugins: () => [
456
+ // A worker build keeps only these plugins, so the generated shader files are
457
+ // named here as they are on the page; otherwise every one of them is read
458
+ // into memory to reach the page's bundle through the worker's own.
459
+ streamedShaderAssets,
460
+ workerFilesPlugin(workerFiles),
461
+ workerPreloadPlugin(),
462
+ shaderParagraphsPlugin(),
463
+ {
464
+ // A worker build keeps these plugins alone, so the engine's generated
465
+ // modules resolve here as they do on the page.
466
+ name: 'null3d:engine-generated',
467
+ enforce: 'pre',
468
+ resolveId: {
469
+ filter: { id: ENGINE_GENERATED },
470
+ handler: (source, importer) => resolveGenerated(source, importer),
471
+ },
472
+ },
473
+ ],
474
+ },
475
+ build: {
476
+ assetsInlineLimit: inlineLimit(config.build?.assetsInlineLimit),
477
+ },
478
+ // A prebundled copy of the engine would lose the addresses of its workers and core files,
479
+ // and one of the sound add-on's page half the address of the mixer it loads into the
480
+ // browser's audio thread.
481
+ optimizeDeps: { exclude: ['@null3d/engine', '@null3d/sound'] },
482
+ };
483
+ },
484
+ configResolved(config) {
485
+ building = config.command === 'build';
486
+ buildingPages = building && !config.build.lib && !config.build.ssr;
487
+ root = config.root;
488
+ base = config.base;
489
+ assetsDir = config.build.assetsDir;
490
+ if (config.worker.format !== 'es') {
491
+ config.logger.warn(`null3D: workers build as ${config.worker.format}, not as ES modules, so each engine worker takes in every shader file and grows to tens of MB. Set worker.format to 'es', or leave it unset for the null3D plugin to set.`);
492
+ }
493
+ notices = building && !config.build.ssr ? thirdPartyNotices(root) : null;
494
+ // Vite's `--force` ignores its own caches; it ignores the shader cache too.
495
+ noShaderCache ||= config.optimizeDeps?.force === true;
496
+ },
497
+ buildStart() {
498
+ emitted.clear();
499
+ workerChunks.clear();
500
+ workerModules.clear();
501
+ // The copies follow the generated set: a watch rebuild reads the files again, so a hash
502
+ // from the last build would name old bytes, and a file that went away would be copied.
503
+ copiedShaders.clear();
504
+ copiedShaderHashes.clear();
505
+ earlyCoreId = undefined;
506
+ earlyCoreSought = false;
507
+ if (!building)
508
+ return;
509
+ const missing = missingCoreFiles(root);
510
+ if (missing && missing.length > 0) {
511
+ this.error(`null3D: the installed @null3d/engine lacks its WebAssembly core (${missing.join(', ')}). Reinstall the package; in a copy of the engine's source, run bun run build first.`);
512
+ }
513
+ },
514
+ async buildEnd() {
515
+ await Promise.all([compiler.close(), hasher.close()]);
516
+ },
517
+ // The dev server's pages import the client module of hot updates. A build of pages that
518
+ // imports the engine ships the early script, found from the module that imports the engine,
519
+ // as the engine itself is. The page's own scripts run only once all of them have arrived. The
520
+ // early script imports nothing, so it runs as soon as it arrives, and the core's download
521
+ // starts sooner by the time the others take to arrive and run.
522
+ resolveId: {
523
+ filter: {
524
+ id: [HOT_CLIENT_ADDRESS, MATERIAL_BUILDS_ADDRESS, /^@null3d\/engine$/, ENGINE_GENERATED],
525
+ },
526
+ async handler(source, importer) {
527
+ if (HOT_CLIENT_ADDRESS.test(source))
528
+ return HOT_CLIENT_ID;
529
+ if (MATERIAL_BUILDS_ADDRESS.test(source))
530
+ return source.startsWith('\0') ? source : `\0${source}`;
531
+ // The engine package carries no built shader modules. Its files import them by a name
532
+ // that the installed package's release asset holds, so each import resolves into the
533
+ // cache folder that every project on this machine shares.
534
+ const generated = await resolveGenerated(source, importer);
535
+ if (generated)
536
+ return generated;
537
+ if (!buildingPages || earlyCoreSought)
538
+ return null;
539
+ earlyCoreSought = true;
540
+ const early = await this.resolve(EARLY_CORE_MODULE, importer, { skipSelf: true });
541
+ if (early && !early.external) {
542
+ earlyCoreId = early.id;
543
+ this.emitFile({ type: 'chunk', id: early.id, name: 'early-core' });
544
+ }
545
+ return null;
546
+ },
547
+ },
548
+ transformIndexHtml: {
549
+ order: 'post',
550
+ handler(html, { bundle, chunk, path }) {
551
+ if (!building)
552
+ return [
553
+ {
554
+ tag: 'script',
555
+ attrs: { type: 'module', src: `${base}@id/__x00__${HOT_CLIENT}` },
556
+ injectTo: 'head',
557
+ },
558
+ ];
559
+ if (!earlyCoreId || !bundle || !chunk)
560
+ return;
561
+ const early = Object.values(bundle).find((file) => file.type === 'chunk' && file.facadeModuleId === earlyCoreId);
562
+ const tag = early && earlyCoreTag(early, chunk, bundle, path.replace(/^\//, ''), base);
563
+ return tag ? { html, tags: [tag] } : html;
564
+ },
565
+ },
566
+ load: {
567
+ filter: {
568
+ id: {
569
+ include: [WGSL_FILE, OPTIMIZED_MODEL, HOT_CLIENT_ADDRESS, MATERIAL_BUILDS_ADDRESS],
570
+ },
571
+ },
572
+ async handler(id) {
573
+ if (id === HOT_CLIENT_ID)
574
+ return HOT_CLIENT_CODE;
575
+ if (MATERIAL_BUILDS_ADDRESS.test(id))
576
+ return (materialBuilds.module(id) ??
577
+ this.error(`null3D has no custom material builds named ${id.slice(1)}. Reload the page so the dev server compiles its WGSL again.`));
578
+ // Another plugin's virtual module whose name ends like a WGSL file.
579
+ if (id.startsWith('\0'))
580
+ return;
581
+ if (OPTIMIZED_MODEL.test(id)) {
582
+ const file = id.slice(0, id.indexOf('?'));
583
+ let model;
584
+ try {
585
+ model = await optimizedModel(root, file, options.assets);
586
+ }
587
+ catch (e) {
588
+ return this.error(`null3D could not optimize ${projectPath(root, file)}: ${e.message}`);
589
+ }
590
+ this.addWatchFile(file);
591
+ const address = `${model.key}/${model.name}`;
592
+ if (!building)
593
+ return `export default ${JSON.stringify(`${base}${ASSET_FOLDER}/${address}`)};\n`;
594
+ let ref = '';
595
+ for (const path of model.files) {
596
+ if (!emitted.has(path))
597
+ emitted.set(path, this.emitFile({
598
+ type: 'asset',
599
+ fileName: `${assetsDir}/${ASSET_FOLDER}/${path}`,
600
+ source: readFileSync(join(cacheFolder(root), path)),
601
+ }));
602
+ if (path === address)
603
+ ref = emitted.get(path) ?? '';
604
+ }
605
+ return `export default new URL(import.meta.ROLLUP_FILE_URL_${ref}, import.meta.url).href;\n`;
606
+ }
607
+ const path = projectPath(root, id);
608
+ const compiled = await compileWgslFile(path, id, readFileSync(id, 'utf8'), shaders);
609
+ if ('error' in compiled)
610
+ return this.error(compiled.error);
611
+ for (const warning of compiled.warnings)
612
+ this.warn(warning);
613
+ const key = keyOf(id, path);
614
+ if (key !== undefined)
615
+ hot.remember(key, compiled.shader);
616
+ if (options.wgslDeclarations !== false && !PACKAGE_MODULE.test(id)) {
617
+ try {
618
+ writeWgslDeclaration(id, compiled.shader);
619
+ }
620
+ catch (e) {
621
+ this.warn(`null3D could not write the types of ${projectPath(root, id)} beside it (${e.message}). TypeScript then takes any uniform name for the file.`);
622
+ }
623
+ }
624
+ const pack = new ShaderPack();
625
+ const builds = new ModuleBuilds();
626
+ const value = builds.value(pack, compiled.shader, key);
627
+ return {
628
+ code: `export default ${value};\n${pack.unpacker()}${materialBuilds.finish(id, builds)}`,
629
+ map: { mappings: '' },
630
+ moduleType: 'js',
631
+ };
632
+ },
633
+ },
634
+ transform: {
635
+ filter: {
636
+ id: { exclude: PACKAGE_MODULE },
637
+ code: { include: [WGSL_TAG, 'import.meta.url'] },
638
+ },
639
+ async handler(code, id) {
640
+ const file = id.split('?')[0] ?? id;
641
+ let out;
642
+ if (SCRIPT_FILE.test(file) && WGSL_TAG.test(code)) {
643
+ const path = projectPath(root, file);
644
+ const tagged = await compileTaggedWgsl(code, file, path, shaders);
645
+ if ('error' in tagged)
646
+ return this.error(tagged.error);
647
+ for (const warning of tagged.warnings)
648
+ this.warn(warning);
649
+ const pack = new ShaderPack();
650
+ const builds = new ModuleBuilds();
651
+ for (const [literal, { start, end, shader }] of tagged.shaders.entries()) {
652
+ const key = keyOf(file, path, literal);
653
+ if (key !== undefined)
654
+ hot.remember(key, shader);
655
+ out ??= new MagicString(code);
656
+ out.overwrite(start, end, builds.value(pack, shader, key));
657
+ }
658
+ if (out && !pack.empty)
659
+ out.append(`${pack.unpacker()}${materialBuilds.finish(file, builds)}`);
660
+ if (keyOf(file, path) !== undefined && tagged.shaders.length > 0)
661
+ hot.scripts.set(file, code);
662
+ }
663
+ if (building && code.includes('import.meta.url')) {
664
+ for (const match of code.matchAll(SCRIPT_URL)) {
665
+ const start = match.index;
666
+ if (WORKER_BEFORE.test(code.slice(Math.max(0, start - 40), start)))
667
+ continue;
668
+ const address = match[2] ?? '';
669
+ if (isGeneratedShaderFile(file, address))
670
+ continue;
671
+ const script = await this.resolve(address, id);
672
+ if (!script || !isImportedModule(script.id))
673
+ continue;
674
+ // The worker imports the compiled module by this address, as a sketch or a task.
675
+ const ref = this.emitFile({
676
+ type: 'chunk',
677
+ id: script.id,
678
+ preserveSignature: 'strict',
679
+ });
680
+ workerChunks.add(ref);
681
+ workerModules.add(script.id);
682
+ out ??= new MagicString(code);
683
+ out.overwrite(start, start + match[0].length, `new URL(import.meta.ROLLUP_FILE_URL_${ref}, import.meta.url)`);
684
+ }
685
+ }
686
+ return out
687
+ ? { code: out.toString(), map: out.generateMap({ hires: 'boundary' }) }
688
+ : undefined;
689
+ },
690
+ },
691
+ async hotUpdate({ type, file, modules, read }) {
692
+ const environment = this.environment;
693
+ if (environment.name !== 'client' || type !== 'update' || PACKAGE_MODULE.test(file))
694
+ return;
695
+ if (!modules.some((module) => module.id === file))
696
+ return;
697
+ const path = projectPath(root, file);
698
+ if (WGSL_FILE.test(file)) {
699
+ const compiled = await compileWgslFile(path, file, await read(), shaders);
700
+ if ('error' in compiled) {
701
+ showError(environment, compiled.error);
702
+ return otherModules(modules, file);
703
+ }
704
+ showWarnings(environment, compiled.warnings);
705
+ const key = hotKey(path);
706
+ // Without a hot update, Vite reloads the page as it does for any module.
707
+ if (!hot.swaps(key, compiled.shader))
708
+ return;
709
+ hot.remember(key, compiled.shader);
710
+ sendUpdates(environment, [{ key, shader: compiled.shader }]);
711
+ return otherModules(modules, file);
712
+ }
713
+ const before = hot.scripts.get(file);
714
+ if (before === undefined)
715
+ return;
716
+ const code = await read();
717
+ const changed = changedLiterals(before, code, file);
718
+ if (!changed)
719
+ return;
720
+ const results = await Promise.all(changed.map(({ literal }) => compileLiteral(literal, code, file, path, shaders)));
721
+ const updates = [];
722
+ for (const [k, result] of results.entries()) {
723
+ if ('error' in result) {
724
+ showError(environment, result.error);
725
+ return otherModules(modules, file);
726
+ }
727
+ showWarnings(environment, result.warnings);
728
+ const key = hotKey(path, changed[k]?.index);
729
+ if (!hot.swaps(key, result.shader))
730
+ return;
731
+ updates.push({ key, shader: result.shader });
732
+ }
733
+ // The script's code that pages run changes only once its updates go out, so an edit
734
+ // after an error sends every literal that changed since.
735
+ hot.scripts.set(file, code);
736
+ for (const { key, shader } of updates)
737
+ hot.remember(key, shader);
738
+ if (updates.length > 0)
739
+ sendUpdates(environment, updates);
740
+ return otherModules(modules, file);
741
+ },
742
+ // A worker that imports a script by its address asks for the script's imports only once the
743
+ // script has arrived, so the script names them all. This runs before the build names the
744
+ // files, so each file's name follows its code.
745
+ renderChunk(code, chunk, _options, meta) {
746
+ const module = chunk.facadeModuleId;
747
+ if (!chunk.isEntry || module === null || !workerModules.has(module))
748
+ return null;
749
+ const chunks = meta.chunks;
750
+ if (!chunks)
751
+ return null;
752
+ const edited = new MagicString(code);
753
+ if (!directImports(edited, chunk.fileName, chunks))
754
+ return null;
755
+ return { code: edited.toString(), map: edited.generateMap({ hires: true }) };
756
+ },
757
+ // After Vite's own plugins, which add the worker builds' files and the pages to the bundle.
758
+ generateBundle: {
759
+ order: 'post',
760
+ handler(_options, bundle) {
761
+ // The scripts that a worker imports run there, where the page's preload helper has no
762
+ // document to read.
763
+ if (workerChunks.size > 0)
764
+ emptyWorkerPreloads(bundle, [...workerChunks].map((ref) => this.getFileName(ref)));
765
+ // Each file that names a copy now knows where it sits, so the mark becomes the
766
+ // address from there to the copy's own place in the output. A worker's files reach
767
+ // this bundle as the worker built them, so they take the same pass.
768
+ for (const file of Object.values(bundle)) {
769
+ const text = file.type === 'chunk'
770
+ ? file.code
771
+ : typeof file.source === 'string'
772
+ ? file.source
773
+ : new TextDecoder().decode(file.source);
774
+ if (!text.includes(SHADER_URL_MARK))
775
+ continue;
776
+ const from = posix.dirname(file.fileName);
777
+ const rewritten = text.replaceAll(/__null3d_shader__([^"'`\s)]+)/g, (_match, name) => {
778
+ const address = posix.relative(from, assetPath(name));
779
+ return address.startsWith('.') ? address : `./${address}`;
780
+ });
781
+ if (file.type === 'chunk')
782
+ file.code = rewritten;
783
+ else
784
+ file.source = rewritten;
785
+ }
786
+ const tables = emitParagraphTables.call(this, bundle, root);
787
+ // The copied device modules are not in the bundle, so the tables of shared
788
+ // paragraphs that they import are emitted from here, once each, and each copy's
789
+ // module names them as its loads. Every build that copies the files needs them,
790
+ // whatever it is for.
791
+ const emittedTables = new Set([...tables.values()].flat());
792
+ const loads = new Map();
793
+ for (const [name, source] of copiedShaders) {
794
+ const own = [];
795
+ for (const stem of tableStemsOfFile(source)) {
796
+ const table = assetPath(`${stem}.js`);
797
+ own.push(table);
798
+ if (emittedTables.has(table))
799
+ continue;
800
+ const file = join(dirname(source), `${stem}.js`);
801
+ if (!existsSync(file))
802
+ this.error(`null3D: ${assetPath(name)} imports ${stem}.js, which the engine's shader modules do not hold. Run \`bun run shaders\` again, and reinstall @null3d/engine if the build still fails.`);
803
+ emittedTables.add(table);
804
+ this.emitFile({ type: 'asset', fileName: table, source: readFileSync(file) });
805
+ }
806
+ loads.set(name, own);
807
+ }
808
+ if (buildingPages) {
809
+ const listed = listedFiles(bundle, workerFiles, packageOf, root, tables);
810
+ // The copied shader files are not in the bundle, so the list of files for offline
811
+ // play takes them here, by the module each one holds.
812
+ for (const [name, source] of copiedShaders) {
813
+ const module = engineModule(source, packageOf);
814
+ listed.push({
815
+ fileName: assetPath(name),
816
+ entry: false,
817
+ modules: module === undefined ? [] : [module],
818
+ imports: [],
819
+ loads: loads.get(name) ?? [],
820
+ });
821
+ }
822
+ const files = offlineFiles(listed);
823
+ this.emitFile({
824
+ type: 'asset',
825
+ fileName: FILES_LIST,
826
+ source: `${JSON.stringify(files, null, '\t')}\n`,
827
+ });
828
+ }
829
+ if (notices)
830
+ this.emitFile({ type: 'asset', fileName: NOTICES_FILE, source: notices });
831
+ },
832
+ },
833
+ // A worker's file that another file names must reach the build, whatever Vite decided about
834
+ // the worker. The bundle is whole here, so a missing file is certain, and the build's files
835
+ // and its list of files for offline play take it as they take the others.
836
+ writeBundle: {
837
+ order: 'post',
838
+ handler(options, bundle) {
839
+ const outDir = options.dir;
840
+ if (!outDir)
841
+ return;
842
+ // The generated shader files are copied one at a time, so the build never holds the
843
+ // whole set of builds in memory as a bundle of assets.
844
+ if (copiedShaders.size > 0) {
845
+ const folder = join(outDir, assetsDir);
846
+ mkdirSync(folder, { recursive: true });
847
+ for (const [name, source] of copiedShaders)
848
+ copyFileSync(source, join(folder, name));
849
+ }
850
+ const recovered = missingWorkerAssets(bundle, workerFiles).filter(({ fileName, source }) => !existsSync(join(outDir, fileName)) && existsSync(source));
851
+ if (recovered.length === 0)
852
+ return;
853
+ for (const { fileName, source } of recovered) {
854
+ const path = join(outDir, fileName);
855
+ mkdirSync(dirname(path), { recursive: true });
856
+ writeFileSync(path, readFileSync(source));
857
+ }
858
+ const listPath = join(outDir, FILES_LIST);
859
+ if (!existsSync(listPath))
860
+ return;
861
+ const list = JSON.parse(readFileSync(listPath, 'utf8'));
862
+ for (const { fileName } of recovered) {
863
+ const modules = workerFiles.get(fileName)?.moduleIds ?? [];
864
+ const feature = modules.flatMap((id) => {
865
+ const module = engineModule(id, packageOf);
866
+ return module === undefined ? [] : featuresOf(module);
867
+ })[0];
868
+ if (feature === undefined) {
869
+ if (!list.start.includes(fileName))
870
+ list.start.push(fileName);
871
+ continue;
872
+ }
873
+ list.features[feature] ??= [];
874
+ const files = list.features[feature];
875
+ if (!files.includes(fileName))
876
+ files.push(fileName);
877
+ files.sort();
878
+ }
879
+ list.start.sort();
880
+ const version = createHash('sha256')
881
+ .update(JSON.stringify({ start: list.start, features: list.features }))
882
+ .digest('hex')
883
+ .slice(0, 16);
884
+ writeFileSync(listPath, `${JSON.stringify({ version, start: list.start, features: list.features }, null, '\t')}\n`);
885
+ },
886
+ },
887
+ configureServer(server) {
888
+ // Ahead of every other step, so it sees each answer of the server and its plugins.
889
+ server.middlewares.use(compressAnswers((req) => !fromLoopback(req)));
890
+ server.middlewares.use(queryExtensionMiddleware());
891
+ // The engine's shader modules sit outside the project, in the machine's cache or in the
892
+ // folder that names a set, and the page and its workers reach them from there.
893
+ const allowed = server.config.server.fs.allow;
894
+ for (const shaders of [engineShadersRoot(), process.env[ENGINE_SHADERS_ENV]])
895
+ if (shaders && !allowed.includes(shaders))
896
+ allowed.push(shaders);
897
+ server.middlewares.use(isolationMiddleware);
898
+ server.middlewares.use(`${server.config.base}${ASSET_FOLDER}/`, (req, res, next) => {
899
+ const path = decodeURIComponent((req.url ?? '').split('?')[0]?.slice(1) ?? '');
900
+ const bytes = cachedFile(root, path);
901
+ if (!bytes)
902
+ return next();
903
+ res.setHeader('Content-Type', assetType(path));
904
+ res.setHeader('Cache-Control', 'no-cache');
905
+ res.end(bytes);
906
+ });
907
+ },
908
+ configurePreviewServer(server) {
909
+ const { config } = server;
910
+ // Every visitor gets compressed answers, as from a host: the build's own files from the
911
+ // step below, and the answers of other plugins' routes, such as model files, from this one.
912
+ server.middlewares.use(compressAnswers(() => true));
913
+ server.middlewares.use(queryExtensionMiddleware());
914
+ server.middlewares.use(isolationMiddleware);
915
+ server.middlewares.use(immutableAssetsMiddleware);
916
+ server.middlewares.use(sameOriginMiddleware);
917
+ server.middlewares.use(compressedFiles(resolve(config.root, config.build.outDir), config.base, config.preview.headers));
918
+ },
919
+ };
920
+ /**
921
+ * Names the generated shader files' copies before Vite's own asset step sees them, which runs
922
+ * after the plugins that declare no order. A generated module loads each of its builds by
923
+ * `new URL('./shaders-<name>.js', import.meta.url)`, and a bundler reads every one of them into
924
+ * memory to emit it as an asset; here a pool of worker threads hashes each file and the build
925
+ * copies it on its own, and the module names the copy, so the build never holds the whole set
926
+ * at once.
927
+ *
928
+ * The argument is a mark rather than an address: where a copy lands is fixed, but the file that
929
+ * names it can sit anywhere in the output, and only `generateBundle` knows where.
930
+ */
931
+ const streamedShaderAssets = {
932
+ name: 'null3d:streamed-shader-assets',
933
+ enforce: 'pre',
934
+ apply: 'build',
935
+ async transform(code, id) {
936
+ if (!code.includes('import.meta.url'))
937
+ return;
938
+ const file = id.split('?')[0] ?? id;
939
+ // The files this module names, and the base of the copy name that each one's hash fixes.
940
+ const named = [];
941
+ for (const match of code.matchAll(SCRIPT_URL)) {
942
+ const address = match[2] ?? '';
943
+ if (!isGeneratedShaderFile(file, address))
944
+ continue;
945
+ const target = resolve(dirname(file), address);
946
+ if (!existsSync(target))
947
+ continue;
948
+ const base = target.slice(target.lastIndexOf('/') + 1).replace(/\.js$/, '');
949
+ named.push({ match, base, target });
950
+ }
951
+ if (named.length === 0)
952
+ return;
953
+ // The pool reads each file in chunks and hashes it, so the build's own thread reads none
954
+ // of the files and holds none of their bytes.
955
+ const hashed = await Promise.all(named.map(async ({ match, base, target }) => ({
956
+ match,
957
+ target,
958
+ name: `${base}-${await copiedShaderHash(target)}.js`,
959
+ })));
960
+ let out;
961
+ for (const { match, name, target } of hashed) {
962
+ copiedShaders.set(name, target);
963
+ out ??= new MagicString(code);
964
+ out.overwrite(match.index, match.index + match[0].length, `((u) => new URL(u, import.meta.url))(${JSON.stringify(SHADER_URL_MARK + name)})`);
965
+ }
966
+ return out
967
+ ? { code: out.toString(), map: out.generateMap({ hires: 'boundary' }) }
968
+ : undefined;
969
+ },
970
+ };
971
+ return [streamedShaderAssets, plugin];
972
+ }