@null3d/vite-plugin 0.0.0 → 0.1.1

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.
@@ -20,8 +20,11 @@ export function engineShadersRoot() {
20
20
  * checkout that has them, and CI's package test, need neither the download nor a build.
21
21
  */
22
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';
23
+ /**
24
+ * The record of a set that a project may use. Its name carries the version of the archive reader,
25
+ * so a set that another version of the reader unpacked is downloaded and unpacked again.
26
+ */
27
+ const MARKER = '.complete-2';
25
28
  /** The answer for each engine package, so the download and the build happen once per build. */
26
29
  const folders = new Map();
27
30
  /**
@@ -141,11 +144,15 @@ function text(header, offset, length) {
141
144
  return field.subarray(0, end < 0 ? field.length : end).toString('utf8');
142
145
  }
143
146
  /**
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.
147
+ * The entries of a tar archive, in its order. The reader takes the ustar form, with a long path in
148
+ * the prefix field. A name over 100 bytes comes in an entry of its own before its file's header:
149
+ * GNU's long-name entry, which the release's archive writes, or a pax header's `path`. Without
150
+ * them, every file whose name passes 100 bytes would take its name cut short.
146
151
  */
147
152
  export function* tarEntries(tar) {
148
153
  let at = 0;
154
+ /** The name that a long-name entry gives the entry after it. */
155
+ let longName;
149
156
  while (at + BLOCK <= tar.length) {
150
157
  const header = tar.subarray(at, at + BLOCK);
151
158
  // Two zero blocks end an archive; a block that cannot hold a name ends it too.
@@ -162,9 +169,29 @@ export function* tarEntries(tar) {
162
169
  const end = start + size;
163
170
  if (end > tar.length)
164
171
  throw new Error(`the archive ends inside ${full}`);
165
- const directory = type === '5' || full.endsWith('/');
172
+ const next = end + ((BLOCK - (size % BLOCK)) % BLOCK);
173
+ if (type === 'L' || type === 'x') {
174
+ const data = tar.subarray(start, end).toString('utf8');
175
+ const path = type === 'L' ? data.replace(/\0.*$/s, '') : paxPath(data);
176
+ if (path !== undefined)
177
+ longName = path;
178
+ at = next;
179
+ continue;
180
+ }
181
+ const named = longName ?? full;
182
+ longName = undefined;
183
+ const directory = type === '5' || named.endsWith('/');
166
184
  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);
185
+ yield { name: named.replace(/^\.\//, '').replace(/\/$/, ''), bytes, directory };
186
+ at = next;
169
187
  }
170
188
  }
189
+ /** The `path` record of a pax header's data, whose records each read `<length> <key>=<value>\n`. */
190
+ function paxPath(data) {
191
+ for (const record of data.split('\n')) {
192
+ const match = /^\d+ path=(.*)$/s.exec(record);
193
+ if (match)
194
+ return match[1];
195
+ }
196
+ return undefined;
197
+ }
@@ -1,5 +1,10 @@
1
1
  /** The workers of a pool by default: one for each core but one, at most `MOST_WORKERS`. */
2
2
  export declare function defaultHashWorkers(): number;
3
+ /** What a scan of a file gives: its hash, and the permutation word of each build that it holds. */
4
+ export interface Scanned {
5
+ readonly hash: string;
6
+ readonly words: readonly number[];
7
+ }
3
8
  /**
4
9
  * Hashes files on worker threads, which start at the first file. An idle worker does not keep the
5
10
  * process alive, so a build ends without `close`.
@@ -16,6 +21,13 @@ export declare class HashPool {
16
21
  * read raised.
17
22
  */
18
23
  hash(file: string): Promise<string>;
24
+ /**
25
+ * The file's hash, as `hash` gives it, and the permutation word of each build that the file
26
+ * holds, from each line of the form that the shader build writes.
27
+ */
28
+ scan(file: string): Promise<Scanned>;
29
+ /** Sends one file to the worker with the fewest files waiting, and gives its answer. */
30
+ private read;
19
31
  /** Stops every worker. A later hash starts them again. */
20
32
  close(): Promise<void>;
21
33
  /** The worker with the fewest files waiting, or a new one while there is room. */
package/lib/hash-pool.js CHANGED
@@ -2,7 +2,8 @@
2
2
  // copies by a hash of the file, and the engine's set alone is thousands of files and gigabytes
3
3
  // together: on the build's own thread that pass holds up module loading. The pool splits the files
4
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.
5
+ // once and keeps none of their bytes. A scan gives the permutation words of a file's builds as well,
6
+ // from the same read, for a build that narrows the set to a project's list.
6
7
  import { availableParallelism } from 'node:os';
7
8
  import { Worker } from 'node:worker_threads';
8
9
  /** The most workers a pool starts, where a wider pool read no faster. */
@@ -28,13 +29,25 @@ export class HashPool {
28
29
  * the whole file's bytes gives. A file that cannot be read rejects with the failure that the
29
30
  * read raised.
30
31
  */
31
- hash(file) {
32
+ async hash(file) {
33
+ return (await this.read(file, false)).hash;
34
+ }
35
+ /**
36
+ * The file's hash, as `hash` gives it, and the permutation word of each build that the file
37
+ * holds, from each line of the form that the shader build writes.
38
+ */
39
+ async scan(file) {
40
+ const { hash, words = [] } = await this.read(file, true);
41
+ return { hash, words };
42
+ }
43
+ /** Sends one file to the worker with the fewest files waiting, and gives its answer. */
44
+ read(file, scan) {
32
45
  const worker = this.pick();
33
46
  const id = this.nextId++;
34
47
  const { thread, waiting } = worker;
35
48
  const answer = new Promise((resolve, reject) => waiting.set(id, { resolve, reject }));
36
49
  thread.ref();
37
- thread.postMessage({ id, file });
50
+ thread.postMessage({ id, file, scan });
38
51
  return answer;
39
52
  }
40
53
  /** Stops every worker. A later hash starts them again. */
@@ -61,7 +74,7 @@ export class HashPool {
61
74
  call.reject(Object.assign(new Error(answer.error?.message ?? ''), answer.error));
62
75
  }
63
76
  else
64
- call.resolve(answer.hash);
77
+ call.resolve(answer);
65
78
  if (worker.waiting.size === 0)
66
79
  thread.unref();
67
80
  });
@@ -2,7 +2,8 @@
2
2
  // own and answers with the prefix of the file's SHA-256, so the build hashes many files at once and
3
3
  // the page's thread reads no file and keeps none of their bytes. The buffer is reused for every
4
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.
5
+ // worker imports only Node's own modules, so the plugin runs under Node as well as Bun. Asked to
6
+ // scan, it also gives the permutation word of each build that the file holds, from the same read.
6
7
  import { createHash } from 'node:crypto';
7
8
  import { open } from 'node:fs/promises';
8
9
  import { parentPort } from 'node:worker_threads';
@@ -13,18 +14,40 @@ const CHUNK = 64 * 1024;
13
14
  const chunk = Buffer.allocUnsafe(CHUNK);
14
15
 
15
16
  /**
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.
17
+ * A line of a generated shader module that holds a build's permutation word: the same lines that
18
+ * `PERMUTATION_LINE` in `shader-list.ts` reads.
19
19
  */
20
- async function hashFile(file) {
20
+ const PERMUTATION_LINE = /^\t*permutation: (\d+),$/gm;
21
+
22
+ /**
23
+ * The first eight hexadecimal digits of the file's SHA-256, which is how a copied shader file's
24
+ * name carries its content, and, when `scan` is set, the permutation word of each build that the
25
+ * file holds. The digest is the same as a hash of the whole file's bytes, whatever the chunks are.
26
+ * A line that two chunks split is read whole, from the text left after the last line break.
27
+ */
28
+ async function readFile(file, scan) {
21
29
  const handle = await open(file, 'r');
22
30
  try {
23
31
  const hash = createHash('sha256');
32
+ const words = new Set();
33
+ const decoder = new TextDecoder();
34
+ let rest = '';
35
+ const lines = (text) => {
36
+ for (const match of text.matchAll(PERMUTATION_LINE)) words.add(Number(match[1]));
37
+ };
24
38
  for (;;) {
25
39
  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));
40
+ if (bytesRead === 0) {
41
+ if (scan) lines(rest + decoder.decode());
42
+ return { hash: hash.digest('hex').slice(0, 8), words: scan ? [...words] : undefined };
43
+ }
44
+ const bytes = chunk.subarray(0, bytesRead);
45
+ hash.update(bytes);
46
+ if (!scan) continue;
47
+ const text = rest + decoder.decode(bytes, { stream: true });
48
+ const end = text.lastIndexOf('\n');
49
+ lines(text.slice(0, end + 1));
50
+ rest = text.slice(end + 1);
28
51
  }
29
52
  } finally {
30
53
  await handle.close();
@@ -32,9 +55,9 @@ async function hashFile(file) {
32
55
  }
33
56
 
34
57
  /** Answers one request with its file's hash, or with the failure that reading it raised. */
35
- async function answer({ id, file }) {
58
+ async function answer({ id, file, scan }) {
36
59
  try {
37
- parentPort?.postMessage({ id, hash: await hashFile(file) });
60
+ parentPort?.postMessage({ id, ...(await readFile(file, scan === true)) });
38
61
  } catch (error) {
39
62
  // The pool raises the failure on the build's thread, which fails the build as a direct read
40
63
  // does. The code lets a caller tell a vanished file from a worker that stopped.
package/lib/hot.d.ts CHANGED
@@ -8,8 +8,18 @@ export declare const HOT_CLIENT = "virtual:null3d/hot";
8
8
  export declare const HOT_CLIENT_ID = "\0virtual:null3d/hot";
9
9
  /** The hot client's name or its module id, as Vite's hook filters match them. */
10
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;
11
+ /** The event that carries a permutation word that a page draws with, from the page to the server. */
12
+ export declare const PERMUTATION_WORD_EVENT = "null3d:permutation";
13
+ /** The event that carries the dev server's warning about a word that the project's list lacks. */
14
+ export declare const UNLISTED_WORD_EVENT = "null3d:unlisted";
15
+ /**
16
+ * The hot client's code. It also closes Vite's overlay, which may show an earlier WGSL error. In a
17
+ * project with a shader list (`listed`), it also sends the dev server each permutation word that
18
+ * the page's engines draw with, once, and shows the server's warning about a word that the list
19
+ * lacks in the browser's console. A recording run adds its page's words to the list, so it sends
20
+ * none.
21
+ */
22
+ export declare function hotClientCode(listed: boolean): string;
13
23
  /** One hot update: the new compiled WGSL under its key. */
14
24
  export interface WgslUpdate {
15
25
  readonly key: string;
package/lib/hot.js CHANGED
@@ -7,15 +7,36 @@ export const HOT_CLIENT = 'virtual:null3d/hot';
7
7
  export const HOT_CLIENT_ID = `\0${HOT_CLIENT}`;
8
8
  /** The hot client's name or its module id, as Vite's hook filters match them. */
9
9
  export const HOT_CLIENT_ADDRESS = /^\0?virtual:null3d\/hot$/;
10
- /** The hot client's code. It also closes Vite's overlay, which may show an earlier WGSL error. */
11
- export const HOT_CLIENT_CODE = `if (import.meta.hot) {
12
- import.meta.hot.on(${JSON.stringify(WGSL_UPDATE_EVENT)}, ({ updates }) => {
10
+ /** The event that carries a permutation word that a page draws with, from the page to the server. */
11
+ export const PERMUTATION_WORD_EVENT = 'null3d:permutation';
12
+ /** The event that carries the dev server's warning about a word that the project's list lacks. */
13
+ export const UNLISTED_WORD_EVENT = 'null3d:unlisted';
14
+ /**
15
+ * The hot client's code. It also closes Vite's overlay, which may show an earlier WGSL error. In a
16
+ * project with a shader list (`listed`), it also sends the dev server each permutation word that
17
+ * the page's engines draw with, once, and shows the server's warning about a word that the list
18
+ * lacks in the browser's console. A recording run adds its page's words to the list, so it sends
19
+ * none.
20
+ */
21
+ export function hotClientCode(listed) {
22
+ const wgsl = ` import.meta.hot.on(${JSON.stringify(WGSL_UPDATE_EVENT)}, ({ updates }) => {
13
23
  for (const overlay of document.querySelectorAll('vite-error-overlay')) overlay.close();
14
24
  globalThis.dispatchEvent(new CustomEvent(${JSON.stringify(WGSL_UPDATE_EVENT)}, { detail: updates }));
15
25
  console.debug('[null3D] hot updated: ' + updates.map((update) => update.key).join(', '));
16
26
  });
17
- }
18
27
  `;
28
+ const words = ` if (new URLSearchParams(location.search).get('permutations') !== 'record') {
29
+ const sent = new Set();
30
+ globalThis.addEventListener(${JSON.stringify(PERMUTATION_WORD_EVENT)}, ({ detail: word }) => {
31
+ if (sent.has(word)) return;
32
+ sent.add(word);
33
+ import.meta.hot.send(${JSON.stringify(PERMUTATION_WORD_EVENT)}, { word, page: location.pathname });
34
+ });
35
+ import.meta.hot.on(${JSON.stringify(UNLISTED_WORD_EVENT)}, ({ message }) => console.warn('[null3D] ' + message));
36
+ }
37
+ `;
38
+ return `if (import.meta.hot) {\n${wgsl}${listed ? words : ''}}\n`;
39
+ }
19
40
  /**
20
41
  * The key of a project's WGSL: a `.wgsl` file's path from the project's root, or that of a script
21
42
  * with the place of a tagged literal among the script's literals, from 0.
package/lib/index.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import type { Connect, HtmlTagDescriptor, Plugin, Rollup } from 'vite';
2
2
  import { type AssetOptions } from './assets.js';
3
+ import { type ShaderOptions } from './shader-list.js';
3
4
  export type { AssetOptions } from './assets.js';
4
5
  export { FILES_LIST, type OfflineFiles } from './offline.js';
6
+ export type { ShaderOptions } from './shader-list.js';
5
7
  export type * from './shader-types.js';
6
8
  /** Headers that make a page cross-origin isolated, which shared memory and worker threads need. */
7
9
  export declare const ISOLATION_HEADERS: Readonly<Record<string, string>>;
@@ -13,6 +15,13 @@ export interface Null3dPluginOptions {
13
15
  * mkcert. Phones and tablets reached over the network need HTTPS for shared memory and WebGPU.
14
16
  */
15
17
  https?: boolean;
18
+ /**
19
+ * Serve the `https` server over HTTP/2, which sends every request at once on one connection,
20
+ * where HTTP/1.1 sends six at a time. The dev server sends each module as its own file, and every
21
+ * engine thread loads its own copies, so a page asks for hundreds. The default is false, because
22
+ * Safari on an iPad sometimes stops while a worker loads its modules over HTTP/2.
23
+ */
24
+ http2?: boolean;
16
25
  /** Directory that holds `cert.pem` and `key.pem`; the default is `target/dev-cert` under the project root. */
17
26
  certDir?: string;
18
27
  /**
@@ -29,10 +38,19 @@ export interface Null3dPluginOptions {
29
38
  assets?: AssetOptions;
30
39
  /**
31
40
  * Let the page's address set the engine's test switches, such as `?gpu=` and `?hold=`, in
32
- * production builds too. Development builds always read them. The default is false, so a link
33
- * cannot change how a shipped game runs. Turn it on for builds of test and benchmark pages.
41
+ * production builds too. Without the option, development builds read them and production builds
42
+ * do not, so a link cannot change how a shipped game runs. An explicit false turns them off in
43
+ * every build, the dev server's and the `null3d` command's included. Turn it on for builds of
44
+ * test and benchmark pages.
34
45
  */
35
46
  urlSwitches?: boolean;
47
+ /**
48
+ * Options for the engine's shader set. `list` names the file of the permutation words that the
49
+ * project's pages draw with, as `bunx @null3d/cli shaders record` writes it, relative to Vite's
50
+ * root. A production build then copies only the shader builds of those words. The dev server
51
+ * warns about each word that a page draws with and the list lacks.
52
+ */
53
+ shaders?: ShaderOptions;
36
54
  }
37
55
  /** Sets the isolation headers on every response, including `.wasm` files and worker scripts. */
38
56
  export declare const isolationMiddleware: Connect.NextHandleFunction;
@@ -42,6 +60,15 @@ export declare const isolationMiddleware: Connect.NextHandleFunction;
42
60
  * in turn, one round trip per thread.
43
61
  */
44
62
  export declare const immutableAssetsMiddleware: Connect.NextHandleFunction;
63
+ /**
64
+ * Takes `Origin` out of the Vary header of an answer to a request from the page's own origin, with
65
+ * the CORS header that the origin chose. Vite's CORS step marks every answer as varying by the
66
+ * request's Origin. The engine's page downloads the sketch module early with `fetch`, which sends no
67
+ * Origin, and the worker's import of it sends one. Without this, the browser cannot use the early
68
+ * copy and asks the server again, one round trip per such file. A request from the same origin needs
69
+ * no CORS header, and the browser names such a request in its Sec-Fetch-Site header.
70
+ */
71
+ export declare const sameOriginMiddleware: Connect.NextHandleFunction;
45
72
  /** The engine core's files, which every production build ships. */
46
73
  export declare const CORE_FILES: string[];
47
74
  /**
@@ -81,6 +108,15 @@ export declare function inlineLimit(own: InlineLimit | undefined, isPackageFile?
81
108
  * so their lists go: an import still fetches its own file, as any worker's import does.
82
109
  */
83
110
  export declare function emptyWorkerPreloads(bundle: Rollup.OutputBundle, seeds: readonly string[]): void;
111
+ /** The parameter that keeps a dotted query from naming a module's extension. */
112
+ export declare const QUERY_EXTENSION_PARAM = "null3d-query";
113
+ /**
114
+ * Keeps a module's query from deciding its type. Vite reads a dotted word at the end of a module's
115
+ * address as the extension, so a sketch at `sketch.ts?render-scale=0.5` parses as JavaScript and
116
+ * fails on its types. The middleware adds a parameter after such a query, which the sketch sees in
117
+ * `import.meta.url` and ignores, and Vite then reads the file's own extension.
118
+ */
119
+ export declare function queryExtensionMiddleware(): Connect.NextHandleFunction;
84
120
  /**
85
121
  * The core files missing from the installed engine package, or null when the project does not
86
122
  * install the engine.