@null3d/vite-plugin 0.0.0-stage → 0.0.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 (50) hide show
  1. package/LICENSE-APACHE +176 -0
  2. package/LICENSE-MIT +21 -0
  3. package/THIRD-PARTY-NOTICES.txt +398 -0
  4. package/dist/shader-compiler.stamp.json +4 -0
  5. package/dist/shader-compiler.wasm +0 -0
  6. package/lib/assets.d.ts +94 -0
  7. package/lib/assets.js +189 -0
  8. package/lib/client.d.ts +21 -0
  9. package/lib/compile-pool.d.ts +25 -0
  10. package/lib/compile-pool.js +90 -0
  11. package/lib/compile-worker.js +11 -0
  12. package/lib/compiler-calls.d.ts +26 -0
  13. package/lib/compiler-calls.js +97 -0
  14. package/lib/compiler-stamp.d.ts +8 -0
  15. package/lib/compiler-stamp.js +34 -0
  16. package/lib/declarations.d.ts +10 -0
  17. package/lib/declarations.js +80 -0
  18. package/lib/engine-shaders-local.d.ts +6 -0
  19. package/lib/engine-shaders-local.js +75 -0
  20. package/lib/engine-shaders.d.ts +61 -0
  21. package/lib/engine-shaders.js +170 -0
  22. package/lib/hash-pool.d.ts +24 -0
  23. package/lib/hash-pool.js +84 -0
  24. package/lib/hash-worker.js +53 -0
  25. package/lib/hot.d.ts +53 -0
  26. package/lib/hot.js +101 -0
  27. package/lib/index.d.ts +95 -0
  28. package/lib/index.js +895 -0
  29. package/lib/material-builds.d.ts +91 -0
  30. package/lib/material-builds.js +236 -0
  31. package/lib/offline.d.ts +92 -0
  32. package/lib/offline.js +304 -0
  33. package/lib/pack.d.ts +30 -0
  34. package/lib/pack.js +112 -0
  35. package/lib/package-files.d.ts +12 -0
  36. package/lib/package-files.js +39 -0
  37. package/lib/paragraphs.d.ts +19 -0
  38. package/lib/paragraphs.js +131 -0
  39. package/lib/shader-cache.d.ts +59 -0
  40. package/lib/shader-cache.js +213 -0
  41. package/lib/shader-compiler.d.ts +258 -0
  42. package/lib/shader-compiler.js +169 -0
  43. package/lib/shader-types.d.ts +261 -0
  44. package/lib/shader-types.js +4 -0
  45. package/lib/wgsl.d.ts +118 -0
  46. package/lib/wgsl.js +446 -0
  47. package/lib/worker-preload.d.ts +17 -0
  48. package/lib/worker-preload.js +65 -0
  49. package/package.json +69 -5
  50. package/README.md +0 -3
