@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.
- package/README.md +95 -0
- package/THIRD-PARTY-NOTICES.txt +18 -3
- package/dist/shader-compiler.stamp.json +1 -1
- package/dist/shader-compiler.wasm +0 -0
- package/lib/assets.d.ts +6 -6
- package/lib/assets.js +3 -3
- package/lib/compress.d.ts +47 -0
- package/lib/compress.js +391 -0
- package/lib/engine-shaders.d.ts +4 -2
- package/lib/engine-shaders.js +34 -7
- package/lib/hash-pool.d.ts +12 -0
- package/lib/hash-pool.js +17 -4
- package/lib/hash-worker.js +32 -9
- package/lib/hot.d.ts +12 -2
- package/lib/hot.js +25 -4
- package/lib/index.d.ts +38 -2
- package/lib/index.js +271 -52
- package/lib/material-builds.d.ts +2 -0
- package/lib/material-builds.js +2 -0
- package/lib/paragraphs.d.ts +9 -3
- package/lib/paragraphs.js +25 -11
- package/lib/shader-list.d.ts +127 -0
- package/lib/shader-list.js +352 -0
- package/lib/wgsl.js +2 -1
- package/lib/worker-preload.d.ts +13 -0
- package/lib/worker-preload.js +19 -0
- package/package.json +3 -3
package/README.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# Vite plugin for null3D
|
|
2
|
+
|
|
3
|
+
`@null3d/vite-plugin` sets up Vite for a [null3D](https://github.com/null3d-engine/null3d) project.
|
|
4
|
+
It sends the headers that worker threads need, compiles your WGSL for WebGPU and WebGL2, and
|
|
5
|
+
builds production files that ship the engine core. Every Vite build of a null3D project needs it.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
bun add @null3d/engine
|
|
11
|
+
bun add -d vite @null3d/vite-plugin
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
The plugin needs Vite 8 or newer.
|
|
15
|
+
|
|
16
|
+
## Use
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
// vite.config.ts
|
|
20
|
+
import null3d from '@null3d/vite-plugin';
|
|
21
|
+
import { defineConfig } from 'vite';
|
|
22
|
+
|
|
23
|
+
export default defineConfig({
|
|
24
|
+
plugins: [null3d()],
|
|
25
|
+
});
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Run `bunx vite` for the dev server and `bunx vite build` for the production files. For the types
|
|
29
|
+
of `.wgsl` and `?optimized` imports, add `@null3d/vite-plugin/client` to the `types` in your
|
|
30
|
+
`tsconfig.json`.
|
|
31
|
+
|
|
32
|
+
## What it does
|
|
33
|
+
|
|
34
|
+
- It sends the two cross-origin isolation headers on every response from `vite` and
|
|
35
|
+
`vite preview`, the `.wasm` files and worker scripts included. Worker threads need them to share
|
|
36
|
+
memory.
|
|
37
|
+
- It compiles the WGSL in `.wgsl` files and in template literals tagged `/* wgsl */`, for WebGPU
|
|
38
|
+
and WebGL2. A shader error stops Vite with its file, line and column. On the dev server, a
|
|
39
|
+
shader that you change reaches the running page without a reload.
|
|
40
|
+
- Each compiled shader stays in `node_modules/.cache/null3d-shaders`, so a later build compiles
|
|
41
|
+
only what changed.
|
|
42
|
+
- An import such as `import shipUrl from './ship.glb?optimized'` runs the asset tool of
|
|
43
|
+
`@null3d/cli` on the glTF model. The import gives the optimized model's address for
|
|
44
|
+
`assets.loadGltf`. Add the tool with `bun add -d @null3d/cli`.
|
|
45
|
+
- A production build compiles the sketch file for its worker, ships the engine's WebAssembly
|
|
46
|
+
core and drops the engine's development checks. It copies the engine's compiled shader files
|
|
47
|
+
beside the page: all of them, or only the builds that the `shaders.list` option names. Each built page that loads the engine gets a
|
|
48
|
+
small script that starts the core's download at once. The build also writes the third-party
|
|
49
|
+
notices and a list of its files (`null3d-files.json`) for offline play.
|
|
50
|
+
|
|
51
|
+
## Options
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
null3d({ https: true, certDir: 'certs', assets: { lod: true, maxTextureSize: 1024 } });
|
|
55
|
+
null3d({ shaders: { list: 'shader-permutations.txt' } });
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
- `https` serves HTTPS on your local network, from both `vite` and `vite preview`. A phone or
|
|
59
|
+
tablet needs it for shared memory and WebGPU. The plugin reads `cert.pem` and `key.pem` from
|
|
60
|
+
`certDir`, which is `target/dev-cert` in the project unless you set it.
|
|
61
|
+
- `http2` serves the `https` server over HTTP/2, which sends all of the page's requests at once on
|
|
62
|
+
one connection. A dev page asks for hundreds of modules. It is off by default, because Safari on
|
|
63
|
+
an iPad sometimes stops while a worker loads its modules over HTTP/2.
|
|
64
|
+
- `wgslDeclarations` writes a TypeScript declaration beside each `.wgsl` file, with the types of
|
|
65
|
+
its uniforms. It is on by default. Set it to false in a project without TypeScript.
|
|
66
|
+
- `assets` takes the asset tool's options for `?optimized` models, such as `lod`, `simplify` and
|
|
67
|
+
`maxTextureSize`.
|
|
68
|
+
- `shaders.list` names a list of the shader permutation words that the project's pages draw with,
|
|
69
|
+
relative to Vite's root. `bunx @null3d/cli shaders record` writes it. A production build then
|
|
70
|
+
copies only the builds of the listed words, and fails when the engine's shader set lacks a listed
|
|
71
|
+
word. Without it, a build copies the whole set, thousands of files and gigabytes, and warns with
|
|
72
|
+
the size that it copied.
|
|
73
|
+
- `urlSwitches` lets the page's address set the engine's test switches, such as `?gpu=`, in a
|
|
74
|
+
production build too. Leave it out for a shipped game. Development builds then read the
|
|
75
|
+
switches and production builds do not, so a link cannot change how the game runs. An explicit
|
|
76
|
+
`false` turns them off in every build, the dev server's and the `null3d` command's included.
|
|
77
|
+
|
|
78
|
+
## Costs and limits
|
|
79
|
+
|
|
80
|
+
- The first build compiles every shader in the project, and one compile can take most of a
|
|
81
|
+
second. The plugin prints the file that it compiles, so the pause does not look like a hang.
|
|
82
|
+
- null3D supports and tests Vite with this plugin, and no other bundler.
|
|
83
|
+
|
|
84
|
+
## Docs
|
|
85
|
+
|
|
86
|
+
- [Install null3D](https://github.com/null3d-engine/null3d/blob/generated/docs/getting-started/install.md):
|
|
87
|
+
each job of the plugin, and the shader cache.
|
|
88
|
+
- [Hosting](https://github.com/null3d-engine/null3d/blob/generated/docs/getting-started/hosting.md):
|
|
89
|
+
the headers, and a certificate for HTTPS on a phone.
|
|
90
|
+
- [Custom shaders](https://github.com/null3d-engine/null3d/blob/generated/docs/guides/custom-shaders.md)
|
|
91
|
+
and [the asset pipeline](https://github.com/null3d-engine/null3d/blob/generated/docs/guides/assets-pipeline.md).
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
Licensed under either of the Apache License 2.0 or the MIT license, at your option.
|
package/THIRD-PARTY-NOTICES.txt
CHANGED
|
@@ -70,6 +70,21 @@ Copyright (c) 2023, Qualcomm Innovation Center, Inc. All rights reserved.
|
|
|
70
70
|
|
|
71
71
|
BSD 3-Clause License, whose text is below.
|
|
72
72
|
|
|
73
|
+
==============================================================================
|
|
74
|
+
SMAA: the anti-aliasing of the moment transparency layer
|
|
75
|
+
==============================================================================
|
|
76
|
+
|
|
77
|
+
The shader library's moment transparency layer follows the SMAA 1x reference implementation's
|
|
78
|
+
three steps, from https://github.com/iryoku/smaa.
|
|
79
|
+
|
|
80
|
+
Copyright (C) 2013 Jorge Jimenez (jorge@iryoku.com)
|
|
81
|
+
Copyright (C) 2013 Jose I. Echevarria (joseignacioechevarria@gmail.com)
|
|
82
|
+
Copyright (C) 2013 Belen Masia (bmasia@unizar.es)
|
|
83
|
+
Copyright (C) 2013 Fernando Navarro (fernandn@microsoft.com)
|
|
84
|
+
Copyright (C) 2013 Diego Gutierrez (diegog@unizar.es)
|
|
85
|
+
|
|
86
|
+
The MIT License, whose text is below.
|
|
87
|
+
|
|
73
88
|
==============================================================================
|
|
74
89
|
naga, naga-types and naga_oil: WGSL parsing, validation and translation
|
|
75
90
|
==============================================================================
|
|
@@ -102,16 +117,16 @@ Each crate below is offered under the MIT License or the Apache License 2.0, and
|
|
|
102
117
|
under the MIT License, except where the line gives another license or another choice. The version
|
|
103
118
|
is the one in the module, and each crate's own package carries its copyright notice.
|
|
104
119
|
|
|
120
|
+
- The Rust standard library: Copyright (c) The Rust Project Contributors.
|
|
105
121
|
- arrayvec 0.7.8, bit-set 0.10.0, bit-vec 0.9.1, bitflags 2.13.2, cfg-if 1.0.5, equivalent
|
|
106
122
|
1.0.2, half 2.7.1, hashbrown 0.17.1, indexmap 2.14.2, itoa 1.0.18, log 0.4.34, num-traits
|
|
107
123
|
0.2.19, once_cell 1.21.4, pin-project-lite 0.2.17, regex 1.13.1, regex-automata 0.4.18,
|
|
108
|
-
regex-syntax 0.8.11, rustc-hash 1.1.0,
|
|
109
|
-
|
|
124
|
+
regex-syntax 0.8.11, rustc-hash 1.1.0, thiserror 2.0.21, unicode-width 0.2.2 and zerocopy
|
|
125
|
+
0.8.59: Copyright their authors.
|
|
110
126
|
- aho-corasick 1.1.5, memchr 2.8.3 and termcolor 1.4.1, each offered under the Unlicense or the
|
|
111
127
|
MIT License, and null3D takes them under the MIT License: Copyright (c) Andrew Gallant.
|
|
112
128
|
- data-encoding 2.11.1, libm 0.2.16, tracing 0.1.44, tracing-core 0.1.36, winnow 1.0.4 and zmij
|
|
113
129
|
1.0.23, under the MIT License: Copyright their authors.
|
|
114
|
-
- crunchy 0.2.4, under the MIT License: Copyright (c) Eira Fransham.
|
|
115
130
|
- foldhash 0.2.0, under the Zlib License: Copyright (c) Orson Peters. Its license text follows.
|
|
116
131
|
- codespan-reporting 0.12.0 and 0.13.1, under the Apache License 2.0: Copyright (c) Brendan
|
|
117
132
|
Zabarauskas. The license text is in the package's LICENSE-APACHE file.
|
|
Binary file
|
package/lib/assets.d.ts
CHANGED
|
@@ -3,9 +3,9 @@ export interface AssetOptions {
|
|
|
3
3
|
/** Add levels of detail to meshes of 64 triangles or more. The default is false. */
|
|
4
4
|
lod?: boolean;
|
|
5
5
|
/**
|
|
6
|
-
* Write each mesh's levels of detail as separate files beside the model,
|
|
7
|
-
*
|
|
8
|
-
* false.
|
|
6
|
+
* Write each mesh's finer levels of detail and cluster bands as separate files beside the model,
|
|
7
|
+
* so the engine draws a coarse first picture at once and takes each finer part as it arrives. It
|
|
8
|
+
* needs `lod` or `clusters`. The default is false.
|
|
9
9
|
*/
|
|
10
10
|
stages?: boolean;
|
|
11
11
|
/**
|
|
@@ -68,9 +68,9 @@ export declare function modelKey(identity: string, options: object, files: reado
|
|
|
68
68
|
/**
|
|
69
69
|
* What the asset tool is: the version it reports and a hash of its own code, which is the module the
|
|
70
70
|
* plugin loads and the files that share its name, the WebAssembly file among them. The version alone
|
|
71
|
-
* is not enough, because it
|
|
72
|
-
* model encodes to without changing the key, and the cache would keep serving models that the
|
|
73
|
-
* wrote before the fix (code review H-17). A tool whose files cannot be read falls back to the
|
|
71
|
+
* is not enough, because it changes only at a release: a fix to the tool between releases can change
|
|
72
|
+
* what a model encodes to without changing the key, and the cache would keep serving models that the
|
|
73
|
+
* tool wrote before the fix (code review H-17). A tool whose files cannot be read falls back to the
|
|
74
74
|
* version it reports.
|
|
75
75
|
*/
|
|
76
76
|
export declare function toolIdentity(version: string): string;
|
package/lib/assets.js
CHANGED
|
@@ -49,9 +49,9 @@ export function modelKey(identity, options, files) {
|
|
|
49
49
|
/**
|
|
50
50
|
* What the asset tool is: the version it reports and a hash of its own code, which is the module the
|
|
51
51
|
* plugin loads and the files that share its name, the WebAssembly file among them. The version alone
|
|
52
|
-
* is not enough, because it
|
|
53
|
-
* model encodes to without changing the key, and the cache would keep serving models that the
|
|
54
|
-
* wrote before the fix (code review H-17). A tool whose files cannot be read falls back to the
|
|
52
|
+
* is not enough, because it changes only at a release: a fix to the tool between releases can change
|
|
53
|
+
* what a model encodes to without changing the key, and the cache would keep serving models that the
|
|
54
|
+
* tool wrote before the fix (code review H-17). A tool whose files cannot be read falls back to the
|
|
55
55
|
* version it reports.
|
|
56
56
|
*/
|
|
57
57
|
export function toolIdentity(version) {
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from 'node:http';
|
|
2
|
+
import type { Connect } from 'vite';
|
|
3
|
+
export type Encoding = 'br' | 'gzip' | 'identity';
|
|
4
|
+
/** The best compression that a request's Accept-Encoding header allows: Brotli, then gzip, then none. */
|
|
5
|
+
export declare function acceptedEncoding(header: string | undefined): Encoding;
|
|
6
|
+
/**
|
|
7
|
+
* Whether a request comes from this computer: over the loopback, and by a loopback host name. A
|
|
8
|
+
* phone over USB, whose forwarding rule reaches the loopback, counts too. An HTTP/2 request names
|
|
9
|
+
* its host in the `:authority` header.
|
|
10
|
+
*/
|
|
11
|
+
export declare function fromLoopback(req: IncomingMessage): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Compressed bodies, kept by a key that names their bytes and encoding, with null for bytes that
|
|
14
|
+
* compression does not make smaller enough. With `best`, each Brotli body is compressed again at
|
|
15
|
+
* the best quality while no request is in flight, one at a time, and that body replaces the first.
|
|
16
|
+
*/
|
|
17
|
+
export declare class CompressedBodies {
|
|
18
|
+
#private;
|
|
19
|
+
/**
|
|
20
|
+
* `best` turns on the second compression at the best quality, which waits until no request has
|
|
21
|
+
* been in flight for `quietMs`.
|
|
22
|
+
*/
|
|
23
|
+
constructor(best: boolean, quietMs?: number);
|
|
24
|
+
/**
|
|
25
|
+
* The body of the bytes that `key` names, in `encoding`: a kept one, or one compressed now from
|
|
26
|
+
* `raw`, which reads the bytes. Null when the bytes are best sent as they are. `raw` may be
|
|
27
|
+
* called again later, for the best quality, and fails when the bytes it would read are no longer
|
|
28
|
+
* the ones that `key` names.
|
|
29
|
+
*/
|
|
30
|
+
body(key: string, encoding: 'br' | 'gzip', raw: () => Promise<Buffer>): Promise<Buffer | null>;
|
|
31
|
+
/** Notes a request until its answer ends, so the best quality waits while one is in flight. */
|
|
32
|
+
track(res: ServerResponse): void;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Compresses the answers of the steps after it, for the requests that `wanted` picks. It holds back
|
|
36
|
+
* an answer's headers until its first bytes, then, when the answer is worth it, collects its body
|
|
37
|
+
* and sends it compressed. An answer that is already encoded, or that is not text or WebAssembly,
|
|
38
|
+
* goes as it is.
|
|
39
|
+
*/
|
|
40
|
+
export declare function compressAnswers(wanted: (req: IncomingMessage) => boolean, bodies?: CompressedBodies): Connect.NextHandleFunction;
|
|
41
|
+
/**
|
|
42
|
+
* Answers each request for a text, WebAssembly or model file of the build in `dir` compressed, with the
|
|
43
|
+
* headers that the preview gives its files and `headers` added. The steps before it set the
|
|
44
|
+
* caching. Other requests, and requests for a range or with no compression accepted, go on to the
|
|
45
|
+
* preview's own file server. `base` is the start of every file's address.
|
|
46
|
+
*/
|
|
47
|
+
export declare function compressedFiles(dir: string, base: string, headers?: OutgoingHttpHeaders, bodies?: CompressedBodies): Connect.NextHandleFunction;
|
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
|
+
}
|
package/lib/engine-shaders.d.ts
CHANGED
|
@@ -55,7 +55,9 @@ export interface TarEntry {
|
|
|
55
55
|
readonly directory: boolean;
|
|
56
56
|
}
|
|
57
57
|
/**
|
|
58
|
-
* The entries of a tar archive, in its order. The reader takes the ustar form, with
|
|
59
|
-
*
|
|
58
|
+
* The entries of a tar archive, in its order. The reader takes the ustar form, with a long path in
|
|
59
|
+
* the prefix field. A name over 100 bytes comes in an entry of its own before its file's header:
|
|
60
|
+
* GNU's long-name entry, which the release's archive writes, or a pax header's `path`. Without
|
|
61
|
+
* them, every file whose name passes 100 bytes would take its name cut short.
|
|
60
62
|
*/
|
|
61
63
|
export declare function tarEntries(tar: Buffer): Generator<TarEntry>;
|