@null3d/vite-plugin 0.1.0 → 0.1.2

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.
package/lib/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync, } from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
+ import { tmpdir } from 'node:os';
4
5
  import { dirname, join, posix, relative, resolve, sep } from 'node:path';
5
6
  import MagicString from 'magic-string';
6
7
  import { ASSET_FOLDER, assetType, cachedFile, cacheFolder, OPTIMIZED_MODEL, optimizedModel, } from "./assets.js";
@@ -10,13 +11,14 @@ import { writeWgslDeclaration } from "./declarations.js";
10
11
  import { ENGINE_SHADERS_ENV, engineShaderFolder, engineShadersRoot, ensureEngineShaders, } from "./engine-shaders.js";
11
12
  import { buildEngineShadersLocally } from "./engine-shaders-local.js";
12
13
  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 { changedLiterals, GPU_PATH_EVENT, HOT_CLIENT, HOT_CLIENT_ADDRESS, HOT_CLIENT_ID, HotState, hotClientCode, hotKey, PERMUTATION_WORD_EVENT, UNLISTED_WORD_EVENT, UNSHIPPED_PATH_EVENT, unshippedPathWarning, WGSL_UPDATE_EVENT, } from "./hot.js";
14
15
  import { MATERIAL_BUILDS_ADDRESS, MaterialBuilds, ModuleBuilds } from "./material-builds.js";
15
16
  import { engineModule, FILES_LIST, featuresOf, listedFiles, missingWorkerAssets, offlineFiles, workerFilesPlugin, } from "./offline.js";
16
- import { ShaderPack } from "./pack.js";
17
+ import { narrowShaderPack, ShaderPack, UNPACK } from "./pack.js";
17
18
  import { null3dPackages } from "./package-files.js";
18
- import { emitParagraphTables, shaderParagraphsPlugin, tableStemsOfFile } from "./paragraphs.js";
19
+ import { emitParagraphTables, shaderParagraphsPlugin, tableImportsOfFile } from "./paragraphs.js";
19
20
  import { ShaderCache, shaderCacheOff } from "./shader-cache.js";
21
+ import { builtWords, holdWord, moduleWords, narrowParagraphTable, narrowShaderModule, ShaderList, shaderMarkersModule, shippedTargets, targetOfModule, UNLISTED_MODULE, UnlistedWords, wordText, } from "./shader-list.js";
20
22
  import { compileLiteral, compileTaggedWgsl, compileWgslFile, WGSL_TAG, } from "./wgsl.js";
21
23
  import { directImports, workerPreloadPlugin } from "./worker-preload.js";
22
24
  export { FILES_LIST } from "./offline.js";