@@ -0,0 +1,80 @@
1
+ // The declarations that the plugin writes beside the `.wgsl` files that a project's modules import.
2
+ // TypeScript cannot read WGSL, so the client types give a `.wgsl` import a general type, which takes
3
+ // any uniform name. A declaration beside the file, `glow.wgsl.d.ts` beside `glow.wgsl`, takes its
4
+ // place: it names the kind of shader, the type of each uniform of `struct Uniforms` and the name
5
+ // of each texture, so that `materials.shader` checks the names and values that its `uniforms` and
6
+ // `textures` options and `set()` get, and `post.addEffect` and `post.setEffectUniform` check an
7
+ // effect's.
8
+ import { readFileSync, writeFileSync } from 'node:fs';
9
+ import { basename } from 'node:path';
10
+ /** The longest line that a formatter keeps whole. */
11
+ const LINE_WIDTH = 100;
12
+ /** A name that TypeScript takes as a property name without quotes. */
13
+ const PLAIN_NAME = /^[A-Za-z_$][\w$]*$/;
14
+ /** The type that each kind of compiled WGSL has. */
15
+ const KIND_TYPES = {
16
+ shader: 'CompiledShader',
17
+ material: 'CompiledMaterial',
18
+ effect: 'CompiledEffect',
19
+ toneCurve: 'CompiledToneCurve',
20
+ skyLayer: 'CompiledSkyLayer',
21
+ };
22
+ /** The path of the declaration of a `.wgsl` file. */
23
+ export function declarationPath(file) {
24
+ return `${file}.d.ts`;
25
+ }
26
+ /**
27
+ * The type of a compiled shader, as TypeScript code: its kind, its uniforms by name, and the names
28
+ * of its textures.
29
+ */
30
+ function shaderType(shader) {
31
+ if (shader.kind === 'shader')
32
+ return 'CompiledShader';
33
+ if (shader.kind === 'toneCurve')
34
+ return 'CompiledToneCurve';
35
+ if (shader.kind === 'skyLayer')
36
+ return 'CompiledSkyLayer';
37
+ const fields = shader.uniforms.map(({ name, type }) => {
38
+ const key = PLAIN_NAME.test(name) ? name : JSON.stringify(name);
39
+ return `\t\treadonly ${key}: '${type}';\n`;
40
+ });
41
+ const type = KIND_TYPES[shader.kind];
42
+ // WGSL names hold no quotes, and the layout is the one that Biome and Prettier give, so a
43
+ // project's formatter leaves the file alone.
44
+ const names = shader.textures.map(({ name }) => `'${name}'`).join(' | ') || 'never';
45
+ const short = `${type}<Record<never, never>, ${names}>`;
46
+ if (fields.length === 0 && `declare const shader: ${short};`.length <= LINE_WIDTH)
47
+ return short;
48
+ const record = fields.length > 0 ? `{\n${fields.join('')}\t}` : 'Record<never, never>';
49
+ return `${type}<\n\t${record},\n\t${names}\n>`;
50
+ }
51
+ /** The declaration of a compiled `.wgsl` file, which TypeScript reads for imports of the file. */
52
+ export function wgslDeclaration(file, shader) {
53
+ const kind = KIND_TYPES[shader.kind];
54
+ return [
55
+ `// The types of ${basename(file)}, which the null3D Vite plugin writes when it compiles the file.`,
56
+ '// Edit the WGSL, not this file.',
57
+ `import type { ${kind} } from '@null3d/vite-plugin';`,
58
+ '',
59
+ `declare const shader: ${shaderType(shader)};`,
60
+ 'export default shader;',
61
+ '',
62
+ ].join('\n');
63
+ }
64
+ /**
65
+ * Writes the declaration of a compiled `.wgsl` file beside it, unless the file there already holds
66
+ * it. An unchanged declaration is left alone, so that editors and file watchers see no change.
67
+ */
68
+ export function writeWgslDeclaration(file, shader) {
69
+ const path = declarationPath(file);
70
+ const text = wgslDeclaration(file, shader);
71
+ let current;
72
+ try {
73
+ current = readFileSync(path, 'utf8');
74
+ }
75
+ catch {
76
+ current = undefined;
77
+ }
78
+ if (current !== text)
79
+ writeFileSync(path, text);
80
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Builds one engine package's shader modules from the sources inside the compiler, and gives the
3
+ * folder that holds them. It reports the wait before it starts and how far it has got, because a
4
+ * first build takes minutes. It gives nothing when the build fails, so the caller reports that.
5
+ */
6
+ export declare function buildEngineShadersLocally(lib: string, report: (message: string) => void): Promise<string | undefined>;
@@ -0,0 +1,75 @@
1
+ // The fallback for the engine's shader modules: where the release asset cannot be downloaded, the
2
+ // plugin builds them from the sources that its compiler carries, and caches them for the machine.
3
+ // The compiler holds the engine's manifest and every WGSL file, so a project needs nothing else.
4
+ import { createHash } from 'node:crypto';
5
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { engineShadersRoot } from "./engine-shaders.js";
8
+ import { engineModule, prepareEngineModules, SHADER_COMPILER_URL } from "./shader-compiler.js";
9
+ /** The record of a set that a project may use, written last. */
10
+ const MARKER = '.complete';
11
+ /**
12
+ * Builds one engine package's shader modules from the sources inside the compiler, and gives the
13
+ * folder that holds them. It reports the wait before it starts and how far it has got, because a
14
+ * first build takes minutes. It gives nothing when the build fails, so the caller reports that.
15
+ */
16
+ export async function buildEngineShadersLocally(lib, report) {
17
+ const folder = join(engineShadersRoot(), 'local', key(lib));
18
+ if (existsSync(join(folder, MARKER)))
19
+ return folder;
20
+ report("null3D: the engine's shaders could not be downloaded, so they are built here from the engine's sources. This happens once for this machine and can take many minutes; later builds read the result from the cache.");
21
+ const staging = `${folder}.incoming-${process.pid}`;
22
+ try {
23
+ report("null3D: compiling the engine's shaders now. The compiler prints nothing until it returns, which on one core can take close to an hour; the percentage lines after it mark writing the modules, not compiling them.");
24
+ const names = prepareEngineModules();
25
+ rmSync(staging, { recursive: true, force: true });
26
+ mkdirSync(staging, { recursive: true });
27
+ let shown = -1;
28
+ for (const [index, name] of names.entries()) {
29
+ if (!/^[A-Za-z0-9_.-]+$/.test(name))
30
+ throw new Error(`the build named ${name}`);
31
+ writeFileSync(join(staging, name), engineModule(name).text);
32
+ const percent = Math.floor(((index + 1) * 10) / names.length) * 10;
33
+ if (percent > shown) {
34
+ shown = percent;
35
+ report(`null3D: building the engine's shaders: ${percent}% (${index + 1} of ${names.length})`);
36
+ }
37
+ }
38
+ writeFileSync(join(staging, MARKER), '');
39
+ rmSync(folder, { recursive: true, force: true });
40
+ mkdirSync(join(folder, '..'), { recursive: true });
41
+ renameSync(staging, folder);
42
+ return folder;
43
+ }
44
+ catch (error) {
45
+ rmSync(staging, { recursive: true, force: true });
46
+ report(`null3D: the engine's shaders could not be built: ${error.message}`);
47
+ return undefined;
48
+ }
49
+ }
50
+ /**
51
+ * The folder's key: the engine's version and the bytes of the compiler that builds it, so an
52
+ * upgrade of either builds the modules again rather than reading an older set.
53
+ */
54
+ function key(lib) {
55
+ let version = 'unknown';
56
+ try {
57
+ const manifest = JSON.parse(readFileSync(join(lib, '..', 'package.json'), 'utf8'));
58
+ if (typeof manifest.version === 'string')
59
+ version = manifest.version;
60
+ }
61
+ catch {
62
+ // A package without a readable manifest still gets a folder of its own.
63
+ }
64
+ let compiler = 'missing';
65
+ try {
66
+ compiler = createHash('sha256')
67
+ .update(readFileSync(SHADER_COMPILER_URL))
68
+ .digest('hex')
69
+ .slice(0, 16);
70
+ }
71
+ catch {
72
+ // A missing compiler fails the build itself, with the compiler's own message.
73
+ }
74
+ return `${version.replace(/[^A-Za-z0-9.-]/g, '_')}-${compiler}`;
75
+ }
@@ -0,0 +1,61 @@
1
+ /** What a release asset holds, and what the installed package says about it. */
2
+ export interface ShaderArtifact {
3
+ /** The release tag, such as `v0.1.0`. */
4
+ readonly tag: string;
5
+ /** The asset's file name, such as `v0.1.0-shaders.tar.br`. */
6
+ readonly file: string;
7
+ /** The asset's address. */
8
+ readonly url: string;
9
+ /** The SHA-256 of the compressed asset, in lowercase hexadecimal. */
10
+ readonly sha256: string;
11
+ }
12
+ /** The file in the engine package that names the release's asset. */
13
+ export declare const ARTIFACT_FILE = "shader-artifact.json";
14
+ /** The folder that holds each unpacked set, one for each hash, inside the machine's cache. */
15
+ export declare function engineShadersRoot(): string;
16
+ /**
17
+ * A folder of the engine's generated modules to use as they are, named by `NULL3D_ENGINE_SHADERS`.
18
+ * A build of the engine's sources writes the same modules to `packages/engine/src/generated`, so a
19
+ * checkout that has them, and CI's package test, need neither the download nor a build.
20
+ */
21
+ export declare const ENGINE_SHADERS_ENV = "NULL3D_ENGINE_SHADERS";
22
+ /** How the folder of an engine's modules is found: fetched from the release, or built here. */
23
+ export interface ShaderSources {
24
+ /** The folder of the release asset's modules, or nothing when it cannot be had. */
25
+ fetch(artifact: ShaderArtifact): Promise<string | undefined>;
26
+ /** The folder of modules built from the engine's own sources. */
27
+ build(): Promise<string | undefined>;
28
+ }
29
+ /**
30
+ * The folder that holds one engine package's built shader modules. The release asset is used when
31
+ * it can be had; otherwise the modules are built here, so a project without a network still works.
32
+ */
33
+ export declare function engineShaderFolder(lib: string, sources: ShaderSources): Promise<string | undefined>;
34
+ /** Reads the artifact record beside an engine package's `lib` folder, or nothing when it has none. */
35
+ export declare function readArtifact(libFolder: string): ShaderArtifact | undefined;
36
+ /**
37
+ * The folder that holds the modules of `artifact`, downloading and unpacking them when the cache
38
+ * has none. It returns nothing when the download fails or the bytes do not match the hash, and the
39
+ * caller then builds the modules itself.
40
+ */
41
+ export declare function ensureEngineShaders(artifact: ShaderArtifact, report: (message: string) => void): Promise<string | undefined>;
42
+ /**
43
+ * Writes the files of a tar's bytes into `folder`, which appears whole or not at all: the files go
44
+ * to a folder beside it first, and one rename puts them in place. A file whose name leaves the
45
+ * folder is refused, so an archive can never write outside it.
46
+ */
47
+ export declare function unpackInto(folder: string, tar: Buffer): void;
48
+ /** One file or folder of a tar archive. */
49
+ export interface TarEntry {
50
+ /** The path inside the archive, with `/` between its parts. */
51
+ readonly name: string;
52
+ /** The file's bytes, empty for a folder. */
53
+ readonly bytes: Buffer;
54
+ /** True for a folder: an entry whose type names one, or one whose name ends with `/`. */
55
+ readonly directory: boolean;
56
+ }
57
+ /**
58
+ * The entries of a tar archive, in its order. The reader takes the ustar form, with the long name
59
+ * in the prefix field, and skips the entry kinds that the release does not use.
60
+ */
61
+ export declare function tarEntries(tar: Buffer): Generator<TarEntry>;
@@ -0,0 +1,170 @@
1
+ // The engine's shader modules come from the release's asset, not from the package: the built set is
2
+ // hundreds of megabytes, which no npm package can carry. A project downloads one Brotli-compressed
3
+ // tar, checks it against the hash the installed package names, and unpacks it into a cache that the
4
+ // whole machine shares. A failed download falls back to building the modules locally, so this is an
5
+ // accelerator and never a dependency.
6
+ import { createHash } from 'node:crypto';
7
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
8
+ import { homedir } from 'node:os';
9
+ import { join, resolve } from 'node:path';
10
+ import { brotliDecompressSync } from 'node:zlib';
11
+ /** The file in the engine package that names the release's asset. */
12
+ export const ARTIFACT_FILE = 'shader-artifact.json';
13
+ /** The folder that holds each unpacked set, one for each hash, inside the machine's cache. */
14
+ export function engineShadersRoot() {
15
+ return join(process.env.NULL3D_BUILD_CACHE ?? join(homedir(), '.cache', 'null3d'), 'engine-shaders');
16
+ }
17
+ /**
18
+ * A folder of the engine's generated modules to use as they are, named by `NULL3D_ENGINE_SHADERS`.
19
+ * A build of the engine's sources writes the same modules to `packages/engine/src/generated`, so a
20
+ * checkout that has them, and CI's package test, need neither the download nor a build.
21
+ */
22
+ export const ENGINE_SHADERS_ENV = 'NULL3D_ENGINE_SHADERS';
23
+ /** The record of a set that a project may use: its hash and the files it holds. */
24
+ const MARKER = '.complete';
25
+ /** The answer for each engine package, so the download and the build happen once per build. */
26
+ const folders = new Map();
27
+ /**
28
+ * The folder that holds one engine package's built shader modules. The release asset is used when
29
+ * it can be had; otherwise the modules are built here, so a project without a network still works.
30
+ */
31
+ export function engineShaderFolder(lib, sources) {
32
+ let folder = folders.get(lib);
33
+ if (!folder) {
34
+ folder = (async () => {
35
+ const named = process.env[ENGINE_SHADERS_ENV];
36
+ if (named) {
37
+ const given = resolve(named);
38
+ if (existsSync(join(given, 'shaders.ts')))
39
+ return given;
40
+ }
41
+ const artifact = readArtifact(lib);
42
+ if (artifact) {
43
+ const fetched = await sources.fetch(artifact);
44
+ if (fetched)
45
+ return fetched;
46
+ }
47
+ return sources.build();
48
+ })();
49
+ folders.set(lib, folder);
50
+ }
51
+ return folder;
52
+ }
53
+ /** Reads the artifact record beside an engine package's `lib` folder, or nothing when it has none. */
54
+ export function readArtifact(libFolder) {
55
+ const path = join(libFolder, ARTIFACT_FILE);
56
+ try {
57
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
58
+ if (typeof parsed.tag === 'string' &&
59
+ typeof parsed.file === 'string' &&
60
+ typeof parsed.url === 'string' &&
61
+ typeof parsed.sha256 === 'string' &&
62
+ /^[a-f0-9]{64}$/.test(parsed.sha256))
63
+ return parsed;
64
+ }
65
+ catch {
66
+ // No record, or one that cannot be read: the caller builds the modules locally instead.
67
+ }
68
+ return undefined;
69
+ }
70
+ /**
71
+ * The folder that holds the modules of `artifact`, downloading and unpacking them when the cache
72
+ * has none. It returns nothing when the download fails or the bytes do not match the hash, and the
73
+ * caller then builds the modules itself.
74
+ */
75
+ export async function ensureEngineShaders(artifact, report) {
76
+ const folder = join(engineShadersRoot(), artifact.sha256);
77
+ if (existsSync(join(folder, MARKER)))
78
+ return folder;
79
+ try {
80
+ report(`null3D: fetching the engine's shaders from ${artifact.url}`);
81
+ const response = await fetch(artifact.url, { redirect: 'follow' });
82
+ if (!response.ok)
83
+ throw new Error(`the server answered ${response.status}`);
84
+ const compressed = Buffer.from(await response.arrayBuffer());
85
+ const digest = createHash('sha256').update(compressed).digest('hex');
86
+ if (digest !== artifact.sha256)
87
+ throw new Error(`the bytes hash to ${digest}, not ${artifact.sha256}`);
88
+ unpackInto(folder, brotliDecompressSync(compressed));
89
+ return folder;
90
+ }
91
+ catch (error) {
92
+ report(`null3D: could not fetch the engine's shaders (${error.message}). Building them from the engine's sources instead, which takes longer.`);
93
+ return undefined;
94
+ }
95
+ }
96
+ /**
97
+ * Writes the files of a tar's bytes into `folder`, which appears whole or not at all: the files go
98
+ * to a folder beside it first, and one rename puts them in place. A file whose name leaves the
99
+ * folder is refused, so an archive can never write outside it.
100
+ */
101
+ export function unpackInto(folder, tar) {
102
+ const staging = `${folder}.incoming-${process.pid}`;
103
+ rmSync(staging, { recursive: true, force: true });
104
+ mkdirSync(staging, { recursive: true });
105
+ try {
106
+ for (const entry of tarEntries(tar)) {
107
+ const target = join(staging, entry.name);
108
+ if (!target.startsWith(`${staging}/`) && target !== staging)
109
+ throw new Error(`the archive holds ${entry.name}, which leaves its folder`);
110
+ if (entry.directory) {
111
+ mkdirSync(target, { recursive: true });
112
+ continue;
113
+ }
114
+ mkdirSync(join(target, '..'), { recursive: true });
115
+ writeFileSync(target, entry.bytes);
116
+ }
117
+ writeFileSync(join(staging, MARKER), '');
118
+ rmSync(folder, { recursive: true, force: true });
119
+ mkdirSync(join(folder, '..'), { recursive: true });
120
+ renameSync(staging, folder);
121
+ }
122
+ catch (error) {
123
+ rmSync(staging, { recursive: true, force: true });
124
+ throw error;
125
+ }
126
+ }
127
+ const BLOCK = 512;
128
+ /** The number in a tar header field: octal digits and spaces, or empty for zero. */
129
+ function octal(header, offset, length) {
130
+ const text = header
131
+ .subarray(offset, offset + length)
132
+ .toString('ascii')
133
+ .replace(/\0.*$/, '')
134
+ .trim();
135
+ return text === '' ? 0 : Number.parseInt(text, 8);
136
+ }
137
+ /** The text in a tar header field, up to its first zero byte. */
138
+ function text(header, offset, length) {
139
+ const field = header.subarray(offset, offset + length);
140
+ const end = field.indexOf(0);
141
+ return field.subarray(0, end < 0 ? field.length : end).toString('utf8');
142
+ }
143
+ /**
144
+ * The entries of a tar archive, in its order. The reader takes the ustar form, with the long name
145
+ * in the prefix field, and skips the entry kinds that the release does not use.
146
+ */
147
+ export function* tarEntries(tar) {
148
+ let at = 0;
149
+ while (at + BLOCK <= tar.length) {
150
+ const header = tar.subarray(at, at + BLOCK);
151
+ // Two zero blocks end an archive; a block that cannot hold a name ends it too.
152
+ if (header.every((byte) => byte === 0))
153
+ return;
154
+ const name = text(header, 0, 100);
155
+ if (name === '')
156
+ return;
157
+ const size = octal(header, 124, 12);
158
+ const type = String.fromCharCode(header[156] ?? 0);
159
+ const prefix = text(header, 345, 155);
160
+ const full = prefix === '' ? name : `${prefix}/${name}`;
161
+ const start = at + BLOCK;
162
+ const end = start + size;
163
+ if (end > tar.length)
164
+ throw new Error(`the archive ends inside ${full}`);
165
+ const directory = type === '5' || full.endsWith('/');
166
+ const bytes = directory ? Buffer.alloc(0) : tar.subarray(start, end);
167
+ yield { name: full.replace(/^\.\//, '').replace(/\/$/, ''), bytes, directory };
168
+ at = end + ((BLOCK - (size % BLOCK)) % BLOCK);
169
+ }
170
+ }
@@ -0,0 +1,24 @@
1
+ /** The workers of a pool by default: one for each core but one, at most `MOST_WORKERS`. */
2
+ export declare function defaultHashWorkers(): number;
3
+ /**
4
+ * Hashes files on worker threads, which start at the first file. An idle worker does not keep the
5
+ * process alive, so a build ends without `close`.
6
+ */
7
+ export declare class HashPool {
8
+ /** The most workers that run at once. */
9
+ readonly size: number;
10
+ private readonly workers;
11
+ private nextId;
12
+ constructor(size?: number);
13
+ /**
14
+ * The first eight hexadecimal digits of the file's SHA-256, which is the same digest a hash of
15
+ * the whole file's bytes gives. A file that cannot be read rejects with the failure that the
16
+ * read raised.
17
+ */
18
+ hash(file: string): Promise<string>;
19
+ /** Stops every worker. A later hash starts them again. */
20
+ close(): Promise<void>;
21
+ /** The worker with the fewest files waiting, or a new one while there is room. */
22
+ private pick;
23
+ private start;
24
+ }
@@ -0,0 +1,84 @@
1
+ // The content hashes of the generated shader files, on worker threads. A build names each file it
2
+ // copies by a hash of the file, and the engine's set alone is thousands of files and gigabytes
3
+ // together: on the build's own thread that pass holds up module loading. The pool splits the files
4
+ // across a few workers, each of which reads its file in chunks, so the build hashes many files at
5
+ // once and keeps none of their bytes.
6
+ import { availableParallelism } from 'node:os';
7
+ import { Worker } from 'node:worker_threads';
8
+ /** The most workers a pool starts, where a wider pool read no faster. */
9
+ const MOST_WORKERS = 4;
10
+ /** The workers of a pool by default: one for each core but one, at most `MOST_WORKERS`. */
11
+ export function defaultHashWorkers() {
12
+ return Math.max(1, Math.min(MOST_WORKERS, availableParallelism() - 1));
13
+ }
14
+ /**
15
+ * Hashes files on worker threads, which start at the first file. An idle worker does not keep the
16
+ * process alive, so a build ends without `close`.
17
+ */
18
+ export class HashPool {
19
+ /** The most workers that run at once. */
20
+ size;
21
+ workers = [];
22
+ nextId = 0;
23
+ constructor(size = defaultHashWorkers()) {
24
+ this.size = size;
25
+ }
26
+ /**
27
+ * The first eight hexadecimal digits of the file's SHA-256, which is the same digest a hash of
28
+ * the whole file's bytes gives. A file that cannot be read rejects with the failure that the
29
+ * read raised.
30
+ */
31
+ hash(file) {
32
+ const worker = this.pick();
33
+ const id = this.nextId++;
34
+ const { thread, waiting } = worker;
35
+ const answer = new Promise((resolve, reject) => waiting.set(id, { resolve, reject }));
36
+ thread.ref();
37
+ thread.postMessage({ id, file });
38
+ return answer;
39
+ }
40
+ /** Stops every worker. A later hash starts them again. */
41
+ async close() {
42
+ const workers = this.workers.splice(0);
43
+ await Promise.all(workers.map((worker) => worker.thread.terminate()));
44
+ }
45
+ /** The worker with the fewest files waiting, or a new one while there is room. */
46
+ pick() {
47
+ let worker = this.workers.reduce((best, next) => (!best || next.waiting.size < best.waiting.size ? next : best), undefined);
48
+ if (!worker || (worker.waiting.size > 0 && this.workers.length < this.size))
49
+ worker = this.start();
50
+ return worker;
51
+ }
52
+ start() {
53
+ const thread = new Worker(new URL('./hash-worker.js', import.meta.url));
54
+ const worker = { thread, waiting: new Map() };
55
+ thread.on('message', (answer) => {
56
+ const call = worker.waiting.get(answer.id);
57
+ if (call === undefined)
58
+ return;
59
+ worker.waiting.delete(answer.id);
60
+ if (answer.hash === undefined) {
61
+ call.reject(Object.assign(new Error(answer.error?.message ?? ''), answer.error));
62
+ }
63
+ else
64
+ call.resolve(answer.hash);
65
+ if (worker.waiting.size === 0)
66
+ thread.unref();
67
+ });
68
+ // A thread that stops takes every file it held with it, and the build fails rather than
69
+ // naming a copy by a hash that was never computed.
70
+ const fail = (error) => {
71
+ const index = this.workers.indexOf(worker);
72
+ if (index >= 0)
73
+ this.workers.splice(index, 1);
74
+ for (const call of worker.waiting.values())
75
+ call.reject(error);
76
+ worker.waiting.clear();
77
+ };
78
+ thread.on('error', (error) => fail(new Error(`null3D: a shader hash thread stopped: ${error.message}`)));
79
+ thread.on('exit', (code) => fail(new Error(`null3D: a shader hash thread exited with code ${code}`)));
80
+ thread.unref();
81
+ this.workers.push(worker);
82
+ return worker;
83
+ }
84
+ }
@@ -0,0 +1,53 @@
1
+ // A worker thread of the hash pool. It reads one file in fixed-size chunks into one buffer of its
2
+ // own and answers with the prefix of the file's SHA-256, so the build hashes many files at once and
3
+ // the page's thread reads no file and keeps none of their bytes. The buffer is reused for every
4
+ // file, so a worker holds no whole file and its memory does not grow with the number of files. The
5
+ // worker imports only Node's own modules, so the plugin runs under Node as well as Bun.
6
+ import { createHash } from 'node:crypto';
7
+ import { open } from 'node:fs/promises';
8
+ import { parentPort } from 'node:worker_threads';
9
+
10
+ /** The bytes that one read takes; a file is hashed in as many reads as it needs. */
11
+ const CHUNK = 64 * 1024;
12
+ /** The buffer that every read fills, so a worker allocates one buffer for its whole life. */
13
+ const chunk = Buffer.allocUnsafe(CHUNK);
14
+
15
+ /**
16
+ * Answers with the first eight hexadecimal digits of the file's SHA-256, which is how a copied
17
+ * shader file's name carries its content. The digest is the same as a hash of the whole file's
18
+ * bytes, whatever the chunks are.
19
+ */
20
+ async function hashFile(file) {
21
+ const handle = await open(file, 'r');
22
+ try {
23
+ const hash = createHash('sha256');
24
+ for (;;) {
25
+ const { bytesRead } = await handle.read(chunk, 0, CHUNK, null);
26
+ if (bytesRead === 0) return hash.digest('hex').slice(0, 8);
27
+ hash.update(chunk.subarray(0, bytesRead));
28
+ }
29
+ } finally {
30
+ await handle.close();
31
+ }
32
+ }
33
+
34
+ /** Answers one request with its file's hash, or with the failure that reading it raised. */
35
+ async function answer({ id, file }) {
36
+ try {
37
+ parentPort?.postMessage({ id, hash: await hashFile(file) });
38
+ } catch (error) {
39
+ // The pool raises the failure on the build's thread, which fails the build as a direct read
40
+ // does. The code lets a caller tell a vanished file from a worker that stopped.
41
+ parentPort?.postMessage({
42
+ id,
43
+ error: { message: error.message, code: error.code },
44
+ });
45
+ }
46
+ }
47
+
48
+ // The pool sends many files to one worker, and the read buffer is shared, so the files are
49
+ // answered one after another; the other workers run meanwhile.
50
+ let answering = Promise.resolve();
51
+ parentPort?.on('message', (request) => {
52
+ answering = answering.then(() => answer(request));
53
+ });
package/lib/hot.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ import type { CompiledWgsl } from './shader-types.js';
2
+ import { type TaggedWgsl } from './wgsl.js';
3
+ /** The event that carries hot updates, on Vite's channel and on the page's global object. */
4
+ export declare const WGSL_UPDATE_EVENT = "null3d:wgsl";
5
+ /** The module that hands hot updates to the engines on a page, which the dev server injects. */
6
+ export declare const HOT_CLIENT = "virtual:null3d/hot";
7
+ /** The module id of the hot client, which no other plugin loads. */
8
+ export declare const HOT_CLIENT_ID = "\0virtual:null3d/hot";
9
+ /** The hot client's name or its module id, as Vite's hook filters match them. */
10
+ export declare const HOT_CLIENT_ADDRESS: RegExp;
11
+ /** The hot client's code. It also closes Vite's overlay, which may show an earlier WGSL error. */
12
+ export declare const HOT_CLIENT_CODE: string;
13
+ /** One hot update: the new compiled WGSL under its key. */
14
+ export interface WgslUpdate {
15
+ readonly key: string;
16
+ readonly shader: CompiledWgsl;
17
+ }
18
+ /**
19
+ * The key of a project's WGSL: a `.wgsl` file's path from the project's root, or that of a script
20
+ * with the place of a tagged literal among the script's literals, from 0.
21
+ */
22
+ export declare function hotKey(path: string, literal?: number): string;
23
+ /**
24
+ * What a running page keeps of compiled WGSL, as text: everything of a custom material but its
25
+ * builds. A material whose new WGSL keeps it can swap its shader. Null for a whole shader, which
26
+ * code outside the engine uses as it likes, and for a custom effect or tone curve, which the
27
+ * engine does not swap. Only a reload brings either a new one.
28
+ */
29
+ export declare function contractOf(shader: CompiledWgsl): string | null;
30
+ /** A tagged literal of a script, with its place among the script's literals. */
31
+ export interface ChangedLiteral {
32
+ readonly index: number;
33
+ readonly literal: TaggedWgsl;
34
+ }
35
+ /**
36
+ * The tagged literals of a script whose WGSL differs between two versions of its code, or null
37
+ * when the code differs elsewhere too, so the script itself must run again.
38
+ */
39
+ export declare function changedLiterals(before: string, after: string, file: string): ChangedLiteral[] | null;
40
+ /** What the dev server knows of the WGSL that pages run, to judge each change. */
41
+ export declare class HotState {
42
+ /** The contract of each key's WGSL as the page runs it. */
43
+ private readonly contracts;
44
+ /** The code of each script with tagged WGSL, as the page runs it, by file. */
45
+ readonly scripts: Map<string, string>;
46
+ /** Notes the WGSL that the page runs under a key. */
47
+ remember(key: string, shader: CompiledWgsl): void;
48
+ /**
49
+ * True when the page can swap the WGSL under a key for `shader` without a reload: both are
50
+ * custom materials with the same contract.
51
+ */
52
+ swaps(key: string, shader: CompiledWgsl): boolean;
53
+ }