@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.
- package/LICENSE-APACHE +176 -0
- package/LICENSE-MIT +21 -0
- package/README.md +87 -2
- package/THIRD-PARTY-NOTICES.txt +413 -0
- package/dist/shader-compiler.stamp.json +4 -0
- package/dist/shader-compiler.wasm +0 -0
- package/lib/assets.d.ts +94 -0
- package/lib/assets.js +189 -0
- package/lib/client.d.ts +21 -0
- package/lib/compile-pool.d.ts +25 -0
- package/lib/compile-pool.js +90 -0
- package/lib/compile-worker.js +11 -0
- package/lib/compiler-calls.d.ts +26 -0
- package/lib/compiler-calls.js +97 -0
- package/lib/compiler-stamp.d.ts +8 -0
- package/lib/compiler-stamp.js +34 -0
- package/lib/compress.d.ts +47 -0
- package/lib/compress.js +391 -0
- package/lib/declarations.d.ts +10 -0
- package/lib/declarations.js +80 -0
- package/lib/engine-shaders-local.d.ts +6 -0
- package/lib/engine-shaders-local.js +75 -0
- package/lib/engine-shaders.d.ts +61 -0
- package/lib/engine-shaders.js +170 -0
- package/lib/hash-pool.d.ts +24 -0
- package/lib/hash-pool.js +84 -0
- package/lib/hash-worker.js +53 -0
- package/lib/hot.d.ts +53 -0
- package/lib/hot.js +101 -0
- package/lib/index.d.ts +122 -0
- package/lib/index.js +972 -0
- package/lib/material-builds.d.ts +91 -0
- package/lib/material-builds.js +236 -0
- package/lib/offline.d.ts +92 -0
- package/lib/offline.js +304 -0
- package/lib/pack.d.ts +30 -0
- package/lib/pack.js +112 -0
- package/lib/package-files.d.ts +12 -0
- package/lib/package-files.js +39 -0
- package/lib/paragraphs.d.ts +19 -0
- package/lib/paragraphs.js +131 -0
- package/lib/shader-cache.d.ts +59 -0
- package/lib/shader-cache.js +213 -0
- package/lib/shader-compiler.d.ts +258 -0
- package/lib/shader-compiler.js +169 -0
- package/lib/shader-types.d.ts +261 -0
- package/lib/shader-types.js +4 -0
- package/lib/wgsl.d.ts +118 -0
- package/lib/wgsl.js +447 -0
- package/lib/worker-preload.d.ts +30 -0
- package/lib/worker-preload.js +84 -0
- package/package.json +69 -5
package/lib/compress.js
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
// Compressed answers from the dev server and from `vite preview`. A phone or tablet that reaches
|
|
2
|
+
// this computer over a network, a VPN or a tunnel waits a round trip for each request, and its
|
|
3
|
+
// browser sends at most six at once over HTTP/1.1, which these servers speak. The engine's largest
|
|
4
|
+
// files are text and WebAssembly: its core, its shader modules, which hold shader source as strings,
|
|
5
|
+
// and the builds of custom materials. Brotli makes them three to fifty times smaller. A glTF model's
|
|
6
|
+
// geometry shrinks too, while a model whose textures are compressed images barely does, so an
|
|
7
|
+
// answer that compression would not make smaller by a useful share goes as it is.
|
|
8
|
+
//
|
|
9
|
+
// The dev server compresses its answers to every request that does not come from this computer's
|
|
10
|
+
// loopback, at a Brotli quality that takes milliseconds, and keeps each result for the next answer
|
|
11
|
+
// with the same bytes. Answers over the loopback stay as they are: there the transfer costs nothing,
|
|
12
|
+
// and compression would only add time. A request through a tunnel, such as BrowserStack Local's,
|
|
13
|
+
// arrives over the loopback by another host name, so it counts as remote.
|
|
14
|
+
//
|
|
15
|
+
// The preview compresses for every request, as a host should: the build's text, WebAssembly and
|
|
16
|
+
// model files, and the answers of other plugins' routes. It answers first at the fast quality. While no request is in flight, it compresses each
|
|
17
|
+
// answered file again at Brotli's best quality, so later visits get the files at the size that a
|
|
18
|
+
// host which compresses its files ahead of time sends.
|
|
19
|
+
import { createHash } from 'node:crypto';
|
|
20
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
21
|
+
import { extname, join, normalize, sep } from 'node:path';
|
|
22
|
+
import { promisify } from 'node:util';
|
|
23
|
+
import { brotliCompress, constants, gzip } from 'node:zlib';
|
|
24
|
+
/** The best compression that a request's Accept-Encoding header allows: Brotli, then gzip, then none. */
|
|
25
|
+
export function acceptedEncoding(header) {
|
|
26
|
+
const accepted = new Set((header ?? '').split(',').flatMap((part) => {
|
|
27
|
+
const [name = '', ...params] = part.trim().toLowerCase().split(';');
|
|
28
|
+
const weight = params.map((param) => param.trim()).find((param) => param.startsWith('q='));
|
|
29
|
+
return weight !== undefined && Number(weight.slice(2)) === 0 ? [] : [name.trim()];
|
|
30
|
+
}));
|
|
31
|
+
if (accepted.has('br'))
|
|
32
|
+
return 'br';
|
|
33
|
+
if (accepted.has('gzip'))
|
|
34
|
+
return 'gzip';
|
|
35
|
+
return 'identity';
|
|
36
|
+
}
|
|
37
|
+
/** A loopback address of this computer, as a socket reports its peer. */
|
|
38
|
+
const LOOPBACK_PEER = /^(?:127(?:\.\d{1,3}){3}|::1|::ffff:127(?:\.\d{1,3}){3})$/;
|
|
39
|
+
/** A host name that names this computer's loopback, with or without a port. */
|
|
40
|
+
const LOOPBACK_HOST = /^(?:localhost|[\w.-]+\.localhost|127(?:\.\d{1,3}){3}|\[::1\])(?::\d+)?$/i;
|
|
41
|
+
/**
|
|
42
|
+
* Whether a request comes from this computer: over the loopback, and by a loopback host name. A
|
|
43
|
+
* phone over USB, whose forwarding rule reaches the loopback, counts too. An HTTP/2 request names
|
|
44
|
+
* its host in the `:authority` header.
|
|
45
|
+
*/
|
|
46
|
+
export function fromLoopback(req) {
|
|
47
|
+
const host = req.headers.host ?? req.headers[':authority'];
|
|
48
|
+
return (LOOPBACK_PEER.test(req.socket?.remoteAddress ?? '') &&
|
|
49
|
+
LOOPBACK_HOST.test(typeof host === 'string' ? host : ''));
|
|
50
|
+
}
|
|
51
|
+
const brotli = promisify(brotliCompress);
|
|
52
|
+
const gzipped = promisify(gzip);
|
|
53
|
+
/** Brotli's quality for an answer that waits on it: milliseconds for a module of megabytes. */
|
|
54
|
+
const FAST_QUALITY = 5;
|
|
55
|
+
/** Smaller answers go as they are: compression saves less than its own header costs. */
|
|
56
|
+
const SMALLEST = 1024;
|
|
57
|
+
/**
|
|
58
|
+
* The share of its size that a compressed body must save for it to go compressed. Bytes that
|
|
59
|
+
* compress no further, such as a model whose textures are compressed images, go as they are.
|
|
60
|
+
*/
|
|
61
|
+
const WORTH = 0.05;
|
|
62
|
+
/** What the kept bodies may hold in all. The least recently used go first. */
|
|
63
|
+
const KEPT_BYTES = 256 << 20;
|
|
64
|
+
/** How long the preview waits with no request in flight before it compresses a file again. */
|
|
65
|
+
const QUIET_MS = 1000;
|
|
66
|
+
function compress(raw, encoding, quality) {
|
|
67
|
+
return encoding === 'br'
|
|
68
|
+
? brotli(raw, {
|
|
69
|
+
params: {
|
|
70
|
+
[constants.BROTLI_PARAM_QUALITY]: quality,
|
|
71
|
+
[constants.BROTLI_PARAM_SIZE_HINT]: raw.length,
|
|
72
|
+
},
|
|
73
|
+
})
|
|
74
|
+
: gzipped(raw);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Compressed bodies, kept by a key that names their bytes and encoding, with null for bytes that
|
|
78
|
+
* compression does not make smaller enough. With `best`, each Brotli body is compressed again at
|
|
79
|
+
* the best quality while no request is in flight, one at a time, and that body replaces the first.
|
|
80
|
+
*/
|
|
81
|
+
export class CompressedBodies {
|
|
82
|
+
#kept = new Map();
|
|
83
|
+
#keptBytes = 0;
|
|
84
|
+
/** Bodies that wait for the best quality, by key, with the read of their raw bytes. */
|
|
85
|
+
#waiting = new Map();
|
|
86
|
+
#inFlight = 0;
|
|
87
|
+
#upgrading = false;
|
|
88
|
+
#quiet;
|
|
89
|
+
#best;
|
|
90
|
+
#quietMs;
|
|
91
|
+
/**
|
|
92
|
+
* `best` turns on the second compression at the best quality, which waits until no request has
|
|
93
|
+
* been in flight for `quietMs`.
|
|
94
|
+
*/
|
|
95
|
+
constructor(best, quietMs = QUIET_MS) {
|
|
96
|
+
this.#best = best;
|
|
97
|
+
this.#quietMs = quietMs;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* The body of the bytes that `key` names, in `encoding`: a kept one, or one compressed now from
|
|
101
|
+
* `raw`, which reads the bytes. Null when the bytes are best sent as they are. `raw` may be
|
|
102
|
+
* called again later, for the best quality, and fails when the bytes it would read are no longer
|
|
103
|
+
* the ones that `key` names.
|
|
104
|
+
*/
|
|
105
|
+
async body(key, encoding, raw) {
|
|
106
|
+
const name = `${encoding}:${key}`;
|
|
107
|
+
const kept = this.#kept.get(name);
|
|
108
|
+
if (kept !== undefined) {
|
|
109
|
+
this.#kept.delete(name);
|
|
110
|
+
this.#kept.set(name, kept);
|
|
111
|
+
return kept;
|
|
112
|
+
}
|
|
113
|
+
const bytes = await raw();
|
|
114
|
+
const compressed = await compress(bytes, encoding, FAST_QUALITY);
|
|
115
|
+
const body = compressed.length <= bytes.length * (1 - WORTH) ? compressed : null;
|
|
116
|
+
this.#keep(name, body);
|
|
117
|
+
if (body && this.#best && encoding === 'br')
|
|
118
|
+
this.#waiting.set(name, raw);
|
|
119
|
+
return body;
|
|
120
|
+
}
|
|
121
|
+
/** Notes a request until its answer ends, so the best quality waits while one is in flight. */
|
|
122
|
+
track(res) {
|
|
123
|
+
if (!this.#best)
|
|
124
|
+
return;
|
|
125
|
+
this.#inFlight++;
|
|
126
|
+
clearTimeout(this.#quiet);
|
|
127
|
+
res.once('close', () => {
|
|
128
|
+
this.#inFlight--;
|
|
129
|
+
this.#schedule();
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
#keep(name, body) {
|
|
133
|
+
const old = this.#kept.get(name);
|
|
134
|
+
if (old !== undefined) {
|
|
135
|
+
this.#keptBytes -= old?.length ?? 0;
|
|
136
|
+
this.#kept.delete(name);
|
|
137
|
+
}
|
|
138
|
+
this.#kept.set(name, body);
|
|
139
|
+
this.#keptBytes += body?.length ?? 0;
|
|
140
|
+
for (const [oldest, kept] of this.#kept) {
|
|
141
|
+
if (this.#keptBytes <= KEPT_BYTES)
|
|
142
|
+
break;
|
|
143
|
+
this.#kept.delete(oldest);
|
|
144
|
+
this.#waiting.delete(oldest);
|
|
145
|
+
this.#keptBytes -= kept?.length ?? 0;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
#schedule() {
|
|
149
|
+
if (this.#inFlight > 0 || this.#upgrading || this.#waiting.size === 0)
|
|
150
|
+
return;
|
|
151
|
+
clearTimeout(this.#quiet);
|
|
152
|
+
this.#quiet = setTimeout(() => void this.#upgradeOne(), this.#quietMs);
|
|
153
|
+
this.#quiet.unref?.();
|
|
154
|
+
}
|
|
155
|
+
async #upgradeOne() {
|
|
156
|
+
const next = this.#waiting.entries().next();
|
|
157
|
+
if (this.#inFlight > 0 || next.done)
|
|
158
|
+
return;
|
|
159
|
+
const [name, raw] = next.value;
|
|
160
|
+
this.#waiting.delete(name);
|
|
161
|
+
this.#upgrading = true;
|
|
162
|
+
try {
|
|
163
|
+
const body = await compress(await raw(), 'br', constants.BROTLI_MAX_QUALITY);
|
|
164
|
+
if (this.#kept.has(name))
|
|
165
|
+
this.#keep(name, body);
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
// The file changed or went away; its next answer compresses the new bytes.
|
|
169
|
+
}
|
|
170
|
+
finally {
|
|
171
|
+
this.#upgrading = false;
|
|
172
|
+
}
|
|
173
|
+
this.#schedule();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/** Answers worth compressing: scripts, WebAssembly, glTF models, styles, pages and other text. */
|
|
177
|
+
const COMPRESSIBLE = /^(?:text\/(?!event-stream)|application\/(?:javascript|json|wasm|xml)|image\/svg|model\/gltf)/;
|
|
178
|
+
/** Whether to compress an answer whose headers are final. */
|
|
179
|
+
function compressible(req, res) {
|
|
180
|
+
return (req.method === 'GET' &&
|
|
181
|
+
res.statusCode === 200 &&
|
|
182
|
+
!res.hasHeader('Content-Encoding') &&
|
|
183
|
+
COMPRESSIBLE.test(String(res.getHeader('Content-Type') ?? '')));
|
|
184
|
+
}
|
|
185
|
+
/** Puts the headers given to writeHead on the response, so they can change before they go out. */
|
|
186
|
+
function setHeaders(res, headers) {
|
|
187
|
+
if (!Array.isArray(headers)) {
|
|
188
|
+
for (const [name, value] of Object.entries(headers))
|
|
189
|
+
if (value !== undefined)
|
|
190
|
+
res.setHeader(name, value);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
// A flat list of names and values, or a list of pairs.
|
|
194
|
+
const pairs = Array.isArray(headers[0])
|
|
195
|
+
? headers
|
|
196
|
+
: headers.flatMap((_, i) => i % 2 === 0 ? [[headers[i], headers[i + 1]]] : []);
|
|
197
|
+
for (const [name, value] of pairs)
|
|
198
|
+
res.setHeader(name, value);
|
|
199
|
+
}
|
|
200
|
+
/** Marks an answer as one of several encodings of the same address. */
|
|
201
|
+
function addVary(res) {
|
|
202
|
+
const vary = res.getHeader('Vary');
|
|
203
|
+
if (!vary)
|
|
204
|
+
res.setHeader('Vary', 'Accept-Encoding');
|
|
205
|
+
else if (!/accept-encoding/i.test(String(vary)))
|
|
206
|
+
res.setHeader('Vary', `${vary}, Accept-Encoding`);
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Compresses the answers of the steps after it, for the requests that `wanted` picks. It holds back
|
|
210
|
+
* an answer's headers until its first bytes, then, when the answer is worth it, collects its body
|
|
211
|
+
* and sends it compressed. An answer that is already encoded, or that is not text or WebAssembly,
|
|
212
|
+
* goes as it is.
|
|
213
|
+
*/
|
|
214
|
+
export function compressAnswers(wanted, bodies = new CompressedBodies(false)) {
|
|
215
|
+
return (req, res, next) => {
|
|
216
|
+
const encoding = acceptedEncoding(req.headers['accept-encoding']);
|
|
217
|
+
if (encoding === 'identity' || req.method !== 'GET' || !wanted(req))
|
|
218
|
+
return next();
|
|
219
|
+
const { writeHead, write, end } = res;
|
|
220
|
+
const sendRest = end;
|
|
221
|
+
/** True once the answer goes on as it is, or compressed: each call then passes straight on. */
|
|
222
|
+
let through = false;
|
|
223
|
+
let chunks;
|
|
224
|
+
const toBuffer = (chunk, textEncoding) => Buffer.isBuffer(chunk)
|
|
225
|
+
? chunk
|
|
226
|
+
: chunk instanceof Uint8Array
|
|
227
|
+
? Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
|
|
228
|
+
: Buffer.from(String(chunk), typeof textEncoding === 'string' ? textEncoding : 'utf8');
|
|
229
|
+
const ownWriteHead = function (status, ...rest) {
|
|
230
|
+
if (through)
|
|
231
|
+
return writeHead.call(res, status, ...rest);
|
|
232
|
+
res.statusCode = status;
|
|
233
|
+
if (typeof rest[0] === 'string')
|
|
234
|
+
res.statusMessage = rest.shift();
|
|
235
|
+
if (rest[0])
|
|
236
|
+
setHeaders(res, rest[0]);
|
|
237
|
+
return res;
|
|
238
|
+
};
|
|
239
|
+
/**
|
|
240
|
+
* Lets the answer go on: puts back the functions that this step replaced, and sends the
|
|
241
|
+
* headers that it held back. A later step, such as Vite's own compression in the preview
|
|
242
|
+
* server, may have wrapped the same functions over these. Its wrappers stay in place, and
|
|
243
|
+
* this step's functions then pass every call straight on: put back, the answer's last call
|
|
244
|
+
* would skip that step, and end the answer before the bytes it still holds.
|
|
245
|
+
*/
|
|
246
|
+
const handOn = () => {
|
|
247
|
+
through = true;
|
|
248
|
+
if (res.writeHead === ownWriteHead)
|
|
249
|
+
res.writeHead = writeHead;
|
|
250
|
+
if (res.write === ownWrite)
|
|
251
|
+
res.write = write;
|
|
252
|
+
if (res.end === ownEnd)
|
|
253
|
+
res.end = end;
|
|
254
|
+
if (!res.headersSent)
|
|
255
|
+
writeHead.call(res, res.statusCode);
|
|
256
|
+
};
|
|
257
|
+
// Decides once, at the first bytes or the end, whether this answer is collected and compressed.
|
|
258
|
+
const start = () => {
|
|
259
|
+
if (!compressible(req, res)) {
|
|
260
|
+
handOn();
|
|
261
|
+
return false;
|
|
262
|
+
}
|
|
263
|
+
chunks = [];
|
|
264
|
+
return true;
|
|
265
|
+
};
|
|
266
|
+
const ownWrite = function (chunk, ...rest) {
|
|
267
|
+
if (through || (!chunks && !start()))
|
|
268
|
+
return write.call(res, chunk, ...rest);
|
|
269
|
+
chunks?.push(toBuffer(chunk, rest[0]));
|
|
270
|
+
return true;
|
|
271
|
+
};
|
|
272
|
+
const ownEnd = function (...args) {
|
|
273
|
+
if (through || (!chunks && !start()))
|
|
274
|
+
return sendRest.apply(res, args);
|
|
275
|
+
const [last] = args;
|
|
276
|
+
if (last !== undefined && last !== null && typeof last !== 'function')
|
|
277
|
+
chunks?.push(toBuffer(last, args[1]));
|
|
278
|
+
const done = args.find((arg) => typeof arg === 'function');
|
|
279
|
+
const raw = Buffer.concat(chunks ?? []);
|
|
280
|
+
if (raw.length < SMALLEST) {
|
|
281
|
+
res.setHeader('Content-Length', raw.length);
|
|
282
|
+
handOn();
|
|
283
|
+
return sendRest.call(res, raw, done);
|
|
284
|
+
}
|
|
285
|
+
const key = createHash('sha1').update(raw).digest('base64');
|
|
286
|
+
bodies
|
|
287
|
+
.body(key, encoding, async () => raw)
|
|
288
|
+
.then((body) => {
|
|
289
|
+
if (body)
|
|
290
|
+
res.setHeader('Content-Encoding', encoding);
|
|
291
|
+
res.setHeader('Content-Length', (body ?? raw).length);
|
|
292
|
+
addVary(res);
|
|
293
|
+
handOn();
|
|
294
|
+
sendRest.call(res, body ?? raw, done);
|
|
295
|
+
}, (e) => {
|
|
296
|
+
res.statusCode = 500;
|
|
297
|
+
res.removeHeader('Content-Length');
|
|
298
|
+
res.setHeader('Content-Type', 'text/plain');
|
|
299
|
+
handOn();
|
|
300
|
+
sendRest.call(res, `null3D: compressing ${req.url} failed: ${e.message}`);
|
|
301
|
+
});
|
|
302
|
+
return res;
|
|
303
|
+
};
|
|
304
|
+
res.writeHead = ownWriteHead;
|
|
305
|
+
res.write = ownWrite;
|
|
306
|
+
res.end = ownEnd;
|
|
307
|
+
next();
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* The types of the build's files that the preview compresses, by extension. A file that compresses
|
|
312
|
+
* no further, such as a model whose textures are compressed images, goes as it is.
|
|
313
|
+
*/
|
|
314
|
+
const FILE_TYPES = {
|
|
315
|
+
'.glb': 'model/gltf-binary',
|
|
316
|
+
'.gltf': 'model/gltf+json',
|
|
317
|
+
'.bin': 'application/octet-stream',
|
|
318
|
+
'.js': 'text/javascript',
|
|
319
|
+
'.mjs': 'text/javascript',
|
|
320
|
+
'.css': 'text/css',
|
|
321
|
+
'.wasm': 'application/wasm',
|
|
322
|
+
'.json': 'application/json',
|
|
323
|
+
'.map': 'application/json',
|
|
324
|
+
'.svg': 'image/svg+xml',
|
|
325
|
+
'.txt': 'text/plain',
|
|
326
|
+
'.xml': 'application/xml',
|
|
327
|
+
};
|
|
328
|
+
/**
|
|
329
|
+
* Answers each request for a text, WebAssembly or model file of the build in `dir` compressed, with the
|
|
330
|
+
* headers that the preview gives its files and `headers` added. The steps before it set the
|
|
331
|
+
* caching. Other requests, and requests for a range or with no compression accepted, go on to the
|
|
332
|
+
* preview's own file server. `base` is the start of every file's address.
|
|
333
|
+
*/
|
|
334
|
+
export function compressedFiles(dir, base, headers = {}, bodies = new CompressedBodies(true)) {
|
|
335
|
+
const root = normalize(dir + sep);
|
|
336
|
+
return (req, res, next) => {
|
|
337
|
+
bodies.track(res);
|
|
338
|
+
const encoding = acceptedEncoding(req.headers['accept-encoding']);
|
|
339
|
+
if (encoding === 'identity' || req.method !== 'GET' || req.headers.range)
|
|
340
|
+
return next();
|
|
341
|
+
const path = (req.url ?? '').split(/[?#]/)[0] ?? '';
|
|
342
|
+
if (!path.startsWith(base))
|
|
343
|
+
return next();
|
|
344
|
+
const type = FILE_TYPES[extname(path).toLowerCase()];
|
|
345
|
+
if (!type)
|
|
346
|
+
return next();
|
|
347
|
+
let file;
|
|
348
|
+
try {
|
|
349
|
+
file = normalize(join(root, decodeURIComponent(path.slice(base.length))));
|
|
350
|
+
}
|
|
351
|
+
catch {
|
|
352
|
+
return next();
|
|
353
|
+
}
|
|
354
|
+
if (!file.startsWith(root))
|
|
355
|
+
return next();
|
|
356
|
+
const tagOf = (size, mtime) => `W/"${size}-${mtime.getTime()}"`;
|
|
357
|
+
void (async () => {
|
|
358
|
+
const info = await stat(file).catch(() => undefined);
|
|
359
|
+
if (!info?.isFile())
|
|
360
|
+
return next();
|
|
361
|
+
const etag = tagOf(info.size, info.mtime);
|
|
362
|
+
for (const [name, value] of Object.entries(headers))
|
|
363
|
+
if (value !== undefined)
|
|
364
|
+
res.setHeader(name, value);
|
|
365
|
+
res.setHeader('Content-Type', type);
|
|
366
|
+
res.setHeader('Last-Modified', info.mtime.toUTCString());
|
|
367
|
+
res.setHeader('ETag', etag);
|
|
368
|
+
if (!res.hasHeader('Cache-Control'))
|
|
369
|
+
res.setHeader('Cache-Control', 'no-cache');
|
|
370
|
+
addVary(res);
|
|
371
|
+
if (req.headers['if-none-match'] === etag) {
|
|
372
|
+
res.statusCode = 304;
|
|
373
|
+
res.end();
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
const read = async () => {
|
|
377
|
+
const now = await stat(file);
|
|
378
|
+
if (tagOf(now.size, now.mtime) !== etag)
|
|
379
|
+
throw new Error(`${file} changed`);
|
|
380
|
+
return readFile(file);
|
|
381
|
+
};
|
|
382
|
+
const compressed = info.size < SMALLEST ? null : await bodies.body(`${file}\0${etag}`, encoding, read);
|
|
383
|
+
if (compressed)
|
|
384
|
+
res.setHeader('Content-Encoding', encoding);
|
|
385
|
+
const body = compressed ?? (await readFile(file));
|
|
386
|
+
res.setHeader('Content-Length', body.length);
|
|
387
|
+
res.statusCode = 200;
|
|
388
|
+
res.end(body);
|
|
389
|
+
})().catch(next);
|
|
390
|
+
};
|
|
391
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { CompiledWgsl } from './shader-types.js';
|
|
2
|
+
/** The path of the declaration of a `.wgsl` file. */
|
|
3
|
+
export declare function declarationPath(file: string): string;
|
|
4
|
+
/** The declaration of a compiled `.wgsl` file, which TypeScript reads for imports of the file. */
|
|
5
|
+
export declare function wgslDeclaration(file: string, shader: CompiledWgsl): string;
|
|
6
|
+
/**
|
|
7
|
+
* Writes the declaration of a compiled `.wgsl` file beside it, unless the file there already holds
|
|
8
|
+
* it. An unchanged declaration is left alone, so that editors and file watchers see no change.
|
|
9
|
+
*/
|
|
10
|
+
export declare function writeWgslDeclaration(file: string, shader: CompiledWgsl): void;
|
|
@@ -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>;
|