@@ -258,8 +260,50 @@ export function emptyWorkerPreloads(bundle, seeds) {
258
260
  */
259
261
  function isGeneratedShaderFile(importer, address) {
260
262
  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
+ return GENERATED_MODULE.test(name) && /^\.\/shaders-[a-z0-9-]+\.js$/.test(address);
264
+ }
265
+ /** The name of one of the engine's generated shader modules: the main module, or one it names. */
266
+ const GENERATED_MODULE = /^shaders(?:-[a-z0-9-]+)?\.[cm]?[jt]s$/;
267
+ /** The name of the generated module that names the words a narrowed shader set holds. */
268
+ const LISTED_MODULE = /^shader-permutations\.[cm]?[jt]s$/;
269
+ /** The start of the name of the module that stands for every device file a list leaves out. */
270
+ const UNLISTED_STEM = 'shaders-unlisted';
271
+ /**
272
+ * The module id that stands for a generated module of a GPU path that a build does not ship. The
273
+ * names that the module exports follow it, so one stub serves every table that exports the same
274
+ * names, such as the tables of builds that need several features.
275
+ */
276
+ const NO_SHADER_MARK = 'null3d:no-shader/';
277
+ const NO_SHADER_ID = `\0${NO_SHADER_MARK}`;
278
+ /** The start of the id of a stub module, with or without Vite's null byte. */
279
+ const NO_SHADER_PATTERN = /^\0?null3d:no-shader\//;
280
+ /** The code of a stub module, which exports each name that it stands for as an empty object. */
281
+ function stubModule(names) {
282
+ return `${names.map((name) => `export const ${name} = {};`).join('\n')}\n`;
283
+ }
284
+ /**
285
+ * True for the folder of a generated shader set, which holds the marker module that every set has.
286
+ * Only a module of such a folder takes a stub, so a project's own file that happens to share a name
287
+ * never does.
288
+ */
289
+ function inShaderSet(folder) {
290
+ return ['shader-permutations.ts', 'shader-permutations.js'].some((name) => existsSync(join(folder, name)));
291
+ }
292
+ /**
293
+ * The names that a generated shader module exports, in the order the shader build writes them. The
294
+ * stub of a module that a build drops exports the same names, so every import of it resolves.
295
+ */
296
+ function exportNamesOf(text, file) {
297
+ const names = [...text.matchAll(/^export (?:const|function|class) ([A-Za-z_$][\w$]*)/gm)].map((match) => match[1]);
298
+ if (names.length === 0)
299
+ throw new Error(`null3D cannot read the exports of the engine's shader module ${file}, so it cannot stand an empty one in its place. Install the same version of @null3d/vite-plugin as of @null3d/engine, or run bun run shaders in a checkout.`);
300
+ return names;
301
+ }
302
+ /** The docs on a project's list of permutation words, which the build's report names. */
303
+ const SHADER_LIST_DOCS = 'https://github.com/null3d-engine/null3d/blob/generated/docs/guides/assets-pipeline.md#build-only-the-shader-permutations-you-draw-with';
304
+ /** A number of bytes in megabytes, as the build's report gives it. */
305
+ function megabytes(bytes) {
306
+ return `${Math.round(bytes / 1e6).toLocaleString('en-US')} MB`;
263
307
  }
264
308
  /** A WGSL file that a module imports, without a query such as `?raw`. */
265
309
  const WGSL_FILE = /\.wgsl$/;
@@ -342,6 +386,11 @@ export default function null3d(options = {}) {
342
386
  let building = false;
343
387
  /** True for a production build of pages, which gets the early script. */
344
388
  let buildingPages = false;
389
+ /**
390
+ * The GPU paths whose shaders a build ships. The dev server keeps both, so a developer can test
391
+ * the other path, and a build narrows the set and the project's own shaders to this.
392
+ */
393
+ const shipped = shippedTargets(options.shaders);
345
394
  /** The early script's module, once a build of pages that imports the engine has added it. */
346
395
  let earlyCoreId;
347
396
  /** True once the build has looked for the early script. */
@@ -371,20 +420,70 @@ export default function null3d(options = {}) {
371
420
  */
372
421
  const copiedShaders = new Map();
373
422
  /**
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.
423
+ * The copy of each generated shader file by its path, which the pool works out. A page build and
424
+ * its workers reach the same files, so each file is read once for the whole build, and a second
425
+ * name for it waits for the same copy.
426
+ */
427
+ const shaderCopies = new Map();
428
+ /** The tables of shared paragraphs that the copies import, which the build emits beside them. */
429
+ const copiedTables = { files: 0, bytes: 0 };
430
+ /** The project's list of permutation words, in a build whose options name one. */
431
+ let shaderList;
432
+ /** Each word that a build of the engine's shader set answers, as this build has read them. */
433
+ const heldWords = new Set();
434
+ /** The folder of this build's narrowed copies, made when the first one is written. */
435
+ let narrowedFolder;
436
+ /** Writes the text of a narrowed copy, named by its hash, into this build's folder of them. */
437
+ const narrowedCopy = (stem, text, source) => {
438
+ narrowedFolder ??= mkdtempSync(join(tmpdir(), 'null3d-shaders-'));
439
+ const name = `${stem}-${createHash('sha256').update(text).digest('hex').slice(0, 8)}.js`;
440
+ const bytes = join(narrowedFolder, name);
441
+ if (!existsSync(bytes))
442
+ writeFileSync(bytes, text);
443
+ return { name, bytes, source: source ?? bytes };
444
+ };
445
+ /**
446
+ * The copy of a generated shader file. A file of a GPU path that this build does not ship gives
447
+ * way to one module without builds, and the build copies it for every such file. With a list, a
448
+ * file whose builds the list all names stays whole, a file of which it names some keeps only
449
+ * those, and a file of which it names none gives way to one module without builds.
377
450
  */
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);
451
+ const copyOf = async (file) => {
452
+ const stem = file.slice(file.lastIndexOf('/') + 1).replace(/\.js$/, '');
453
+ const target = targetOfModule(file);
454
+ if (target !== null && !shipped[target]) {
455
+ // The words of a dropped file still answer the project's list, which may hold a word that
456
+ // only the other GPU path builds, such as a morph target's.
457
+ if (shaderList !== undefined)
458
+ for (const word of (await hasher.scan(file)).words)
459
+ holdWord(heldWords, word);
460
+ return narrowedCopy(UNLISTED_STEM, UNLISTED_MODULE);
385
461
  }
386
- return hash;
462
+ const list = shaderList;
463
+ if (list === undefined)
464
+ return { name: `${stem}-${await hasher.hash(file)}.js`, bytes: file, source: file };
465
+ const { hash, words } = await hasher.scan(file);
466
+ for (const word of words)
467
+ holdWord(heldWords, word);
468
+ const kept = words.filter((word) => list.holds(word)).length;
469
+ if (kept === words.length)
470
+ return { name: `${stem}-${hash}.js`, bytes: file, source: file };
471
+ if (kept === 0)
472
+ return narrowedCopy(UNLISTED_STEM, UNLISTED_MODULE);
473
+ const narrowed = narrowShaderModule(readFileSync(file, 'utf8'), (word) => list.holds(word), file);
474
+ return narrowedCopy(stem, narrowed.text, file);
387
475
  };
476
+ /** The copy of a generated shader file, worked out on the pool when a module first names it. */
477
+ const shaderCopy = (file) => {
478
+ let copy = shaderCopies.get(file);
479
+ if (copy === undefined) {
480
+ copy = copyOf(file);
481
+ shaderCopies.set(file, copy);
482
+ }
483
+ return copy;
484
+ };
485
+ /** Vite's logger, for the build's report of the shader files it copied. */
486
+ let logger;
388
487
  /** A copied shader file's path in the output, whatever the assets folder is called. */
389
488
  const assetPath = (name) => (assetsDir === '' ? name : posix.join(assetsDir, name));
390
489
  /** Compiles WGSL on worker threads, so the dev server answers other requests meanwhile. */
@@ -392,7 +491,7 @@ export default function null3d(options = {}) {
392
491
  /** Keeps each compiled shader in the project's cache, so a later build skips the compile. */
393
492
  const shaders = new ShaderCache(() => root, compiler, { disabled: () => noShaderCache });
394
493
  /** Custom materials' builds, which load on first use from modules of their own by device. */
395
- const materialBuilds = new MaterialBuilds();
494
+ const materialBuilds = new MaterialBuilds(() => !building || shipped.glsl);
396
495
  /** What the dev server's pages run, to judge each change of WGSL. */
397
496
  const hot = new HotState();
398
497
  /** The key of a project module's WGSL on the dev server, which builds and packages lack. */
@@ -429,6 +528,21 @@ export default function null3d(options = {}) {
429
528
  const asSource = join(folder, name.replace(/\.js$/, '.ts'));
430
529
  return existsSync(asSource) ? asSource : null;
431
530
  };
531
+ /**
532
+ * Reports the shader files that the build copied. Without a list, the build copied the whole
533
+ * set, which a host stores although a page downloads a few files of it, so the report warns and
534
+ * names the way to copy less.
535
+ */
536
+ const reportShaderCopies = (files, bytes) => {
537
+ const copied = `null3D: copied ${files.toLocaleString('en-US')} shader files, ${megabytes(bytes)}`;
538
+ const paths = shipped.glsl ? '' : ' for the WebGPU path alone';
539
+ if (shaderList !== undefined)
540
+ logger?.info(`${copied}${paths}: the builds of the ${shaderList.words.size} permutation words of ${shaderList.file}.`);
541
+ else if (!shipped.glsl)
542
+ logger?.info(`${copied}: every build of every permutation word of the WebGPU path. A page downloads only the few that its device needs. Record the words that your pages draw with in a list, and name it in the plugin's shaders.list option, to copy only their builds: ${SHADER_LIST_DOCS}`);
543
+ else
544
+ logger?.warn(`${copied}: every build of every permutation word in the engine's shader set. A page downloads only the few that its device needs, but the host stores them all. Record the words that your pages draw with in a list, and name it in the plugin's shaders.list option, to copy only their builds: ${SHADER_LIST_DOCS}`);
545
+ };
432
546
  const plugin = {
433
547
  name: 'null3d',
434
548
  // Runs before Vite's own asset handling, which would copy a sketch file as raw text, and
@@ -491,6 +605,7 @@ export default function null3d(options = {}) {
491
605
  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
606
  }
493
607
  notices = building && !config.build.ssr ? thirdPartyNotices(root) : null;
608
+ logger = config.logger;
494
609
  // Vite's `--force` ignores its own caches; it ignores the shader cache too.
495
610
  noShaderCache ||= config.optimizeDeps?.force === true;
496
611
  },
@@ -501,11 +616,29 @@ export default function null3d(options = {}) {
501
616
  // The copies follow the generated set: a watch rebuild reads the files again, so a hash
502
617
  // from the last build would name old bytes, and a file that went away would be copied.
503
618
  copiedShaders.clear();
504
- copiedShaderHashes.clear();
619
+ shaderCopies.clear();
620
+ copiedTables.files = 0;
621
+ copiedTables.bytes = 0;
622
+ heldWords.clear();
623
+ // A rebuild reads the dropped files again, so the scan must answer the new list too.
624
+ scannedWords.clear();
625
+ if (narrowedFolder !== undefined)
626
+ rmSync(narrowedFolder, { recursive: true, force: true });
627
+ narrowedFolder = undefined;
628
+ shaderList = undefined;
505
629
  earlyCoreId = undefined;
506
630
  earlyCoreSought = false;
507
631
  if (!building)
508
632
  return;
633
+ const list = options.shaders?.list;
634
+ if (list !== undefined) {
635
+ try {
636
+ shaderList = ShaderList.read(resolve(root, list), list);
637
+ }
638
+ catch (error) {
639
+ this.error(`null3D: ${error.message}`);
640
+ }
641
+ }
509
642
  const missing = missingCoreFiles(root);
510
643
  if (missing && missing.length > 0) {
511
644
  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.`);
@@ -514,6 +647,11 @@ export default function null3d(options = {}) {
514
647
  async buildEnd() {
515
648
  await Promise.all([compiler.close(), hasher.close()]);
516
649
  },
650
+ closeBundle() {
651
+ if (narrowedFolder !== undefined)
652
+ rmSync(narrowedFolder, { recursive: true, force: true });
653
+ narrowedFolder = undefined;
654
+ },
517
655
  // The dev server's pages import the client module of hot updates. A build of pages that
518
656
  // imports the engine ships the early script, found from the module that imports the engine,
519
657
  // as the engine itself is. The page's own scripts run only once all of them have arrived. The
@@ -571,7 +709,7 @@ export default function null3d(options = {}) {
571
709
  },
572
710
  async handler(id) {
573
711
  if (id === HOT_CLIENT_ID)
574
- return HOT_CLIENT_CODE;
712
+ return hotClientCode(options.shaders?.list !== undefined, !shipped.glsl);
575
713
  if (MATERIAL_BUILDS_ADDRESS.test(id))
576
714
  return (materialBuilds.module(id) ??
577
715
  this.error(`null3D has no custom material builds named ${id.slice(1)}. Reload the page so the dev server compiles its WGSL again.`));
@@ -605,7 +743,7 @@ export default function null3d(options = {}) {
605
743
  return `export default new URL(import.meta.ROLLUP_FILE_URL_${ref}, import.meta.url).href;\n`;
606
744
  }
607
745
  const path = projectPath(root, id);
608
- const compiled = await compileWgslFile(path, id, readFileSync(id, 'utf8'), shaders);
746
+ const compiled = await compileWgslFile(path, id, readFileSync(id, 'utf8'), shaders, !building || shipped.glsl);
609
747
  if ('error' in compiled)
610
748
  return this.error(compiled.error);
611
749
  for (const warning of compiled.warnings)
@@ -622,7 +760,7 @@ export default function null3d(options = {}) {
622
760
  }
623
761
  }
624
762
  const pack = new ShaderPack();
625
- const builds = new ModuleBuilds();
763
+ const builds = new ModuleBuilds(!building || shipped.glsl);
626
764
  const value = builds.value(pack, compiled.shader, key);
627
765
  return {
628
766
  code: `export default ${value};\n${pack.unpacker()}${materialBuilds.finish(id, builds)}`,
@@ -641,13 +779,13 @@ export default function null3d(options = {}) {
641
779
  let out;
642
780
  if (SCRIPT_FILE.test(file) && WGSL_TAG.test(code)) {
643
781
  const path = projectPath(root, file);
644
- const tagged = await compileTaggedWgsl(code, file, path, shaders);
782
+ const tagged = await compileTaggedWgsl(code, file, path, shaders, !building || shipped.glsl);
645
783
  if ('error' in tagged)
646
784
  return this.error(tagged.error);
647
785
  for (const warning of tagged.warnings)
648
786
  this.warn(warning);
649
787
  const pack = new ShaderPack();
650
- const builds = new ModuleBuilds();
788
+ const builds = new ModuleBuilds(!building || shipped.glsl);
651
789
  for (const [literal, { start, end, shader }] of tagged.shaders.entries()) {
652
790
  const key = keyOf(file, path, literal);
653
791
  if (key !== undefined)
@@ -696,7 +834,7 @@ export default function null3d(options = {}) {
696
834
  return;
697
835
  const path = projectPath(root, file);
698
836
  if (WGSL_FILE.test(file)) {
699
- const compiled = await compileWgslFile(path, file, await read(), shaders);
837
+ const compiled = await compileWgslFile(path, file, await read(), shaders, !building || shipped.glsl);
700
838
  if ('error' in compiled) {
701
839
  showError(environment, compiled.error);
702
840
  return otherModules(modules, file);
@@ -717,7 +855,7 @@ export default function null3d(options = {}) {
717
855
  const changed = changedLiterals(before, code, file);
718
856
  if (!changed)
719
857
  return;
720
- const results = await Promise.all(changed.map(({ literal }) => compileLiteral(literal, code, file, path, shaders)));
858
+ const results = await Promise.all(changed.map(({ literal }) => compileLiteral(literal, code, file, path, shaders, !building || shipped.glsl)));
721
859
  const updates = [];
722
860
  for (const [k, result] of results.entries()) {
723
861
  if ('error' in result) {
@@ -762,6 +900,8 @@ export default function null3d(options = {}) {
762
900
  // document to read.
763
901
  if (workerChunks.size > 0)
764
902
  emptyWorkerPreloads(bundle, [...workerChunks].map((ref) => this.getFileName(ref)));
903
+ /** True for a build with a list that reached the engine's shader set. */
904
+ const listing = shaderList !== undefined && copiedShaders.size > 0;
765
905
  // Each file that names a copy now knows where it sits, so the mark becomes the
766
906
  // address from there to the copy's own place in the output. A worker's files reach
767
907
  // this bundle as the worker built them, so they take the same pass.
@@ -771,6 +911,12 @@ export default function null3d(options = {}) {
771
911
  : typeof file.source === 'string'
772
912
  ? file.source
773
913
  : new TextDecoder().decode(file.source);
914
+ // The builds that the bundle holds answer their words: the set's own main module,
915
+ // and the project's custom materials and add-on shaders, in the worker builds' files
916
+ // too.
917
+ if (listing)
918
+ for (const word of builtWords(text))
919
+ holdWord(heldWords, word);
774
920
  if (!text.includes(SHADER_URL_MARK))
775
921
  continue;
776
922
  const from = posix.dirname(file.fileName);
@@ -783,6 +929,11 @@ export default function null3d(options = {}) {
783
929
  else
784
930
  file.source = rewritten;
785
931
  }
932
+ // A listed word that no build answers, a copied one or one that the bundle holds,
933
+ // would fail its pipeline on a device, so the build fails first and names it.
934
+ const missing = listing ? (shaderList?.missing(heldWords) ?? []) : [];
935
+ if (missing.length > 0)
936
+ this.error(`null3D: the shader list ${shaderList?.file} names ${missing.map(wordText).join(', ')}, which no shader build of this project holds: none of the engine's shader set and none of its own shaders. Record the list again against this version of the engine with bunx @null3d/cli shaders record, or remove the word. A set that ${ENGINE_SHADERS_ENV} names must hold every listed word.`);
786
937
  const tables = emitParagraphTables.call(this, bundle, root);
787
938
  // The copied device modules are not in the bundle, so the tables of shared
788
939
  // paragraphs that they import are emitted from here, once each, and each copy's
@@ -790,27 +941,45 @@ export default function null3d(options = {}) {
790
941
  // whatever it is for.
791
942
  const emittedTables = new Set([...tables.values()].flat());
792
943
  const loads = new Map();
793
- for (const [name, source] of copiedShaders) {
944
+ /** The file of each table that the copies import, by its place in the output. */
945
+ const tableFiles = new Map();
946
+ /** The names that the copies import from each of those tables. */
947
+ const tableNames = new Map();
948
+ for (const [name, copy] of copiedShaders) {
794
949
  const own = [];
795
- for (const stem of tableStemsOfFile(source)) {
950
+ for (const { stem, names } of tableImportsOfFile(copy.bytes)) {
796
951
  const table = assetPath(`${stem}.js`);
797
952
  own.push(table);
798
953
  if (emittedTables.has(table))
799
954
  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) });
955
+ if (!tableFiles.has(table)) {
956
+ const file = join(dirname(copy.source), `${stem}.js`);
957
+ if (!existsSync(file))
958
+ 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.`);
959
+ tableFiles.set(table, file);
960
+ tableNames.set(table, new Set());
961
+ }
962
+ for (const imported of names)
963
+ tableNames.get(table)?.add(imported);
805
964
  }
806
965
  loads.set(name, own);
807
966
  }
967
+ // With a list, a table keeps only the paragraphs that the narrowed copies import.
968
+ for (const [table, file] of tableFiles) {
969
+ const whole = readFileSync(file);
970
+ const source = shaderList === undefined
971
+ ? whole
972
+ : Buffer.from(narrowParagraphTable(whole.toString('utf8'), tableNames.get(table) ?? new Set(), file));
973
+ copiedTables.files++;
974
+ copiedTables.bytes += source.length;
975
+ this.emitFile({ type: 'asset', fileName: table, source });
976
+ }
808
977
  if (buildingPages) {
809
978
  const listed = listedFiles(bundle, workerFiles, packageOf, root, tables);
810
979
  // The copied shader files are not in the bundle, so the list of files for offline
811
980
  // play takes them here, by the module each one holds.
812
- for (const [name, source] of copiedShaders) {
813
- const module = engineModule(source, packageOf);
981
+ for (const [name, copy] of copiedShaders) {
982
+ const module = engineModule(copy.source, packageOf);
814
983
  listed.push({
815
984
  fileName: assetPath(name),
816
985
  entry: false,
@@ -844,8 +1013,12 @@ export default function null3d(options = {}) {
844
1013
  if (copiedShaders.size > 0) {
845
1014
  const folder = join(outDir, assetsDir);
846
1015
  mkdirSync(folder, { recursive: true });
847
- for (const [name, source] of copiedShaders)
848
- copyFileSync(source, join(folder, name));
1016
+ let bytes = copiedTables.bytes;
1017
+ for (const [name, copy] of copiedShaders) {
1018
+ copyFileSync(copy.bytes, join(folder, name));
1019
+ bytes += statSync(copy.bytes).size;
1020
+ }
1021
+ reportShaderCopies(copiedShaders.size + copiedTables.files, bytes);
849
1022
  }
850
1023
  const recovered = missingWorkerAssets(bundle, workerFiles).filter(({ fileName, source }) => !existsSync(join(outDir, fileName)) && existsSync(source));
851
1024
  if (recovered.length === 0)
@@ -895,6 +1068,41 @@ export default function null3d(options = {}) {
895
1068
  if (shaders && !allowed.includes(shaders))
896
1069
  allowed.push(shaders);
897
1070
  server.middlewares.use(isolationMiddleware);
1071
+ // The dev server draws with the whole shader set. It warns about each word that a page
1072
+ // draws with and the project's list lacks, because a production build stops that page.
1073
+ const list = options.shaders?.list;
1074
+ if (list !== undefined) {
1075
+ const unlisted = new UnlistedWords(resolve(server.config.root, list), list);
1076
+ server.environments.client.hot.on(PERMUTATION_WORD_EVENT, (data, client) => {
1077
+ const { word, page } = (data ?? {});
1078
+ if (typeof word !== 'number' || typeof page !== 'string')
1079
+ return;
1080
+ const warning = unlisted.check(word, page);
1081
+ if (warning === undefined)
1082
+ return;
1083
+ if (warning.first)
1084
+ server.config.logger.warn(`null3D: ${warning.message}`, { timestamp: true });
1085
+ client.send(UNLISTED_WORD_EVENT, { message: warning.message });
1086
+ });
1087
+ }
1088
+ // The dev server draws with both GPU paths. It warns when a page draws with a path that a
1089
+ // production build with these options does not ship, because that build stops the page.
1090
+ if (!shipped.glsl) {
1091
+ const warned = new Set();
1092
+ server.environments.client.hot.on(GPU_PATH_EVENT, (data, client) => {
1093
+ const { path, page } = (data ?? {});
1094
+ if (typeof path !== 'string' || typeof page !== 'string')
1095
+ return;
1096
+ if (warned.has(page))
1097
+ return;
1098
+ const message = unshippedPathWarning(path, page, shipped.glsl);
1099
+ if (message === undefined)
1100
+ return;
1101
+ warned.add(page);
1102
+ server.config.logger.warn(`null3D: ${message}`, { timestamp: true });
1103
+ client.send(UNSHIPPED_PATH_EVENT, { message });
1104
+ });
1105
+ }
898
1106
  server.middlewares.use(`${server.config.base}${ASSET_FOLDER}/`, (req, res, next) => {
899
1107
  const path = decodeURIComponent((req.url ?? '').split('?')[0]?.slice(1) ?? '');
900
1108
  const bytes = cachedFile(root, path);
@@ -917,13 +1125,37 @@ export default function null3d(options = {}) {
917
1125
  server.middlewares.use(compressedFiles(resolve(config.root, config.build.outDir), config.base, config.preview.headers));
918
1126
  },
919
1127
  };
1128
+ /** The device files whose words this build has read for the project's shader list. */
1129
+ const scannedWords = new Set();
1130
+ /**
1131
+ * Adds to `heldWords` the words of every device file that a generated module names. A build
1132
+ * that drops the module must still answer the project's list with its words, which the module's
1133
+ * own text does not hold: a table of combined builds names them through the addresses below.
1134
+ */
1135
+ const holdNamedWords = (text, file) => {
1136
+ if (shaderList === undefined)
1137
+ return;
1138
+ for (const match of text.matchAll(SCRIPT_URL)) {
1139
+ const address = match[2] ?? '';
1140
+ if (!isGeneratedShaderFile(file, address))
1141
+ continue;
1142
+ const named = resolve(dirname(file), address);
1143
+ if (scannedWords.has(named) || !existsSync(named))
1144
+ continue;
1145
+ scannedWords.add(named);
1146
+ for (const word of moduleWords(readFileSync(named, 'utf8')))
1147
+ holdWord(heldWords, word);
1148
+ }
1149
+ };
920
1150
  /**
921
1151
  * Names the generated shader files' copies before Vite's own asset step sees them, which runs
922
1152
  * after the plugins that declare no order. A generated module loads each of its builds by
923
1153
  * `new URL('./shaders-<name>.js', import.meta.url)`, and a bundler reads every one of them into
924
1154
  * memory to emit it as an asset; here a pool of worker threads hashes each file and the build
925
1155
  * copies it on its own, and the module names the copy, so the build never holds the whole set
926
- * at once.
1156
+ * at once. With a list of words, each copy holds only the listed builds, and the set's module of
1157
+ * listed words names the project's list. With a GPU path set, a file of the other path gives way
1158
+ * to one module without builds, so the build copies none of that path's text.
927
1159
  *
928
1160
  * The argument is a mark rather than an address: where a copy lands is fixed, but the file that
929
1161
  * names it can sit anywhere in the output, and only `generateBundle` knows where.
@@ -933,39 +1165,116 @@ export default function null3d(options = {}) {
933
1165
  enforce: 'pre',
934
1166
  apply: 'build',
935
1167
  async transform(code, id) {
936
- if (!code.includes('import.meta.url'))
937
- return;
938
1168
  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.
1169
+ // The engine names a missing word as one that the list lacks, and the list to record.
1170
+ const name = file.slice(file.lastIndexOf('/') + 1);
1171
+ if ((shaderList !== undefined || !shipped.glsl) &&
1172
+ LISTED_MODULE.test(name) &&
1173
+ inShaderSet(dirname(file)) &&
1174
+ code.includes('LISTED_PERMUTATIONS')) {
1175
+ // The engine reads the shipped paths from the same module. A set that predates the
1176
+ // constant would keep both paths, so the build refuses rather than ship one silently.
1177
+ if (!code.includes('SHIPPED_GPU_PATHS'))
1178
+ this.error("null3D: the engine's shader set is older than the plugin: its shader-permutations module has no SHIPPED_GPU_PATHS. Install the same version of @null3d/engine as of @null3d/vite-plugin, or run bun run shaders in a checkout.");
1179
+ return {
1180
+ code: shaderMarkersModule(shaderList?.words ?? null, shipped.glsl ? null : ['webgpu']),
1181
+ map: null,
1182
+ };
1183
+ }
1184
+ let text = code;
1185
+ let changed = false;
1186
+ // An add-on package's compiled shaders keep both GPU paths, which a build that ships one
1187
+ // path drops here, including the modules of the other path's build sets.
1188
+ if (!shipped.glsl && text.includes(UNPACK)) {
1189
+ text = narrowShaderPack(text, file);
1190
+ changed = true;
1191
+ }
1192
+ if (!text.includes('import.meta.url'))
1193
+ return changed ? { code: text, map: null } : undefined;
1194
+ // The files this module names.
940
1195
  const named = [];
941
- for (const match of code.matchAll(SCRIPT_URL)) {
1196
+ for (const match of text.matchAll(SCRIPT_URL)) {
942
1197
  const address = match[2] ?? '';
943
1198
  if (!isGeneratedShaderFile(file, address))
944
1199
  continue;
945
1200
  const target = resolve(dirname(file), address);
946
1201
  if (!existsSync(target))
947
1202
  continue;
948
- const base = target.slice(target.lastIndexOf('/') + 1).replace(/\.js$/, '');
949
- named.push({ match, base, target });
1203
+ named.push({ match, target });
950
1204
  }
951
1205
  if (named.length === 0)
952
- return;
1206
+ return changed ? { code: text, map: null } : undefined;
953
1207
  // 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
- })));
1208
+ // of the files and holds none of their bytes; only a file that a list narrows is read
1209
+ // here, to write the copy of its listed builds.
1210
+ const copies = await Promise.all(named.map(async ({ match, target }) => ({ match, copy: await shaderCopy(target) })));
960
1211
  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)})`);
1212
+ for (const { match, copy } of copies) {
1213
+ copiedShaders.set(copy.name, copy);
1214
+ out ??= new MagicString(text);
1215
+ out.overwrite(match.index, match.index + match[0].length, `((u) => new URL(u, import.meta.url))(${JSON.stringify(SHADER_URL_MARK + copy.name)})`);
965
1216
  }
966
- return out
967
- ? { code: out.toString(), map: out.generateMap({ hires: 'boundary' }) }
968
- : undefined;
1217
+ if (out === undefined)
1218
+ return changed ? { code: text, map: null } : undefined;
1219
+ return { code: out.toString(), map: out.generateMap({ hires: 'boundary' }) };
1220
+ },
1221
+ // A generated module of a GPU path that this build does not ship, named by a module of the
1222
+ // set itself, such as a table of builds that need several features, takes the place of one
1223
+ // stub module. The stub exports the names of the module it stands for, so every import of it
1224
+ // resolves, and the lookups find no build rather than failing to load the module.
1225
+ resolveId: {
1226
+ filter: { id: /^\.\/shaders(?:-[a-z0-9-]+)+$/ },
1227
+ handler(source, importer) {
1228
+ if (shipped.glsl || importer === undefined)
1229
+ return;
1230
+ const importerFile = importer.split('?')[0] ?? importer;
1231
+ const importerName = importerFile.slice(importerFile.lastIndexOf('/') + 1);
1232
+ if (!GENERATED_MODULE.test(importerName))
1233
+ return;
1234
+ if (!inShaderSet(dirname(importerFile)))
1235
+ return;
1236
+ if (targetOfModule(source) !== 'glsl')
1237
+ return;
1238
+ const named = resolve(dirname(importerFile), source);
1239
+ const file = [named, `${named}.ts`, `${named}.js`].find((path) => existsSync(path));
1240
+ if (file === undefined)
1241
+ return;
1242
+ const text = readFileSync(file, 'utf8');
1243
+ holdNamedWords(text, file);
1244
+ return `${NO_SHADER_ID}${exportNamesOf(text, file).join(',')}`;
1245
+ },
1246
+ },
1247
+ // A dropped generated module that a module imports by name, such as a whole shader that loads
1248
+ // on first use, gives way to a stub of the same exports. Its words still answer a project's
1249
+ // shader list, which may hold a word that only the other GPU path builds.
1250
+ load: {
1251
+ filter: {
1252
+ id: { include: [/shaders(?:-[a-z0-9-]+)?\.[cm]?[jt]s$/, NO_SHADER_PATTERN] },
1253
+ },
1254
+ handler(id) {
1255
+ const bare = id.startsWith('\0') ? id.slice(1) : id;
1256
+ if (bare.startsWith(NO_SHADER_MARK))
1257
+ return stubModule(bare
1258
+ .slice(NO_SHADER_MARK.length)
1259
+ .split(',')
1260
+ .filter((name) => name !== ''));
1261
+ if (shipped.glsl)
1262
+ return;
1263
+ const file = id.split('?')[0] ?? id;
1264
+ const name = file.slice(file.lastIndexOf('/') + 1);
1265
+ if (!GENERATED_MODULE.test(name))
1266
+ return;
1267
+ if (!inShaderSet(dirname(file)))
1268
+ return;
1269
+ if (targetOfModule(name) !== 'glsl')
1270
+ return;
1271
+ const text = readFileSync(file, 'utf8');
1272
+ if (shaderList !== undefined)
1273
+ for (const word of moduleWords(text))
1274
+ holdWord(heldWords, word);
1275
+ holdNamedWords(text, file);
1276
+ return stubModule(exportNamesOf(text, file));
1277
+ },
969
1278
  },
970
1279
  };
971
1280
  return [streamedShaderAssets, plugin];