@softistx/alxia-react-router 0.84.2 → 0.86.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/README.md +6 -5
- package/dist/chunks/{index-5gqcpyyg.js → index-jt62gn6d.js} +18 -5
- package/dist/chunks/index-jt62gn6d.js.map +10 -0
- package/dist/chunks/index-q0ks955b.js +10 -0
- package/dist/chunks/{index-59vhfj6n.js.map → index-q0ks955b.js.map} +2 -2
- package/dist/chunks/{index-6jf7zpxz.js → index-zb23cx4p.js} +27 -11
- package/dist/chunks/index-zb23cx4p.js.map +11 -0
- package/dist/pwa/build/build-worker.d.ts +21 -2
- package/dist/pwa/build/build-worker.d.ts.map +1 -1
- package/dist/pwa/build/index.js +1 -1
- package/dist/pwa/build/precache.d.ts +4 -2
- package/dist/pwa/build/precache.d.ts.map +1 -1
- package/dist/pwa/index.d.ts +1 -1
- package/dist/pwa/index.d.ts.map +1 -1
- package/dist/pwa/index.js +1 -1
- package/dist/pwa/model/precache-list.d.ts +20 -9
- package/dist/pwa/model/precache-list.d.ts.map +1 -1
- package/dist/pwa/worker/index.d.ts +1 -0
- package/dist/pwa/worker/index.d.ts.map +1 -1
- package/dist/pwa/worker/index.js +5 -5
- package/dist/pwa/worker/index.js.map +2 -2
- package/dist/vite/index.d.ts +2 -2
- package/dist/vite/index.js +1 -1
- package/dist/vite/index.js.map +1 -1
- package/docs/guide/pwa.md +36 -7
- package/docs/roadmap.md +8 -0
- package/docs/troubleshooting.md +24 -0
- package/package.json +1 -1
- package/dist/chunks/index-59vhfj6n.js +0 -10
- package/dist/chunks/index-5gqcpyyg.js.map +0 -10
- package/dist/chunks/index-6jf7zpxz.js.map +0 -11
package/README.md
CHANGED
|
@@ -751,7 +751,7 @@ With `app/service-worker.ts` in the app, `react-router build` writes
|
|
|
751
751
|
client build, with the precache list written in, and there is no script to
|
|
752
752
|
add. It needs Bun (`bun --bun react-router build`, or a `bunfig.toml` with
|
|
753
753
|
`[run] bun = true`). `alxia({ worker: 'app/pwa/worker.ts' })` names another file
|
|
754
|
-
and `alxia({ worker: false })` builds none.
|
|
754
|
+
and `alxia({ worker: false })` builds none. `alxia({ worker: { precacheRoutes: 'root' } })` (e.g. `plugins: [reactRouter(), alxia({ worker: { precacheRoutes: 'root' } })]`) precaches only the client entry and the root route, leaving the other routes' code to be cached when visited; `precacheFiles` adds files such as manifest icons and `maxPrecacheBytes` (4 MiB) fails a build whose precache grows past it (`"shell"`, the entry and the root CSS, by default; `"all"` is about 10 MB for a real app; a `RegExp` or `(routeId) => boolean` adds routes).
|
|
755
755
|
|
|
756
756
|
The worker bundles Workbox, whose six packages are optional peers:
|
|
757
757
|
|
|
@@ -1781,9 +1781,9 @@ From `@softistx/alxia-react-router/pwa`:
|
|
|
1781
1781
|
| `Caching`, `RequestFacts`, `CachingOptions` | its types |
|
|
1782
1782
|
| `isStorable(response)` | whether a response may be stored: a full, same-origin, `public` 200 of a script, style, font or image, not varying on who asks |
|
|
1783
1783
|
| `parseBrowserManifest(source)` | React Router's browser manifest, read from `build/client/assets/manifest-*.js` |
|
|
1784
|
-
| `precacheList(manifest)` | the hashed scripts and stylesheets
|
|
1784
|
+
| `precacheList(manifest, routes?)` | the hashed scripts and stylesheets the routes need (the app shell by default, or the `routes` kept: `'all'`, `'root'`, a RegExp or a predicate over route ids), as Workbox precache entries |
|
|
1785
1785
|
| `assetPrecache(files, include, base?)` | the entries of the files in `build/client/assets` that a regex of yours matches, such as fonts |
|
|
1786
|
-
| `BrowserManifest`, `PrecacheEntry` | their types |
|
|
1786
|
+
| `BrowserManifest`, `PrecacheEntry`, `PrecacheRoutes` | their types |
|
|
1787
1787
|
| `fontPrecachePattern(families)` | the `precacheAssets` regex for `<family>-<8 hash chars>.woff2` files, from the file-name stems you keep offline (`['inter-latin', 'display-latin-wght-normal']`); a stem matches whole, regex characters are escaped, throws on an empty list |
|
|
1788
1788
|
| `themeColorHex(token)`, `themeColors(tokens)` | a theme colour token (`#rgb`, `#rrggbb` or `oklch(L C H)`) as the `#rrggbb` a manifest `themeColor` and a `theme-color` meta need; `themeColors` converts a record of tokens and keeps its keys |
|
|
1789
1789
|
| `clearAppCaches(contract)` | deletes the caches the worker filled but the offline page; for sign-out. Does nothing without Cache Storage |
|
|
@@ -1824,14 +1824,15 @@ From `@softistx/alxia-react-router/pwa/worker` (the six `workbox-*` packages, op
|
|
|
1824
1824
|
| --- | --- |
|
|
1825
1825
|
| `startWorker(options)` | the worker's strategies: the precache route, `NetworkOnly` for a page load with the precached offline page as its fallback, `CacheFirst` for hashed bundles, `StaleWhileRevalidate` for other static files (both storing only what `isStorable` accepts), the obsolete caches swept on `activate`, and `SKIP_WAITING` applied |
|
|
1826
1826
|
| `WorkerOptions` | `contract` (required), `caching`, `assets`, `static`, `navigationPreload`, `precache` |
|
|
1827
|
+
| `injectedPrecache()` | the precache list the build wrote into the worker, or `undefined`; filter it and pass the result as `WorkerOptions.precache` |
|
|
1827
1828
|
| `ExpirationOptions` | `{ maxEntries?, maxAgeSeconds? }` |
|
|
1828
1829
|
|
|
1829
1830
|
From `@softistx/alxia-react-router/pwa/build` (Bun; Node's built-ins its only imports):
|
|
1830
1831
|
|
|
1831
1832
|
| export | |
|
|
1832
1833
|
| --- | --- |
|
|
1833
|
-
| `buildWorker(options)` | bundles the worker into `build/client/service-worker.js` with its precache list (the offline page by its content,
|
|
1834
|
-
| `BuildWorkerOptions` | `file` (required), `root`, `client`, `contract`, `offline`, `precacheAssets`, `minify` |
|
|
1834
|
+
| `buildWorker(options)` | bundles the worker into `build/client/service-worker.js` with its precache list (the offline page by its content, the app shell's code, `precacheFiles`, `precacheAssets`; 4 MiB cap), after `react-router build` |
|
|
1835
|
+
| `BuildWorkerOptions` | `file` (required), `root`, `client`, `contract`, `offline`, `precacheRoutes`, `precacheFiles`, `maxPrecacheBytes`, `precacheAssets`, `minify` |
|
|
1835
1836
|
| `WorkerBuild` | `{ file, precache, precacheBytes, bytes }` |
|
|
1836
1837
|
|
|
1837
1838
|
From `@softistx/alxia-react-router/errors` (`react-router` is its only package import, and never `@softistx/alxia`):
|
|
@@ -8,9 +8,20 @@ function parseBrowserManifest2(source) {
|
|
|
8
8
|
}
|
|
9
9
|
return JSON.parse(source.slice(start, end + 1));
|
|
10
10
|
}
|
|
11
|
-
function
|
|
11
|
+
function keepsRoute(routes, id) {
|
|
12
|
+
if (id === "root" || routes === "all")
|
|
13
|
+
return true;
|
|
14
|
+
if (routes === "root" || routes === "shell")
|
|
15
|
+
return false;
|
|
16
|
+
if (typeof routes === "function")
|
|
17
|
+
return routes(id);
|
|
18
|
+
routes.lastIndex = 0;
|
|
19
|
+
return routes.test(id);
|
|
20
|
+
}
|
|
21
|
+
function precacheList2(manifest, routes = "shell") {
|
|
12
22
|
const urls = new Set([manifest.url]);
|
|
13
|
-
|
|
23
|
+
const parts = Object.entries(manifest.routes).filter(([id]) => keepsRoute(routes, id)).map(([id, part]) => routes === "shell" && id === "root" ? { css: part.css ?? [] } : part);
|
|
24
|
+
for (const part of [manifest.entry, ...parts]) {
|
|
14
25
|
for (const url of [
|
|
15
26
|
...part.module ? [part.module] : [],
|
|
16
27
|
...part.imports ?? [],
|
|
@@ -19,10 +30,12 @@ function precacheList2(manifest) {
|
|
|
19
30
|
urls.add(url);
|
|
20
31
|
}
|
|
21
32
|
}
|
|
22
|
-
return [...urls].filter((url) => HASHED_ASSET.test(url)).map((url) => ({ url, revision: null }));
|
|
33
|
+
return [...urls].filter((url) => !url.endsWith("/") && HASHED_ASSET.test(url)).map((url) => ({ url, revision: null }));
|
|
23
34
|
}
|
|
24
35
|
function assetPrecache2(assetFiles, include, base = "/assets/") {
|
|
25
36
|
return assetFiles.filter((file) => {
|
|
37
|
+
if (file.endsWith("/"))
|
|
38
|
+
return false;
|
|
26
39
|
include.lastIndex = 0;
|
|
27
40
|
return include.test(file);
|
|
28
41
|
}).sort().map((file) => ({ url: `${base}${file}`, revision: null }));
|
|
@@ -30,5 +43,5 @@ function assetPrecache2(assetFiles, include, base = "/assets/") {
|
|
|
30
43
|
|
|
31
44
|
export { parseBrowserManifest2, precacheList2, assetPrecache2 };
|
|
32
45
|
|
|
33
|
-
//# debugId=
|
|
34
|
-
//# sourceMappingURL=index-
|
|
46
|
+
//# debugId=03ABD5BDC80F739564756E2164756E21
|
|
47
|
+
//# sourceMappingURL=index-jt62gn6d.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/pwa/model/precache-list.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * What the service worker precaches, read from a build: by default the app\n * shell only (the manifest, the client entry with its imports and CSS, and\n * the root route's CSS). Every route's code (`routes: 'all'`) is about 10 MB\n * for a real app, and the worker stays \"installing\" for 15 to 30 seconds. Only\n * hashed `/assets/` files, never a directory: a new build names new files, so\n * each precaches under its own URL, revision `null`. Everything else is\n * stored by the cache-first route the first time it loads.\n *\n * Dependency-free: a build script runs it at build time.\n */\n\n/** A route or the entry, as `window.__reactRouterManifest` lists it. */\ntype ManifestModule = { module?: string; imports?: string[]; css?: string[] };\n\n/** The parts of React Router's browser manifest the list reads. */\nexport type BrowserManifest = {\n\turl: string;\n\tentry: ManifestModule;\n\troutes: Record<string, ManifestModule>;\n};\n\n/** A Workbox precache entry: a hashed URL needs no revision. */\nexport type PrecacheEntry = { url: string; revision: string | null };\n\n/** A Vite-hashed file under `/assets/`: `name-<8 hash chars>.js|css`. */\nconst HASHED_ASSET = /^\\/assets\\/[^/]+-[\\w-]{8}\\.(?:js|css)$/;\n\n/** Reads `window.__reactRouterManifest={…};` (build/client/assets/manifest-*.js). */\nexport function parseBrowserManifest(source: string): BrowserManifest {\n\tconst start = source.indexOf('{');\n\tconst end = source.lastIndexOf('}');\n\tif (start < 0 || end < start) {\n\t\tthrow new Error(\n\t\t\t\"parseBrowserManifest(): not React Router's browser manifest (build/client/assets/manifest-*.js).\",\n\t\t);\n\t}\n\treturn JSON.parse(source.slice(start, end + 1)) as BrowserManifest;\n}\n\n/**\n * Which routes' code the list holds: `\"shell\"` (the default: the root\n * route's CSS only), `\"root\"` (the root route's module, imports and CSS),\n * `\"all\"`, a RegExp or a predicate over the route ids of `app/routes.ts`\n * (`root`, `routes/items`, …; they add the matching routes to the root\n * route). The client entry and its imports are always kept.\n */\nexport type PrecacheRoutes =\n\t| 'shell'\n\t| 'all'\n\t| 'root'\n\t| RegExp\n\t| ((routeId: string) => boolean);\n\nfunction keepsRoute(routes: PrecacheRoutes, id: string): boolean {\n\tif (id === 'root' || routes === 'all') return true;\n\tif (routes === 'root' || routes === 'shell') return false;\n\tif (typeof routes === 'function') return routes(id);\n\troutes.lastIndex = 0; // a /g or /y regex remembers its last match\n\treturn routes.test(id);\n}\n\n/**\n * The hashed scripts and stylesheets the routes need, the manifest's own file\n * first. `routes` narrows which routes' code is kept (the shell by default).\n */\nexport function precacheList(\n\tmanifest: BrowserManifest,\n\troutes: PrecacheRoutes = 'shell',\n): PrecacheEntry[] {\n\tconst urls = new Set<string>([manifest.url]);\n\tconst parts: ManifestModule[] = Object.entries(manifest.routes)\n\t\t.filter(([id]) => keepsRoute(routes, id))\n\t\t.map(([id, part]) =>\n\t\t\t// The shell takes the root route's stylesheets, not its code.\n\t\t\troutes === 'shell' && id === 'root' ? { css: part.css ?? [] } : part,\n\t\t);\n\tfor (const part of [manifest.entry, ...parts]) {\n\t\tfor (const url of [\n\t\t\t...(part.module ? [part.module] : []),\n\t\t\t...(part.imports ?? []),\n\t\t\t...(part.css ?? []),\n\t\t]) {\n\t\t\turls.add(url);\n\t\t}\n\t}\n\treturn [...urls]\n\t\t.filter((url) => !url.endsWith('/') && HASHED_ASSET.test(url))\n\t\t.map((url) => ({ url, revision: null }));\n}\n\n/**\n * The precache entries of the files among `assetFiles` (the names in\n * build/client/assets) that `include` matches, sorted, under `base`: fonts\n * an app keeps offline, say. The regex is the app's.\n */\nexport function assetPrecache(\n\tassetFiles: readonly string[],\n\tinclude: RegExp,\n\tbase = '/assets/',\n): PrecacheEntry[] {\n\treturn assetFiles\n\t\t.filter((file) => {\n\t\t\tif (file.endsWith('/')) return false; // a directory is no file to fetch\n\t\t\tinclude.lastIndex = 0; // a /g or /y regex remembers its last match\n\t\t\treturn include.test(file);\n\t\t})\n\t\t.sort()\n\t\t.map((file) => ({ url: `${base}${file}`, revision: null }));\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";AA0BA,IAAM,eAAe;AAGd,SAAS,qBAAoB,CAAC,QAAiC;AAAA,EACrE,MAAM,QAAQ,OAAO,QAAQ,GAAG;AAAA,EAChC,MAAM,MAAM,OAAO,YAAY,GAAG;AAAA,EAClC,IAAI,QAAQ,KAAK,MAAM,OAAO;AAAA,IAC7B,MAAM,IAAI,MACT,kGACD;AAAA,EACD;AAAA,EACA,OAAO,KAAK,MAAM,OAAO,MAAM,OAAO,MAAM,CAAC,CAAC;AAAA;AAiB/C,SAAS,UAAU,CAAC,QAAwB,IAAqB;AAAA,EAChE,IAAI,OAAO,UAAU,WAAW;AAAA,IAAO,OAAO;AAAA,EAC9C,IAAI,WAAW,UAAU,WAAW;AAAA,IAAS,OAAO;AAAA,EACpD,IAAI,OAAO,WAAW;AAAA,IAAY,OAAO,OAAO,EAAE;AAAA,EAClD,OAAO,YAAY;AAAA,EACnB,OAAO,OAAO,KAAK,EAAE;AAAA;AAOf,SAAS,aAAY,CAC3B,UACA,SAAyB,SACP;AAAA,EAClB,MAAM,OAAO,IAAI,IAAY,CAAC,SAAS,GAAG,CAAC;AAAA,EAC3C,MAAM,QAA0B,OAAO,QAAQ,SAAS,MAAM,EAC5D,OAAO,EAAE,QAAQ,WAAW,QAAQ,EAAE,CAAC,EACvC,IAAI,EAAE,IAAI,UAEV,WAAW,WAAW,OAAO,SAAS,EAAE,KAAK,KAAK,OAAO,CAAC,EAAE,IAAI,IACjE;AAAA,EACD,WAAW,QAAQ,CAAC,SAAS,OAAO,GAAG,KAAK,GAAG;AAAA,IAC9C,WAAW,OAAO;AAAA,MACjB,GAAI,KAAK,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC;AAAA,MACnC,GAAI,KAAK,WAAW,CAAC;AAAA,MACrB,GAAI,KAAK,OAAO,CAAC;AAAA,IAClB,GAAG;AAAA,MACF,KAAK,IAAI,GAAG;AAAA,IACb;AAAA,EACD;AAAA,EACA,OAAO,CAAC,GAAG,IAAI,EACb,OAAO,CAAC,QAAQ,CAAC,IAAI,SAAS,GAAG,KAAK,aAAa,KAAK,GAAG,CAAC,EAC5D,IAAI,CAAC,SAAS,EAAE,KAAK,UAAU,KAAK,EAAE;AAAA;AAQlC,SAAS,cAAa,CAC5B,YACA,SACA,OAAO,YACW;AAAA,EAClB,OAAO,WACL,OAAO,CAAC,SAAS;AAAA,IACjB,IAAI,KAAK,SAAS,GAAG;AAAA,MAAG,OAAO;AAAA,IAC/B,QAAQ,YAAY;AAAA,IACpB,OAAO,QAAQ,KAAK,IAAI;AAAA,GACxB,EACA,KAAK,EACL,IAAI,CAAC,UAAU,EAAE,KAAK,GAAG,OAAO,QAAQ,UAAU,KAAK,EAAE;AAAA;",
|
|
8
|
+
"debugId": "03ABD5BDC80F739564756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// src/pwa/worker/injected.ts
|
|
2
|
+
var PRECACHE_DEFINE = "globalThis.__ALXIA_PRECACHE__";
|
|
3
|
+
function injectedPrecache2() {
|
|
4
|
+
return globalThis.__ALXIA_PRECACHE__;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export { PRECACHE_DEFINE, injectedPrecache2 };
|
|
8
|
+
|
|
9
|
+
//# debugId=EC1988A1AB9FF26C64756E2164756E21
|
|
10
|
+
//# sourceMappingURL=index-q0ks955b.js.map
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/** The define key the build sets: the worker's precache list, as JSON. */\nexport const PRECACHE_DEFINE = 'globalThis.__ALXIA_PRECACHE__';\n\n/** One file the worker precaches: its URL and a revision (`null` when hashed in the name). */\ntype Entry = { readonly url: string; readonly revision: string | null };\n\n/**\n * The precache list the build wrote into this worker, or `undefined` when the\n * worker did not go through the build. Read through `globalThis`, so a missing\n * define is `undefined`, never a `ReferenceError`.\n */\nexport function injectedPrecache(): readonly Entry[] | undefined {\n\treturn (globalThis as { __ALXIA_PRECACHE__?: readonly Entry[] })\n\t\t.__ALXIA_PRECACHE__;\n}\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": ";AACO,IAAM,kBAAkB;AAUxB,SAAS,
|
|
8
|
-
"debugId": "
|
|
7
|
+
"mappings": ";AACO,IAAM,kBAAkB;AAUxB,SAAS,iBAAgB,GAAiC;AAAA,EAChE,OAAQ,WACN;AAAA;",
|
|
8
|
+
"debugId": "EC1988A1AB9FF26C64756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
PRECACHE_DEFINE
|
|
3
|
-
} from "./index-
|
|
3
|
+
} from "./index-q0ks955b.js";
|
|
4
4
|
import {
|
|
5
5
|
parseBrowserManifest2,
|
|
6
6
|
precacheList2,
|
|
7
7
|
assetPrecache2
|
|
8
|
-
} from "./index-
|
|
8
|
+
} from "./index-jt62gn6d.js";
|
|
9
9
|
import {
|
|
10
10
|
SERVICE_WORKER_URL2,
|
|
11
11
|
OFFLINE_URL2
|
|
@@ -32,14 +32,16 @@ function revisionOf(bytes) {
|
|
|
32
32
|
function workerPrecache(input) {
|
|
33
33
|
const all = [
|
|
34
34
|
...input.offline ? [input.offline] : [],
|
|
35
|
-
...precacheList2(parseBrowserManifest2(input.manifestSource)),
|
|
35
|
+
...precacheList2(parseBrowserManifest2(input.manifestSource), input.routes),
|
|
36
|
+
...input.files ?? [],
|
|
36
37
|
...input.include ? assetPrecache2(input.assetFiles, input.include) : []
|
|
37
38
|
];
|
|
38
39
|
const seen = new Set;
|
|
39
|
-
return all.filter(({ url }) => !seen.has(url) && seen.add(url));
|
|
40
|
+
return all.filter(({ url }) => !url.endsWith("/") && !seen.has(url) && seen.add(url));
|
|
40
41
|
}
|
|
41
42
|
|
|
42
43
|
// src/pwa/build/build-worker.ts
|
|
44
|
+
var MAX_PRECACHE_BYTES = 4 * 1024 * 1024;
|
|
43
45
|
function assertBun(onBun = globalThis.Bun !== undefined) {
|
|
44
46
|
if (onBun)
|
|
45
47
|
return;
|
|
@@ -73,12 +75,30 @@ async function buildWorker2(options) {
|
|
|
73
75
|
}
|
|
74
76
|
offline = { url: offlineUrl, revision: revisionOf(await readFile(page)) };
|
|
75
77
|
}
|
|
78
|
+
const extra = [];
|
|
79
|
+
for (const url of options.precacheFiles ?? []) {
|
|
80
|
+
const path = urlInClient(client, url);
|
|
81
|
+
if (!existsSync(path)) {
|
|
82
|
+
throw new Error(`buildWorker(): precacheFiles names ${url}, which does not exist in ${options.client ?? "build/client"}.`);
|
|
83
|
+
}
|
|
84
|
+
extra.push({ url, revision: revisionOf(await readFile(path)) });
|
|
85
|
+
}
|
|
76
86
|
const precache = workerPrecache({
|
|
77
87
|
manifestSource: await readFile(join(assets, manifest), "utf8"),
|
|
78
88
|
assetFiles: files,
|
|
79
89
|
offline,
|
|
80
|
-
include: options.precacheAssets
|
|
90
|
+
include: options.precacheAssets,
|
|
91
|
+
files: extra,
|
|
92
|
+
routes: options.precacheRoutes
|
|
81
93
|
});
|
|
94
|
+
let precacheBytes = 0;
|
|
95
|
+
for (const { url } of precache) {
|
|
96
|
+
precacheBytes += (await stat(join(client, url))).size;
|
|
97
|
+
}
|
|
98
|
+
const cap = options.maxPrecacheBytes ?? MAX_PRECACHE_BYTES;
|
|
99
|
+
if (precacheBytes > cap) {
|
|
100
|
+
throw new Error(`buildWorker(): the precache is ${precache.length} files, ${(precacheBytes / 1048576).toFixed(2)} MB, past the ${(cap / 1048576).toFixed(2)} MB cap. A worker precaches the app shell; other chunks load and cache on first use. Trim precacheAssets, precacheFiles or precacheRoutes, or raise maxPrecacheBytes.`);
|
|
101
|
+
}
|
|
82
102
|
const out = urlInClient(client, workerUrl);
|
|
83
103
|
const result = await Bun.build({
|
|
84
104
|
entrypoints: [source],
|
|
@@ -102,10 +122,6 @@ ${detail}`);
|
|
|
102
122
|
${result.logs.map(String).join(`
|
|
103
123
|
`)}`);
|
|
104
124
|
}
|
|
105
|
-
let precacheBytes = 0;
|
|
106
|
-
for (const { url } of precache) {
|
|
107
|
-
precacheBytes += (await stat(join(client, url))).size;
|
|
108
|
-
}
|
|
109
125
|
return {
|
|
110
126
|
file: out,
|
|
111
127
|
precache,
|
|
@@ -115,5 +131,5 @@ ${result.logs.map(String).join(`
|
|
|
115
131
|
}
|
|
116
132
|
export { buildWorker2 };
|
|
117
133
|
|
|
118
|
-
//# debugId=
|
|
119
|
-
//# sourceMappingURL=index-
|
|
134
|
+
//# debugId=1B3B24F957A3845D64756E2164756E21
|
|
135
|
+
//# sourceMappingURL=index-zb23cx4p.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/pwa/build/build-worker.ts", "../src/pwa/build/precache.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { existsSync } from 'node:fs';\nimport { readdir, readFile, stat } from 'node:fs/promises';\nimport { basename, dirname, join, resolve, sep } from 'node:path';\nimport type { PrecacheEntry, PrecacheRoutes } from '../model/precache-list';\nimport {\n\tOFFLINE_URL,\n\tSERVICE_WORKER_URL,\n\ttype WorkerContract,\n} from '../model/worker-contract';\nimport { PRECACHE_DEFINE } from '../worker/injected';\nimport { browserManifestFile, revisionOf, workerPrecache } from './precache';\n\n/** The default cap on the precache: 4 MiB before compression. */\nconst MAX_PRECACHE_BYTES = 4 * 1024 * 1024;\n\nexport interface BuildWorkerOptions {\n\t/**\n\t * The worker's source, relative to `root`: `app/service-worker.ts`. Named\n\t * `file`, not `entry`: `reveal` reads `alxia({ entry })`.\n\t */\n\tfile: string;\n\t/** `process.cwd()` by default. */\n\troot?: string;\n\t/** The client build, relative to `root`: `build/client` by default. */\n\tclient?: string;\n\t/** Where the worker is written and which offline page is precached. */\n\tcontract?: Pick<WorkerContract, 'serviceWorkerUrl' | 'offlineUrl'>;\n\t/** Precache the offline page, which must then exist. `true` by default. */\n\toffline?: boolean;\n\t/** More files of `assets/` to precache, such as fonts: the app's regex. */\n\tprecacheAssets?: RegExp;\n\t/**\n\t * Which routes' code the worker precaches: `\"shell\"` (the default: the\n\t * client entry with its imports and CSS, and the root route's CSS),\n\t * `\"root\"` (and the root route's code), `\"all\"` (every route, about 10 MB\n\t * for a real app), a RegExp or a `(routeId) => boolean` over the route ids,\n\t * which adds the matching routes to the root. The other routes are cached\n\t * when visited.\n\t */\n\tprecacheRoutes?: PrecacheRoutes;\n\t/**\n\t * Other files of the client build to precache, root-relative and revisioned\n\t * by their content: the manifest's icons, say (`/pwa-192x192.png`).\n\t */\n\tprecacheFiles?: readonly string[];\n\t/**\n\t * The most the precache may weigh, before compression, in bytes: the build\n\t * fails past it. 4 MiB by default.\n\t */\n\tmaxPrecacheBytes?: number;\n\t/** `true` by default. */\n\tminify?: boolean;\n}\n\nexport interface WorkerBuild {\n\t/** The absolute path of the worker written. */\n\tfile: string;\n\tprecache: PrecacheEntry[];\n\t/** The precached files' size, before compression. */\n\tprecacheBytes: number;\n\t/** The worker's own size. */\n\tbytes: number;\n}\n\n/** Not `requireBun` of `vite/`: `/pwa/build` imports Node's built-ins only. */\nexport function assertBun(\n\tonBun = (globalThis as { Bun?: unknown }).Bun !== undefined,\n): void {\n\tif (onBun) return;\n\tthrow new Error(\n\t\t'buildWorker() runs on Bun: it is running on Node. Run it with bun, or run react-router build with bun --bun.',\n\t);\n}\n\n/**\n * The file a root-relative URL names inside `client`. It fails closed: a URL\n * that is absolute, protocol-relative, not rooted at `/`, or that resolves to\n * `client` itself or outside it, is refused.\n */\nfunction urlInClient(client: string, url: string): string {\n\tconst path = join(client, url);\n\tif (\n\t\t!url.startsWith('/') ||\n\t\t/^[a-z][a-z0-9+.-]*:|^\\/\\//i.test(url) ||\n\t\t!path.startsWith(client + sep) ||\n\t\tpath.endsWith(sep)\n\t) {\n\t\tthrow new Error(`buildWorker(): ${url} is outside ${client}.`);\n\t}\n\treturn path;\n}\n\n/**\n * Bundles the worker (Workbox included) into the client build, after\n * `react-router build`, with the precache list written in: the offline page\n * by its content, the routes' code (`precacheRoutes`) and `precacheAssets`. A new build\n * changes the list, so the worker's bytes, so the browser installs it.\n * Runs on Bun; the only imports of this module are Node's built-ins.\n */\nexport async function buildWorker(\n\toptions: BuildWorkerOptions,\n): Promise<WorkerBuild> {\n\tassertBun();\n\tconst root = resolve(options.root ?? process.cwd());\n\tconst client = resolve(root, options.client ?? 'build/client');\n\tconst source = resolve(root, options.file);\n\tconst workerUrl = options.contract?.serviceWorkerUrl ?? SERVICE_WORKER_URL;\n\tconst offlineUrl = options.contract?.offlineUrl ?? OFFLINE_URL;\n\tif (!existsSync(source)) {\n\t\tthrow new Error(`buildWorker(): ${options.file} does not exist.`);\n\t}\n\tconst assets = join(client, 'assets');\n\tconst files = await readdir(assets).catch(() => []);\n\tconst manifest = browserManifestFile(files);\n\tlet offline: PrecacheEntry | undefined;\n\tif (options.offline !== false) {\n\t\tconst page = urlInClient(client, offlineUrl);\n\t\tif (!existsSync(page)) {\n\t\t\tthrow new Error(\n\t\t\t\t`buildWorker(): ${options.client ?? 'build/client'}${offlineUrl} does not exist. Add public${offlineUrl}, or pass offline: false (\\`worker: { offline: false }\\` in alxia()), or pass the app's contract (\\`worker: { contract }\\` in alxia()).`,\n\t\t\t);\n\t\t}\n\t\toffline = { url: offlineUrl, revision: revisionOf(await readFile(page)) };\n\t}\n\tconst extra: PrecacheEntry[] = [];\n\tfor (const url of options.precacheFiles ?? []) {\n\t\tconst path = urlInClient(client, url);\n\t\tif (!existsSync(path)) {\n\t\t\tthrow new Error(\n\t\t\t\t`buildWorker(): precacheFiles names ${url}, which does not exist in ${options.client ?? 'build/client'}.`,\n\t\t\t);\n\t\t}\n\t\textra.push({ url, revision: revisionOf(await readFile(path)) });\n\t}\n\tconst precache = workerPrecache({\n\t\tmanifestSource: await readFile(join(assets, manifest), 'utf8'),\n\t\tassetFiles: files,\n\t\toffline,\n\t\tinclude: options.precacheAssets,\n\t\tfiles: extra,\n\t\troutes: options.precacheRoutes,\n\t});\n\tlet precacheBytes = 0;\n\tfor (const { url } of precache) {\n\t\tprecacheBytes += (await stat(join(client, url))).size;\n\t}\n\tconst cap = options.maxPrecacheBytes ?? MAX_PRECACHE_BYTES;\n\tif (precacheBytes > cap) {\n\t\tthrow new Error(\n\t\t\t`buildWorker(): the precache is ${precache.length} files, ${(precacheBytes / 1048576).toFixed(2)} MB, past the ${(cap / 1048576).toFixed(2)} MB cap. A worker precaches the app shell; other chunks load and cache on first use. Trim precacheAssets, precacheFiles or precacheRoutes, or raise maxPrecacheBytes.`,\n\t\t);\n\t}\n\tconst out = urlInClient(client, workerUrl);\n\tconst result = await Bun.build({\n\t\tentrypoints: [source],\n\t\toutdir: dirname(out),\n\t\tnaming: basename(out),\n\t\ttarget: 'browser',\n\t\tformat: 'iife',\n\t\tminify: options.minify ?? true,\n\t\tdefine: {\n\t\t\t// Workbox's production build: no logging, no dev assertions.\n\t\t\t'process.env.NODE_ENV': '\"production\"',\n\t\t\t[PRECACHE_DEFINE]: JSON.stringify(precache),\n\t\t},\n\t}).catch((error: unknown) => {\n\t\tconst detail =\n\t\t\terror instanceof AggregateError\n\t\t\t\t? error.errors.map(String).join('\\n')\n\t\t\t\t: String(error);\n\t\tthrow new Error(`buildWorker(): Bun.build failed:\\n${detail}`);\n\t});\n\tif (!result.success) {\n\t\tthrow new Error(\n\t\t\t`buildWorker(): Bun.build failed:\\n${result.logs.map(String).join('\\n')}`,\n\t\t);\n\t}\n\treturn {\n\t\tfile: out,\n\t\tprecache,\n\t\tprecacheBytes,\n\t\tbytes: (await stat(out)).size,\n\t};\n}\n",
|
|
6
|
+
"import { createHash } from 'node:crypto';\nimport {\n\tassetPrecache,\n\ttype PrecacheEntry,\n\ttype PrecacheRoutes,\n\tparseBrowserManifest,\n\tprecacheList,\n} from '../model/precache-list';\n\n/** The one React Router browser manifest among the names in build/client/assets. */\nexport function browserManifestFile(files: readonly string[]): string {\n\tconst found = files.filter((file) => /^manifest-[\\w-]+\\.js$/.test(file));\n\tconst [only] = found;\n\tif (found.length !== 1 || only === undefined) {\n\t\tthrow new Error(\n\t\t\t`buildWorker(): expected one React Router browser manifest, build/client/assets/manifest-*.js, found ${found.length}. Run react-router build first.`,\n\t\t);\n\t}\n\treturn only;\n}\n\n/** A file's revision: the first 16 hex characters of its sha256. */\nexport function revisionOf(bytes: Uint8Array): string {\n\treturn createHash('sha256').update(bytes).digest('hex').slice(0, 16);\n}\n\n/**\n * The worker's precache list: the offline page (revisioned by its content),\n * the app shell (`routes`: the shell by default), `files`, then the asset files `include` matches. Each URL once,\n * the first kept.\n */\nexport function workerPrecache(input: {\n\tmanifestSource: string;\n\tassetFiles: readonly string[];\n\toffline?: PrecacheEntry | undefined;\n\tinclude?: RegExp | undefined;\n\tfiles?: readonly PrecacheEntry[] | undefined;\n\troutes?: PrecacheRoutes | undefined;\n}): PrecacheEntry[] {\n\tconst all = [\n\t\t...(input.offline ? [input.offline] : []),\n\t\t...precacheList(parseBrowserManifest(input.manifestSource), input.routes),\n\t\t...(input.files ?? []),\n\t\t...(input.include ? assetPrecache(input.assetFiles, input.include) : []),\n\t];\n\tconst seen = new Set<string>();\n\treturn all.filter(\n\t\t({ url }) => !url.endsWith('/') && !seen.has(url) && seen.add(url),\n\t);\n}\n"
|
|
7
|
+
],
|
|
8
|
+
"mappings": ";;;;;;;;;;;;;;AAAA;AACA;AACA;;;ACFA;AAUO,SAAS,mBAAmB,CAAC,OAAkC;AAAA,EACrE,MAAM,QAAQ,MAAM,OAAO,CAAC,SAAS,wBAAwB,KAAK,IAAI,CAAC;AAAA,EACv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AA,IACN,MAAM;AAAA,IACN;AAAA,IACA;AAAA,IACA,QAAQ,MAAM,KAAK,GAAG,GAAG;AAAA,EAC1B;AAAA;",
|
|
9
|
+
"debugId": "1B3B24F957A3845D64756E2164756E21",
|
|
10
|
+
"names": []
|
|
11
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { PrecacheEntry } from '../model/precache-list';
|
|
1
|
+
import type { PrecacheEntry, PrecacheRoutes } from '../model/precache-list';
|
|
2
2
|
import { type WorkerContract } from '../model/worker-contract';
|
|
3
3
|
export interface BuildWorkerOptions {
|
|
4
4
|
/**
|
|
@@ -16,6 +16,25 @@ export interface BuildWorkerOptions {
|
|
|
16
16
|
offline?: boolean;
|
|
17
17
|
/** More files of `assets/` to precache, such as fonts: the app's regex. */
|
|
18
18
|
precacheAssets?: RegExp;
|
|
19
|
+
/**
|
|
20
|
+
* Which routes' code the worker precaches: `"shell"` (the default: the
|
|
21
|
+
* client entry with its imports and CSS, and the root route's CSS),
|
|
22
|
+
* `"root"` (and the root route's code), `"all"` (every route, about 10 MB
|
|
23
|
+
* for a real app), a RegExp or a `(routeId) => boolean` over the route ids,
|
|
24
|
+
* which adds the matching routes to the root. The other routes are cached
|
|
25
|
+
* when visited.
|
|
26
|
+
*/
|
|
27
|
+
precacheRoutes?: PrecacheRoutes;
|
|
28
|
+
/**
|
|
29
|
+
* Other files of the client build to precache, root-relative and revisioned
|
|
30
|
+
* by their content: the manifest's icons, say (`/pwa-192x192.png`).
|
|
31
|
+
*/
|
|
32
|
+
precacheFiles?: readonly string[];
|
|
33
|
+
/**
|
|
34
|
+
* The most the precache may weigh, before compression, in bytes: the build
|
|
35
|
+
* fails past it. 4 MiB by default.
|
|
36
|
+
*/
|
|
37
|
+
maxPrecacheBytes?: number;
|
|
19
38
|
/** `true` by default. */
|
|
20
39
|
minify?: boolean;
|
|
21
40
|
}
|
|
@@ -33,7 +52,7 @@ export declare function assertBun(onBun?: boolean): void;
|
|
|
33
52
|
/**
|
|
34
53
|
* Bundles the worker (Workbox included) into the client build, after
|
|
35
54
|
* `react-router build`, with the precache list written in: the offline page
|
|
36
|
-
* by its content,
|
|
55
|
+
* by its content, the routes' code (`precacheRoutes`) and `precacheAssets`. A new build
|
|
37
56
|
* changes the list, so the worker's bytes, so the browser installs it.
|
|
38
57
|
* Runs on Bun; the only imports of this module are Node's built-ins.
|
|
39
58
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-worker.d.ts","sourceRoot":"","sources":["../../../src/pwa/build/build-worker.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"build-worker.d.ts","sourceRoot":"","sources":["../../../src/pwa/build/build-worker.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC5E,OAAO,EAGN,KAAK,cAAc,EACnB,MAAM,0BAA0B,CAAC;AAOlC,MAAM,WAAW,kBAAkB;IAClC;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IACb,kCAAkC;IAClC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,uEAAuE;IACvE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,uEAAuE;IACvE,QAAQ,CAAC,EAAE,IAAI,CAAC,cAAc,EAAE,kBAAkB,GAAG,YAAY,CAAC,CAAC;IACnE,2EAA2E;IAC3E,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,2EAA2E;IAC3E,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;;;;;OAOG;IACH,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC;;;OAGG;IACH,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,yBAAyB;IACzB,MAAM,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,WAAW;IAC3B,+CAA+C;IAC/C,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,qDAAqD;IACrD,aAAa,EAAE,MAAM,CAAC;IACtB,6BAA6B;IAC7B,KAAK,EAAE,MAAM,CAAC;CACd;AAED,+EAA+E;AAC/E,wBAAgB,SAAS,CACxB,KAAK,UAAsD,GACzD,IAAI,CAKN;AAoBD;;;;;;GAMG;AACH,wBAAsB,WAAW,CAChC,OAAO,EAAE,kBAAkB,GACzB,OAAO,CAAC,WAAW,CAAC,CAkFtB"}
|
package/dist/pwa/build/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { type PrecacheEntry } from '../model/precache-list';
|
|
1
|
+
import { type PrecacheEntry, type PrecacheRoutes } from '../model/precache-list';
|
|
2
2
|
/** The one React Router browser manifest among the names in build/client/assets. */
|
|
3
3
|
export declare function browserManifestFile(files: readonly string[]): string;
|
|
4
4
|
/** A file's revision: the first 16 hex characters of its sha256. */
|
|
5
5
|
export declare function revisionOf(bytes: Uint8Array): string;
|
|
6
6
|
/**
|
|
7
7
|
* The worker's precache list: the offline page (revisioned by its content),
|
|
8
|
-
*
|
|
8
|
+
* the app shell (`routes`: the shell by default), `files`, then the asset files `include` matches. Each URL once,
|
|
9
9
|
* the first kept.
|
|
10
10
|
*/
|
|
11
11
|
export declare function workerPrecache(input: {
|
|
@@ -13,5 +13,7 @@ export declare function workerPrecache(input: {
|
|
|
13
13
|
assetFiles: readonly string[];
|
|
14
14
|
offline?: PrecacheEntry | undefined;
|
|
15
15
|
include?: RegExp | undefined;
|
|
16
|
+
files?: readonly PrecacheEntry[] | undefined;
|
|
17
|
+
routes?: PrecacheRoutes | undefined;
|
|
16
18
|
}): PrecacheEntry[];
|
|
17
19
|
//# sourceMappingURL=precache.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"precache.d.ts","sourceRoot":"","sources":["../../../src/pwa/build/precache.ts"],"names":[],"mappings":"AACA,OAAO,EAEN,KAAK,aAAa,
|
|
1
|
+
{"version":3,"file":"precache.d.ts","sourceRoot":"","sources":["../../../src/pwa/build/precache.ts"],"names":[],"mappings":"AACA,OAAO,EAEN,KAAK,aAAa,EAClB,KAAK,cAAc,EAGnB,MAAM,wBAAwB,CAAC;AAEhC,oFAAoF;AACpF,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CASpE;AAED,oEAAoE;AACpE,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAEpD;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE;IACrC,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,OAAO,CAAC,EAAE,aAAa,GAAG,SAAS,CAAC;IACpC,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,KAAK,CAAC,EAAE,SAAS,aAAa,EAAE,GAAG,SAAS,CAAC;IAC7C,MAAM,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;CACpC,GAAG,aAAa,EAAE,CAWlB"}
|
package/dist/pwa/index.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ export { type Caching, type CachingOptions, cachingFor, type RequestFacts, } fro
|
|
|
7
7
|
export { clearAppCaches } from './model/clear-app-caches';
|
|
8
8
|
export { fontPrecachePattern } from './model/font-precache';
|
|
9
9
|
export { MANIFEST_HEADERS, MANIFEST_PATH, type ManifestIcon, MINIMAL_2023_ICONS, manifestHref, manifestLanguage, type WebAppManifest, type WebAppManifestOptions, webAppManifest, } from './model/manifest';
|
|
10
|
-
export { assetPrecache, type BrowserManifest, type PrecacheEntry, parseBrowserManifest, precacheList, } from './model/precache-list';
|
|
10
|
+
export { assetPrecache, type BrowserManifest, type PrecacheEntry, type PrecacheRoutes, parseBrowserManifest, precacheList, } from './model/precache-list';
|
|
11
11
|
export { type ApplyUpdate, afterLoad, createUpdater, type RegisterOptions, registerServiceWorker, type ServiceWorkerContainerLike, watchForUpdates, } from './model/registration';
|
|
12
12
|
export { isStorable } from './model/storable';
|
|
13
13
|
export { themeColorHex, themeColors } from './model/theme-color';
|
package/dist/pwa/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/pwa/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACN,KAAK,OAAO,EACZ,KAAK,cAAc,EACnB,UAAU,EACV,KAAK,YAAY,GACjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EACN,gBAAgB,EAChB,aAAa,EACb,KAAK,YAAY,EACjB,kBAAkB,EAClB,YAAY,EACZ,gBAAgB,EAChB,KAAK,cAAc,EACnB,KAAK,qBAAqB,EAC1B,cAAc,GACd,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACN,aAAa,EACb,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,oBAAoB,EACpB,YAAY,GACZ,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,KAAK,WAAW,EAChB,SAAS,EACT,aAAa,EACb,KAAK,eAAe,EACpB,qBAAqB,EACrB,KAAK,0BAA0B,EAC/B,eAAe,GACf,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EACN,kBAAkB,EAClB,KAAK,aAAa,EAClB,YAAY,EACZ,gBAAgB,EAChB,KAAK,YAAY,EACjB,KAAK,iBAAiB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,KAAK,UAAU,EACf,oBA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,MAAM,yBAAyB,CAAC"}
|
package/dist/pwa/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* What the service worker precaches, read from a build:
|
|
3
|
-
*
|
|
4
|
-
* route's
|
|
5
|
-
*
|
|
6
|
-
* hashed `/assets/` files: a new build names new files, so
|
|
7
|
-
* under its own URL, revision `null`.
|
|
8
|
-
*
|
|
2
|
+
* What the service worker precaches, read from a build: by default the app
|
|
3
|
+
* shell only (the manifest, the client entry with its imports and CSS, and
|
|
4
|
+
* the root route's CSS). Every route's code (`routes: 'all'`) is about 10 MB
|
|
5
|
+
* for a real app, and the worker stays "installing" for 15 to 30 seconds. Only
|
|
6
|
+
* hashed `/assets/` files, never a directory: a new build names new files, so
|
|
7
|
+
* each precaches under its own URL, revision `null`. Everything else is
|
|
8
|
+
* stored by the cache-first route the first time it loads.
|
|
9
9
|
*
|
|
10
10
|
* Dependency-free: a build script runs it at build time.
|
|
11
11
|
*/
|
|
@@ -28,8 +28,19 @@ export type PrecacheEntry = {
|
|
|
28
28
|
};
|
|
29
29
|
/** Reads `window.__reactRouterManifest={…};` (build/client/assets/manifest-*.js). */
|
|
30
30
|
export declare function parseBrowserManifest(source: string): BrowserManifest;
|
|
31
|
-
/**
|
|
32
|
-
|
|
31
|
+
/**
|
|
32
|
+
* Which routes' code the list holds: `"shell"` (the default: the root
|
|
33
|
+
* route's CSS only), `"root"` (the root route's module, imports and CSS),
|
|
34
|
+
* `"all"`, a RegExp or a predicate over the route ids of `app/routes.ts`
|
|
35
|
+
* (`root`, `routes/items`, …; they add the matching routes to the root
|
|
36
|
+
* route). The client entry and its imports are always kept.
|
|
37
|
+
*/
|
|
38
|
+
export type PrecacheRoutes = 'shell' | 'all' | 'root' | RegExp | ((routeId: string) => boolean);
|
|
39
|
+
/**
|
|
40
|
+
* The hashed scripts and stylesheets the routes need, the manifest's own file
|
|
41
|
+
* first. `routes` narrows which routes' code is kept (the shell by default).
|
|
42
|
+
*/
|
|
43
|
+
export declare function precacheList(manifest: BrowserManifest, routes?: PrecacheRoutes): PrecacheEntry[];
|
|
33
44
|
/**
|
|
34
45
|
* The precache entries of the files among `assetFiles` (the names in
|
|
35
46
|
* build/client/assets) that `include` matches, sorted, under `base`: fonts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"precache-list.d.ts","sourceRoot":"","sources":["../../../src/pwa/model/precache-list.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,wEAAwE;AACxE,KAAK,cAAc,GAAG;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAE9E,mEAAmE;AACnE,MAAM,MAAM,eAAe,GAAG;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,cAAc,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;CACvC,CAAC;AAEF,gEAAgE;AAChE,MAAM,MAAM,aAAa,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC;AAKrE,qFAAqF;AACrF,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,eAAe,CASpE;AAED,
|
|
1
|
+
{"version":3,"file":"precache-list.d.ts","sourceRoot":"","sources":["../../../src/pwa/model/precache-list.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,wEAAwE;AACxE,KAAK,cAAc,GAAG;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAE9E,mEAAmE;AACnE,MAAM,MAAM,eAAe,GAAG;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,cAAc,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;CACvC,CAAC;AAEF,gEAAgE;AAChE,MAAM,MAAM,aAAa,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC;AAKrE,qFAAqF;AACrF,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,eAAe,CASpE;AAED;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,GACvB,OAAO,GACP,KAAK,GACL,MAAM,GACN,MAAM,GACN,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;AAUlC;;;GAGG;AACH,wBAAgB,YAAY,CAC3B,QAAQ,EAAE,eAAe,EACzB,MAAM,GAAE,cAAwB,GAC9B,aAAa,EAAE,CAoBjB;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAC5B,UAAU,EAAE,SAAS,MAAM,EAAE,EAC7B,OAAO,EAAE,MAAM,EACf,IAAI,SAAa,GACf,aAAa,EAAE,CASjB"}
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* packages (`core`, `expiration`, `navigation-preload`, `precaching`,
|
|
5
5
|
* `routing`, `strategies`, optional peers) are its only package imports.
|
|
6
6
|
*/
|
|
7
|
+
export { injectedPrecache } from './injected';
|
|
7
8
|
export type { ExpirationOptions, WorkerOptions } from './plan';
|
|
8
9
|
export { startWorker } from './start-worker';
|
|
9
10
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/pwa/worker/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/pwa/worker/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC"}
|
package/dist/pwa/worker/index.js
CHANGED
|
@@ -3,12 +3,11 @@ import {
|
|
|
3
3
|
isStorable2
|
|
4
4
|
} from "../../chunks/index-zdbqzcjp.js";
|
|
5
5
|
import {
|
|
6
|
-
|
|
7
|
-
} from "../../chunks/index-
|
|
6
|
+
injectedPrecache2
|
|
7
|
+
} from "../../chunks/index-q0ks955b.js";
|
|
8
8
|
import {
|
|
9
9
|
SKIP_WAITING2
|
|
10
10
|
} from "../../chunks/index-rfr02vg4.js";
|
|
11
|
-
|
|
12
11
|
// src/pwa/worker/start-worker.ts
|
|
13
12
|
import {
|
|
14
13
|
clientsClaim,
|
|
@@ -96,7 +95,7 @@ var workerScope = () => globalThis;
|
|
|
96
95
|
|
|
97
96
|
// src/pwa/worker/start-worker.ts
|
|
98
97
|
function startWorker(options) {
|
|
99
|
-
const plan = workerPlan(options,
|
|
98
|
+
const plan = workerPlan(options, injectedPrecache2());
|
|
100
99
|
const scope = workerScope();
|
|
101
100
|
const { contract } = options;
|
|
102
101
|
setCacheNameDetails(plan.cacheNameDetails);
|
|
@@ -137,8 +136,9 @@ function startWorker(options) {
|
|
|
137
136
|
});
|
|
138
137
|
}
|
|
139
138
|
export {
|
|
139
|
+
injectedPrecache2 as injectedPrecache,
|
|
140
140
|
startWorker
|
|
141
141
|
};
|
|
142
142
|
|
|
143
|
-
//# debugId=
|
|
143
|
+
//# debugId=7DA3F7F688E186F864756E2164756E21
|
|
144
144
|
//# sourceMappingURL=index.js.map
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
"import {\n\ttype Caching,\n\ttype CachingOptions,\n\tcachingFor,\n\ttype RequestFacts,\n} from '../model/caching';\nimport type { PrecacheEntry } from '../model/precache-list';\nimport { isStorable } from '../model/storable';\nimport { SKIP_WAITING, type WorkerContract } from '../model/worker-contract';\n\n/** How many files, and for how long, a runtime cache keeps. */\nexport interface ExpirationOptions {\n\tmaxEntries?: number;\n\tmaxAgeSeconds?: number;\n}\n\nexport interface WorkerOptions {\n\t/** The app's contract: cache names, offline page, the worker's URL. */\n\tcontract: WorkerContract;\n\t/** What `cachingFor` reads besides the contract: `never`, `immutable`, `manifestPath`, `serviceWorkerUrl`. */\n\tcaching?: Omit<CachingOptions, 'contract'>;\n\t/** The hashed bundles' cache. `{ maxEntries: 200 }` by default. */\n\tassets?: ExpirationOptions;\n\t/** The other static files' cache. `{ maxEntries: 100, maxAgeSeconds: 30 days }` by default. */\n\tstatic?: ExpirationOptions;\n\t/** Start the worker alongside a page load. `true` by default. */\n\tnavigationPreload?: boolean;\n\t/** The precache list. By default the one the build wrote into the worker. */\n\tprecache?: readonly PrecacheEntry[];\n}\n\nexport type WorkerRoute =\n\t| {\n\t\t\tcaching: 'navigation';\n\t\t\tstrategy: 'network-only';\n\t\t\tfallback: string | undefined;\n\t }\n\t| {\n\t\t\tcaching: 'immutable';\n\t\t\tstrategy: 'cache-first';\n\t\t\tcacheName: string;\n\t\t\texpiration: ExpirationOptions & { maxEntries: number };\n\t }\n\t| {\n\t\t\tcaching: 'static';\n\t\t\tstrategy: 'stale-while-revalidate';\n\t\t\tcacheName: string;\n\t\t\texpiration: ExpirationOptions;\n\t };\n\nexport interface WorkerPlan {\n\tcacheNameDetails: { prefix: string; precache: 'precache'; suffix: string };\n\tprecache: readonly PrecacheEntry[];\n\troutes: readonly WorkerRoute[];\n\tnavigationPreload: boolean;\n}\n\nconst THIRTY_DAYS = 30 * 24 * 60 * 60;\n\n/** What the worker does, decided without Workbox so that it is tested as data. */\nexport function workerPlan(\n\toptions: WorkerOptions,\n\tinjected: readonly PrecacheEntry[] | undefined,\n): WorkerPlan {\n\tconst { contract } = options;\n\tif (!contract) {\n\t\tthrow new TypeError(\n\t\t\t'startWorker(): contract is required: pass defineWorkerContract({ cachePrefix }) from @softistx/alxia-react-router/pwa.',\n\t\t);\n\t}\n\tconst precache = options.precache ?? injected;\n\tif (!precache) {\n\t\tthrow new Error(\n\t\t\t'startWorker(): no precache list. Build this worker with alxia() from @softistx/alxia-react-router/vite (app/service-worker.ts) or buildWorker() from @softistx/alxia-react-router/pwa/build, which write it in.',\n\t\t);\n\t}\n\tconst offlineUrl = contract.offlineUrl;\n\tconst hasOffline = precache.some(\n\t\t(entry) => entry.url.split('?')[0] === offlineUrl,\n\t);\n\treturn {\n\t\tcacheNameDetails: {\n\t\t\tprefix: contract.cachePrefix,\n\t\t\tprecache: 'precache',\n\t\t\tsuffix: contract.cacheVersion,\n\t\t},\n\t\tprecache,\n\t\troutes: [\n\t\t\t{\n\t\t\t\tcaching: 'navigation',\n\t\t\t\tstrategy: 'network-only',\n\t\t\t\tfallback: hasOffline ? offlineUrl : undefined,\n\t\t\t},\n\t\t\t{\n\t\t\t\tcaching: 'immutable',\n\t\t\t\tstrategy: 'cache-first',\n\t\t\t\tcacheName: contract.cacheNames.assets,\n\t\t\t\texpiration: { maxEntries: 200, ...options.assets },\n\t\t\t},\n\t\t\t{\n\t\t\t\tcaching: 'static',\n\t\t\t\tstrategy: 'stale-while-revalidate',\n\t\t\t\tcacheName: contract.cacheNames.static,\n\t\t\t\texpiration: {\n\t\t\t\t\tmaxEntries: 100,\n\t\t\t\t\tmaxAgeSeconds: THIRTY_DAYS,\n\t\t\t\t\t...options.static,\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\tnavigationPreload: options.navigationPreload ?? true,\n\t};\n}\n\n/** Whether a request is answered the way `caching` says. */\nexport function matcher(\n\tcaching: Caching,\n\torigin: () => string,\n\toptions: WorkerOptions,\n): (o: { request: RequestFacts }) => boolean {\n\treturn ({ request }) =>\n\t\tcachingFor(request, origin(), {\n\t\t\t...options.caching,\n\t\t\tcontract: options.contract,\n\t\t}) === caching;\n}\n\n/** Stores only what `isStorable` accepts: a public, same-origin 200. */\nexport const storableOnly = {\n\tasync cacheWillUpdate({\n\t\tresponse,\n\t}: {\n\t\tresponse: Response;\n\t}): Promise<Response | null> {\n\t\treturn isStorable(response) ? response : null;\n\t},\n};\n\nexport function isSkipWaiting(data: unknown): boolean {\n\treturn (data as { type?: unknown } | null | undefined)?.type === SKIP_WAITING;\n}\n\n/** Deletes the caches an earlier version of the contract owned. */\nexport async function deleteObsoleteCaches(\n\tcontract: Pick<WorkerContract, 'obsoleteCaches'>,\n\tstorage: Pick<CacheStorage, 'keys' | 'delete'>,\n): Promise<void> {\n\tconst names = await storage.keys();\n\tawait Promise.all(\n\t\tcontract.obsoleteCaches(names).map((name) => storage.delete(name)),\n\t);\n}\n",
|
|
7
7
|
"/**\n * The part of the service worker's global scope that `startWorker` reads,\n * declared here so no WebWorker-only type reaches the package's declarations\n * (the DOM lib has no `ServiceWorkerGlobalScope`).\n */\nexport interface WorkerScope {\n\treadonly location: { readonly origin: string };\n\tskipWaiting(): Promise<void>;\n\taddEventListener(\n\t\ttype: 'activate' | 'message',\n\t\tlistener: (event: {\n\t\t\tdata?: unknown;\n\t\t\twaitUntil(promise: Promise<unknown>): void;\n\t\t}) => void,\n\t): void;\n}\n\n/** The worker's scope. Called only inside `startWorker`, never at module load. */\nexport const workerScope = (): WorkerScope =>\n\tglobalThis as unknown as WorkerScope;\n"
|
|
8
8
|
],
|
|
9
|
-
"mappings": "
|
|
10
|
-
"debugId": "
|
|
9
|
+
"mappings": ";;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAKA;AACA;AACA;AACA;AACA;AAAA;AAAA;AAAA;AAAA;;;ACgDA,IAAM,cAAc,KAAK,KAAK,KAAK;AAG5B,SAAS,UAAU,CACzB,SACA,UACa;AAAA,EACb,QAAQ,aAAa;AAAA,EACrB,IAAI,CAAC,UAAU;AAAA,IACd,MAAM,IAAI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AAM,CAAC;AAAA,GACtD;AAAA,EACD,MAAM,iBAAiB,WAAW,CAAC,UAAU;AAAA,IAC5C,IAAI,cAAc,MAAM,IAAI;AAAA,MAAQ,MAAM,YAAY;AAAA,GACtD;AAAA;",
|
|
10
|
+
"debugId": "7DA3F7F688E186F864756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
package/dist/vite/index.d.ts
CHANGED
|
@@ -14,8 +14,8 @@ export interface AlxiaOptions {
|
|
|
14
14
|
/**
|
|
15
15
|
* The service worker, bundled into `build/client/service-worker.js` after
|
|
16
16
|
* `react-router build`, with its precache list: a file relative to Vite's
|
|
17
|
-
* root, or options (`file`, `contract`, `offline`, `
|
|
18
|
-
* `minify`). By default `app/service-worker.ts` when it exists, and
|
|
17
|
+
* root, or options (`file`, `contract`, `offline`, `precacheRoutes`,
|
|
18
|
+
* `precacheAssets`, `precacheFiles`, `maxPrecacheBytes`, `minify`). By default `app/service-worker.ts` when it exists, and
|
|
19
19
|
* nothing without it; `false` builds none. Needs Bun.
|
|
20
20
|
*/
|
|
21
21
|
readonly worker?: false | string | AlxiaWorkerOptions;
|
package/dist/vite/index.js
CHANGED
package/dist/vite/index.js.map
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/vite/index.ts", "../src/vite/bun.ts", "../src/vite/bundle.ts", "../src/vite/compress.ts", "../src/vite/config.ts", "../src/vite/node.ts", "../src/vite/socket.ts", "../src/vite/dev.ts", "../src/vite/hosts.ts", "../src/vite/inline.ts", "../src/vite/preview.ts", "../src/vite/runtime.ts", "../src/vite/worker.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * `@softistx/alxia-react-router/vite`: `alxia()`, the Vite plugin that makes alxia\n * the server of a React Router app, under `react-router dev` and in\n * `react-router build`, with or without an `app/server.ts`.\n */\nimport { join, relative } from 'node:path';\n// Types only: the plugin runs on whichever Vite the app has, never on a\n// copy of this package's own.\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport { ssrEnvironment } from './bundle';\nimport { type PrecompressOptions, precompressClient } from './compress';\nimport {\n\tclientPath,\n\tcontextOf,\n\tDEFAULT,\n\tisChildCompiler,\n\tSERVER,\n\tserverBuildOptions,\n\tserverFile,\n} from './config';\nimport { serveDev } from './dev';\nimport { NAME, PASS_THROUGH, serverEntry } from './entry';\nimport { hostsToAdd, wantedHosts } from './hosts';\nimport { inlineAliases, inlinedFile } from './inline';\nimport { servePreview } from './preview';\nimport { requireBun } from './runtime';\nimport { type AlxiaWorkerOptions, buildAppWorker } from './worker';\n\nexport type { PrecompressOptions } from './compress';\nexport type { AlxiaWorkerOptions } from './worker';\n\nexport interface AlxiaOptions {\n\t/**\n\t * The server file, relative to Vite's root: a module whose default export\n\t * is `createServer()` from `@softistx/alxia-react-router`. By default `server.ts`\n\t * in React Router's app directory, `app/server.ts`, when it exists, and\n\t * otherwise `createServer()` with no options.\n\t */\n\treadonly entry?: string;\n\t/**\n\t * The service worker, bundled into `build/client/service-worker.js` after\n\t * `react-router build`, with its precache list: a file relative to Vite's\n\t * root, or options (`file`, `contract`, `offline`, `
|
|
5
|
+
"/**\n * `@softistx/alxia-react-router/vite`: `alxia()`, the Vite plugin that makes alxia\n * the server of a React Router app, under `react-router dev` and in\n * `react-router build`, with or without an `app/server.ts`.\n */\nimport { join, relative } from 'node:path';\n// Types only: the plugin runs on whichever Vite the app has, never on a\n// copy of this package's own.\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport { ssrEnvironment } from './bundle';\nimport { type PrecompressOptions, precompressClient } from './compress';\nimport {\n\tclientPath,\n\tcontextOf,\n\tDEFAULT,\n\tisChildCompiler,\n\tSERVER,\n\tserverBuildOptions,\n\tserverFile,\n} from './config';\nimport { serveDev } from './dev';\nimport { NAME, PASS_THROUGH, serverEntry } from './entry';\nimport { hostsToAdd, wantedHosts } from './hosts';\nimport { inlineAliases, inlinedFile } from './inline';\nimport { servePreview } from './preview';\nimport { requireBun } from './runtime';\nimport { type AlxiaWorkerOptions, buildAppWorker } from './worker';\n\nexport type { PrecompressOptions } from './compress';\nexport type { AlxiaWorkerOptions } from './worker';\n\nexport interface AlxiaOptions {\n\t/**\n\t * The server file, relative to Vite's root: a module whose default export\n\t * is `createServer()` from `@softistx/alxia-react-router`. By default `server.ts`\n\t * in React Router's app directory, `app/server.ts`, when it exists, and\n\t * otherwise `createServer()` with no options.\n\t */\n\treadonly entry?: string;\n\t/**\n\t * The service worker, bundled into `build/client/service-worker.js` after\n\t * `react-router build`, with its precache list: a file relative to Vite's\n\t * root, or options (`file`, `contract`, `offline`, `precacheRoutes`,\n\t * `precacheAssets`, `precacheFiles`, `maxPrecacheBytes`, `minify`). By default `app/service-worker.ts` when it exists, and\n\t * nothing without it; `false` builds none. Needs Bun.\n\t */\n\treadonly worker?: false | string | AlxiaWorkerOptions;\n\t/**\n\t * Writes `.br` and `.gz` copies beside the client build's compressible\n\t * files (JavaScript, CSS, HTML, SVG, JSON, text, WebAssembly, source\n\t * maps, fonts) of at least `minSize` bytes (1024), after the service\n\t * worker is built: the server sends them to a browser that accepts them.\n\t * On by default; `false` writes none.\n\t */\n\treadonly precompress?: false | PrecompressOptions;\n\t/**\n\t * Hosts added to Vite's `server.allowedHosts` and `preview.allowedHosts`,\n\t * beside the comma-separated `DEV_ALLOWED_HOSTS` variable and the hosts\n\t * the app's own config sets (a leading dot allows the subdomains too).\n\t * For a dev tunnel on a public hostname. Never allows every host: an app\n\t * that set `allowedHosts: true` keeps it. Nothing by default.\n\t */\n\treadonly allowedHosts?: readonly string[];\n}\n\nconst RESOLVED_SERVER = `\\0${SERVER}`;\nconst RESOLVED_DEFAULT = `\\0${DEFAULT}`;\n\n/**\n * Whether there is a server to be: not in the Vite server React Router\n * compiles route modules in, nor in a single-page app. Throws when the\n * server build would be split in several.\n */\nfunction servesApp(resolved: ResolvedConfig): boolean {\n\t// React Router compiles route modules in a Vite server of its own,\n\t// with every plugin but its own: there is nothing to serve there.\n\tif (isChildCompiler(resolved)) return false;\n\tconst rr = contextOf(resolved);\n\t// A single-page app has no server to be.\n\tif (rr.ssr && rr.serverBundles !== undefined) {\n\t\tthrow new Error(\n\t\t\t`${NAME}: serverBundles splits React Router's server build in several, and alxia serves one. Remove serverBundles from react-router.config.ts.`,\n\t\t);\n\t}\n\treturn rr.ssr;\n}\n\n/**\n * The Vite plugin that makes alxia the server of a React Router app,\n * anywhere in `plugins`:\n *\n * ```ts\n * export default defineConfig({ plugins: [alxia(), reactRouter()] });\n * ```\n *\n * - **`react-router dev`**: every request Vite does not answer itself —\n * pages, data, `/api` — goes to the server, loaded through Vite's SSR\n * runner. HMR, an edit to the server, the app's own context keys and\n * its WebSocket routes work, with no restart.\n * - **`react-router build`**: `build/server/index.js` is the server, with\n * React Router's build inside it. `bun build/server/index.js` listens on\n * `PORT` (3000) and `HOST` (`0.0.0.0`); importing it starts nothing.\n * - **`vite preview`**: every request goes to that built server, as it\n * would answer it; so does React Router's prerendering.\n * - **Built for Bun**: the `ssr` environment resolves packages with the\n * `bun` export condition, leaves `bun` and `bun:*` external, and targets\n * `esnext` unless the app set a target. What the app set is kept.\n * - **Self-contained**: `react-router build` bundles every package into\n * `build/server/index.js` (`ssr.noExternal: true`), so `build/` runs with\n * no `node_modules`. `ssr.external` keeps the packages it names external,\n * and `ssr.external: true` all of them.\n *\n * The server is `app/server.ts`'s default export, `createServer()` from\n * `@softistx/alxia-react-router`, or without that file `createServer()` as it is.\n */\nexport function alxia(options: AlxiaOptions = {}): Plugin {\n\tlet config: ResolvedConfig | undefined;\n\tlet enabled = true;\n\n\treturn {\n\t\tname: NAME,\n\t\t// Before React Router's plugin, wherever it is listed: its config reads\n\t\t// the server build's input from this one's, and its dev middleware,\n\t\t// which would render the pages without alxia, comes after this one's.\n\t\tenforce: 'pre',\n\t\tconfig(userConfig, env) {\n\t\t\tconst wanted = wantedHosts(\n\t\t\t\toptions.allowedHosts,\n\t\t\t\tprocess.env['DEV_ALLOWED_HOSTS'],\n\t\t\t);\n\t\t\tconst server = hostsToAdd(userConfig.server?.allowedHosts, wanted);\n\t\t\t// Preview inherits the server's list when it has none: it then takes\n\t\t\t// the server's hosts along with the added ones.\n\t\t\tconst own = userConfig.preview?.allowedHosts;\n\t\t\tconst inherited = userConfig.server?.allowedHosts;\n\t\t\tconst preview =\n\t\t\t\twanted.length > 0 &&\n\t\t\t\town === undefined &&\n\t\t\t\tinherited !== undefined &&\n\t\t\t\tinherited !== true\n\t\t\t\t\t? hostsToAdd(undefined, [...inherited, ...wanted])\n\t\t\t\t\t: hostsToAdd(own ?? inherited, wanted);\n\t\t\tconst hosts = {\n\t\t\t\t...(server === undefined ? {} : { server: { allowedHosts: server } }),\n\t\t\t\t...(preview === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { preview: { allowedHosts: preview } }),\n\t\t\t};\n\t\t\tif (env.command === 'serve') {\n\t\t\t\treturn { ...hosts, ...inlineAliases() };\n\t\t\t}\n\t\t\tif (env.command !== 'build') return;\n\t\t\t// Vite 7's types know neither `rolldownVersion` nor `rolldownOptions`.\n\t\t\tconst meta = this.meta as { readonly rolldownVersion?: string };\n\t\t\tconst bundler = serverBuildOptions(meta.rolldownVersion !== undefined);\n\t\t\treturn { environments: { ssr: { build: bundler as never } } };\n\t\t},\n\t\tconfigEnvironment(name, options, env) {\n\t\t\t// After every config hook, React Router's included: the server\n\t\t\t// environment as the app and the plugins left it, built for Bun.\n\t\t\t// An app that chose `ssr.target: 'webworker'` keeps Vite's own.\n\t\t\tif (name !== 'ssr' || env.isSsrTargetWebworker === true) return;\n\t\t\treturn ssrEnvironment(options, env.command);\n\t\t},\n\t\tconfigResolved(resolved) {\n\t\t\tconfig = resolved;\n\t\t\tenabled = servesApp(resolved);\n\t\t},\n\t\tresolveId(id) {\n\t\t\tif (id === SERVER) return RESOLVED_SERVER;\n\t\t\tif (id === DEFAULT) return RESOLVED_DEFAULT;\n\t\t\t// An absolute path is never external: see inline.ts.\n\t\t\tif (this.environment?.name === 'ssr') return inlinedFile(id);\n\t\t\treturn undefined;\n\t\t},\n\t\tload(id) {\n\t\t\tif (id !== RESOLVED_SERVER && id !== RESOLVED_DEFAULT) return;\n\t\t\tif (config === undefined) return;\n\t\t\t// Disabled, a single-page app: React Router still builds its server\n\t\t\t// build, to render index.html, from this input.\n\t\t\tif (!enabled) return PASS_THROUGH;\n\t\t\tconst dev = config.command === 'serve';\n\t\t\tconst file =\n\t\t\t\tid === RESOLVED_DEFAULT ? undefined : serverFile(options.entry, config);\n\t\t\treturn serverEntry({\n\t\t\t\tfile,\n\t\t\t\tlabel: file === undefined ? '' : relative(config.root, file),\n\t\t\t\tdev,\n\t\t\t\tclient: dev ? undefined : clientPath(config),\n\t\t\t});\n\t\t},\n\t\tbuildApp: {\n\t\t\t// After React Router's builder: its client build, the one the worker reads.\n\t\t\torder: 'post',\n\t\t\tasync handler() {\n\t\t\t\tif (config === undefined) return;\n\t\t\t\tawait buildAppWorker(config, options.worker);\n\t\t\t\tif (!enabled || options.precompress === false) return;\n\t\t\t\tconst done = await precompressClient(\n\t\t\t\t\tjoin(contextOf(config).buildDirectory, 'client'),\n\t\t\t\t\toptions.precompress,\n\t\t\t\t);\n\t\t\t\tconfig.logger.info(\n\t\t\t\t\t`✓ ${done.files} client files precompressed (${(done.bytes / 1024).toFixed(0)} kB → ${(done.brotliBytes / 1024).toFixed(0)} kB brotli)`,\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\tconfigureServer(server) {\n\t\t\tif (!enabled) return;\n\t\t\trequireBun('react-router dev');\n\t\t\treturn serveDev(server, options.entry);\n\t\t},\n\t\tconfigurePreviewServer(server) {\n\t\t\tif (!enabled) return;\n\t\t\t// React Router prerenders through a preview server of its own,\n\t\t\t// resolved as `serve` too: the message cannot tell the two apart.\n\t\t\trequireBun(\n\t\t\t\t'vite preview, or a react-router build that prerenders,',\n\t\t\t\t'bun --bun vite preview or bun --bun react-router build',\n\t\t\t);\n\t\t\t// Before Vite's own files: the built server answers every request.\n\t\t\tservePreview(server);\n\t\t},\n\t};\n}\n",
|
|
6
6
|
"/**\n * The server build, for Bun: what the plugin adds to Vite's `ssr`\n * environment so that `build/server/index.js` is built for the runtime\n * that runs it, and so is the module the dev server loads.\n */\nimport { builtinModules } from 'node:module';\nimport type { EnvironmentOptions } from 'vite';\n\n/** The export condition Bun resolves a package by, and the plugin adds. */\nconst BUN_CONDITION = 'bun';\n\n/**\n * Vite's own builtins for a server environment (its `nodeLikeBuiltins`),\n * which it uses when the config names none: Node's modules, `node:*` and\n * `bun:*`. Bare `bun` is among Node's modules only when Vite runs on Bun.\n */\nconst VITE_BUILTINS: readonly (string | RegExp)[] = [\n\t...builtinModules.filter((id) => !id.includes(':')),\n\t/^node:/,\n\t/^bun:/,\n];\n\n/**\n * Vite's default conditions for a server environment, and for its\n * externals, which it uses when the config names none. React Router's\n * plugin always names them; these are for a config where nothing did.\n */\nconst VITE_CONDITIONS = ['module', 'node', 'development|production'];\nconst VITE_EXTERNAL_CONDITIONS = ['node', 'module-sync'];\n\n/** Bun's own modules, which no bundler should try to resolve: `bun` and `bun:*`. */\nconst BUN_BUILTINS: readonly (string | RegExp)[] = [BUN_CONDITION, /^bun:/];\n\n/**\n * What to merge into `present` so that it holds `wanted`: Vite replaces its\n * default with any value set, so an unset option gets the default too.\n * Strings compare by value, patterns by source.\n */\nfunction adding<T extends string | RegExp>(\n\tpresent: readonly T[] | undefined,\n\tfallback: readonly T[],\n\twanted: readonly T[],\n): T[] {\n\tconst list = present ?? fallback;\n\tconst has = (item: T) =>\n\t\tlist.some((other) =>\n\t\t\ttypeof item === 'string'\n\t\t\t\t? other === item\n\t\t\t\t: other instanceof RegExp && other.source === item.source,\n\t\t);\n\treturn [\n\t\t...(present === undefined ? fallback : []),\n\t\t...wanted.filter((item) => !has(item)),\n\t];\n}\n\n/**\n * What the plugin adds to the `ssr` environment, given its options as the\n * config and every plugin's `config` hook left them. Vite merges the\n * result into them, concatenating arrays, so what the app set is kept:\n *\n * - `resolve.conditions` and `resolve.externalConditions` gain `bun`, so a\n * package that exports a `bun` variant is bundled, and checked, as Bun\n * would load it. Which variant wins stays the package's own order.\n * - `resolve.builtins` gains `bun` and `bun:*`: left external, whichever\n * runtime runs Vite. Vite's own builtins are kept when the app names none.\n * - `build.target` is `esnext`, Bun's, unless the app set one, at the top\n * level or on the environment.\n *\n * `ssr.target` stays `node`: Bun runs Node's modules, and `webworker`\n * would bundle every dependency with the browser's conditions. An app that\n * sets `webworker` itself gets none of this: the plugin leaves that\n * environment to Vite's own defaults.\n */\nexport function bunEnvironment(\n\toptions: EnvironmentOptions,\n): EnvironmentOptions {\n\tconst resolve = options.resolve ?? {};\n\tconst added: EnvironmentOptions = {\n\t\tresolve: {\n\t\t\tconditions: adding(resolve.conditions, VITE_CONDITIONS, [BUN_CONDITION]),\n\t\t\texternalConditions: adding(\n\t\t\t\tresolve.externalConditions,\n\t\t\t\tVITE_EXTERNAL_CONDITIONS,\n\t\t\t\t[BUN_CONDITION],\n\t\t\t),\n\t\t\tbuiltins: adding(resolve.builtins, VITE_BUILTINS, BUN_BUILTINS),\n\t\t},\n\t};\n\tif (options.build?.target === undefined) {\n\t\tadded.build = { target: 'esnext' };\n\t}\n\treturn added;\n}\n",
|
|
7
7
|
"/**\n * The server build, self-contained: every dependency bundled into\n * `build/server/index.js`, so that running it needs `build/` and Bun, and\n * no `node_modules`. A Docker image's final stage copies `build/` alone.\n */\nimport type { EnvironmentOptions } from 'vite';\nimport { bunEnvironment } from './bun';\n\n/**\n * What the plugin adds to the `ssr` environment under `react-router build`,\n * given its options as the config and the plugins left them:\n * `resolve.noExternal: true`, every package bundled. Never in dev, where\n * Vite's SSR runner loads the packages from `node_modules`.\n *\n * What the app set wins:\n *\n * - `ssr.external: ['sharp']`, or the same on `environments.ssr.resolve`,\n * keeps those packages external, imported from `node_modules` at\n * runtime: Vite reads `external` before `noExternal`. Bun's own modules,\n * `bun` and `bun:*`, and Node's are builtins, external whatever this says.\n * - `ssr.external: true` keeps every package external, Vite's own default:\n * the plugin adds nothing then.\n * - `ssr.noExternal`, a list, is a subset of everything: it changes nothing.\n *\n * React Router's own plugin reads `noExternal: true` and adds no externals\n * of its own; it runs after this one, which is `enforce: 'pre'`.\n */\nexport function bundledEnvironment(\n\toptions: EnvironmentOptions,\n): EnvironmentOptions | undefined {\n\tif (options.resolve?.external === true) return undefined;\n\treturn { resolve: { noExternal: true } };\n}\n\n/**\n * Everything the plugin adds to the `ssr` environment: built for Bun under\n * either command, and self-contained under `build` alone. In dev, Vite's\n * SSR runner loads the packages from `node_modules`.\n */\nexport function ssrEnvironment(\n\toptions: EnvironmentOptions,\n\tcommand: 'build' | 'serve',\n): EnvironmentOptions {\n\tconst added = bunEnvironment(options);\n\tconst bundled = command === 'build' ? bundledEnvironment(options) : undefined;\n\tif (bundled === undefined) return added;\n\treturn { ...added, resolve: { ...added.resolve, ...bundled.resolve } };\n}\n",
|
|
8
8
|
"/**\n * The client build's compressed copies: `app.js.br` and `app.js.gz` beside\n * every compressible file, which `app.static(…, { precompressed })` serves\n * to a browser that accepts them, so the server never compresses on a request.\n */\nimport { readdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { extname, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { brotliCompress, constants, gzip } from 'node:zlib';\n\nconst brotli = promisify(brotliCompress);\nconst deflate = promisify(gzip);\n\n/** What compresses well: text, and the formats built on it. */\nconst COMPRESSIBLE = new Set([\n\t'.js',\n\t'.mjs',\n\t'.cjs',\n\t'.css',\n\t'.html',\n\t'.htm',\n\t'.svg',\n\t'.json',\n\t'.map',\n\t'.txt',\n\t'.xml',\n\t'.webmanifest',\n\t'.wasm',\n\t'.ico',\n\t'.ttf',\n\t'.otf',\n\t'.eot',\n]);\n\nexport interface PrecompressOptions {\n\t/** The smallest file, in bytes, that gets copies: 1024 by default. */\n\treadonly minSize?: number;\n}\n\nexport interface Precompressed {\n\t/** The files that got copies. */\n\treadonly files: number;\n\t/** Their size before, and the size of their brotli copies. */\n\treadonly bytes: number;\n\treadonly brotliBytes: number;\n}\n\nasync function* walk(dir: string): AsyncGenerator<string> {\n\tfor (const entry of await readdir(dir, { withFileTypes: true })) {\n\t\tconst path = join(dir, entry.name);\n\t\tif (entry.isDirectory()) yield* walk(path);\n\t\telse if (entry.isFile()) yield path;\n\t}\n}\n\n/**\n * Writes `<file>.br` and `<file>.gz` beside each compressible file of\n * `client` of at least `minSize` bytes, whichever is smaller than the file\n * itself. Brotli at its best quality: it runs once, at build time.\n */\nexport async function precompressClient(\n\tclient: string,\n\toptions: PrecompressOptions = {},\n): Promise<Precompressed> {\n\tconst minSize = options.minSize ?? 1024;\n\tlet files = 0;\n\tlet bytes = 0;\n\tlet brotliBytes = 0;\n\tfor await (const path of walk(client)) {\n\t\tif (!COMPRESSIBLE.has(extname(path).toLowerCase())) continue;\n\t\tconst body = await readFile(path);\n\t\tif (body.length < minSize) continue;\n\t\tconst [br, gz] = await Promise.all([\n\t\t\tbrotli(body, {\n\t\t\t\tparams: {\n\t\t\t\t\t[constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY,\n\t\t\t\t\t[constants.BROTLI_PARAM_SIZE_HINT]: body.length,\n\t\t\t\t},\n\t\t\t}),\n\t\t\tdeflate(body, { level: 9 }),\n\t\t]);\n\t\tlet written = false;\n\t\tfor (const [extension, copy] of [\n\t\t\t['br', br],\n\t\t\t['gz', gz],\n\t\t] as const) {\n\t\t\tif (copy.length < body.length) {\n\t\t\t\tawait writeFile(`${path}.${extension}`, copy);\n\t\t\t\twritten = true;\n\t\t\t} else {\n\t\t\t\t// A copy left by an earlier build would be stale.\n\t\t\t\tawait rm(`${path}.${extension}`, { force: true });\n\t\t\t}\n\t\t}\n\t\tif (!written) continue;\n\t\tfiles += 1;\n\t\tbytes += body.length;\n\t\tbrotliBytes += Math.min(br.length, body.length);\n\t}\n\treturn { files, bytes, brotliBytes };\n}\n",
|
package/docs/guide/pwa.md
CHANGED
|
@@ -34,7 +34,7 @@ globals only inside its functions, never at load.
|
|
|
34
34
|
| `/pwa` | every runtime: the contract, `cachingFor`, `isStorable`, `registerServiceWorker`, `createUpdateNotice`, `manifestHref`, `webAppManifest`, `clearAppCaches`, the precache parts and `SERVICE_WORKER_URL` | nothing: it imports nothing |
|
|
35
35
|
| `/pwa/react` | the page's hooks: `useServiceWorker`, `useUpdateNotice`, `useOnline` | `react` (`^19`), an optional peer. Keep it out of the worker, which would bundle React |
|
|
36
36
|
| `/pwa/server` | the server file alone: `noCache` and `revalidated` | `@softistx/alxia`, a peer the package already has |
|
|
37
|
-
| `/pwa/worker` | the service worker bundle alone: `startWorker` | the six `workbox-*` packages (`core`, `expiration`, `navigation-preload`, `precaching`, `routing`, `strategies`), optional peers (`^7`) |
|
|
37
|
+
| `/pwa/worker` | the service worker bundle alone: `startWorker`, `injectedPrecache` | the six `workbox-*` packages (`core`, `expiration`, `navigation-preload`, `precaching`, `routing`, `strategies`), optional peers (`^7`) |
|
|
38
38
|
| `/pwa/build` | a build pipeline of your own: `buildWorker` | Bun; Node's built-ins are its only imports, and it reads `Bun` only inside the function. The Workbox peers must be installed to bundle the worker |
|
|
39
39
|
|
|
40
40
|
The main entry, `@softistx/alxia-react-router`, is not for those: it imports
|
|
@@ -123,6 +123,8 @@ network; `clientsClaim()` makes a first install control the open pages at
|
|
|
123
123
|
once; an update waits until the page posts `SKIP_WAITING`; and on `activate`
|
|
124
124
|
the caches the contract no longer owns (`obsoleteCaches`) are deleted.
|
|
125
125
|
|
|
126
|
+
`injectedPrecache()` (from `/pwa/worker`) returns the list the build wrote in, or `undefined`: an app can filter it and pass the result as `precache`.
|
|
127
|
+
|
|
126
128
|
The precache list is the `precache` option, or else
|
|
127
129
|
`globalThis.__ALXIA_PRECACHE__`, which the build writes into the bundle (a
|
|
128
130
|
worker bundled some other way passes `precache`, or defines that global in its
|
|
@@ -249,7 +251,32 @@ export default defineConfig({
|
|
|
249
251
|
| left out | `app/service-worker.ts`, when it exists |
|
|
250
252
|
| a string | another file, relative to Vite's root; the build fails when it is not there |
|
|
251
253
|
| `false` | no worker is built |
|
|
252
|
-
| an object | `file` (as the string), `contract`, `offline`, `precacheAssets` and `minify`, as in `buildWorker`'s table below |
|
|
254
|
+
| an object | `file` (as the string), `contract`, `offline`, `precacheRoutes`, `precacheAssets`, `precacheFiles`, `maxPrecacheBytes` and `minify`, as in `buildWorker`'s table below |
|
|
255
|
+
|
|
256
|
+
The default precaches the app shell only. To go lighter still, precache the client
|
|
257
|
+
entry and the root route; the other routes' chunks are cached when visited:
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
// vite.config.ts
|
|
261
|
+
import { alxia } from '@softistx/alxia-react-router/vite';
|
|
262
|
+
import { reactRouter } from '@react-router/dev/vite';
|
|
263
|
+
import { defineConfig } from 'vite';
|
|
264
|
+
|
|
265
|
+
export default defineConfig({
|
|
266
|
+
plugins: [reactRouter(), alxia({ worker: { precacheRoutes: 'root' } })],
|
|
267
|
+
});
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
`startWorker` can also filter the list the build wrote in:
|
|
271
|
+
|
|
272
|
+
```ts
|
|
273
|
+
// app/service-worker.ts
|
|
274
|
+
import { injectedPrecache, startWorker } from '@softistx/alxia-react-router/pwa/worker';
|
|
275
|
+
|
|
276
|
+
startWorker({
|
|
277
|
+
precache: (injectedPrecache() ?? []).filter(({ url }) => !url.endsWith('.css')),
|
|
278
|
+
});
|
|
279
|
+
```
|
|
253
280
|
|
|
254
281
|
The object form takes the options of [`buildWorker`](#with-buildworker), but
|
|
255
282
|
`root` and `client`, which the plugin knows. Its `contract` must be the same
|
|
@@ -299,7 +326,7 @@ console.log(
|
|
|
299
326
|
|
|
300
327
|
Run it as `bun scripts/build-worker.ts` after `react-router build`. The list is
|
|
301
328
|
the offline page, revisioned by its content (a changed page installs a new
|
|
302
|
-
worker), then
|
|
329
|
+
worker), then the app shell's code (see `precacheRoutes`), the `precacheFiles` and the `precacheAssets` files. A new build
|
|
303
330
|
changes the list, so the worker's bytes, so the browser installs it.
|
|
304
331
|
|
|
305
332
|
| option | default | |
|
|
@@ -309,6 +336,9 @@ changes the list, so the worker's bytes, so the browser installs it.
|
|
|
309
336
|
| `client` | `build/client` | the client build, relative to `root` |
|
|
310
337
|
| `contract` | `SERVICE_WORKER_URL`, `OFFLINE_URL` | `{ serviceWorkerUrl, offlineUrl }`: where the worker is written and which offline page is precached. Pass the same object `startWorker` gets (the app's contract), or the build and the worker can disagree |
|
|
311
338
|
| `offline` | `true` | precache the offline page, which must exist in the client build ([`public/offline.html`](#the-offline-page)) |
|
|
339
|
+
| `precacheRoutes` | `"shell"` | which routes' code is precached: `"shell"` (the manifest, the client entry with its imports and CSS, and the `root` route's CSS: about 0.7 MB of code beside the CSS and fonts), `"all"` (every route: about 10 MB for a real app, and a worker still installing 15 to 30 seconds), `"root"` (the client entry and the `root` route, with their imports and CSS, the manifest, the offline page and `precacheAssets`), or a `RegExp` or `(routeId) => boolean` over the route ids (`routes/items`), which adds the matching routes to the entry and `root`, always kept. The other routes' chunks are cached when first visited, so an app with many routes keeps a short first-visit download. A navigation offline to a route not precached and never visited shows the offline page |
|
|
340
|
+
| `precacheFiles` | none | other files of the client build to precache, root-relative (`['/pwa-192x192.png']`), revisioned by their content; a missing one fails the build |
|
|
341
|
+
| `maxPrecacheBytes` | 4 MiB | the build fails when the precache weighs more, before compression |
|
|
312
342
|
| `precacheAssets` | none | a regex over the names in `build/client/assets`, such as fonts; `fontPrecachePattern(['inter-latin', …])` from `/pwa` builds the font one |
|
|
313
343
|
| `minify` | `true` | |
|
|
314
344
|
|
|
@@ -318,8 +348,7 @@ Its errors are in [the troubleshooting page](../troubleshooting.md#buildworker-e
|
|
|
318
348
|
|
|
319
349
|
### The parts
|
|
320
350
|
|
|
321
|
-
|
|
322
|
-
a route never visited still finds its modules. Set
|
|
351
|
+
By default a worker precaches the app shell only; a route's code is cached the first time it loads. To open a route never visited while offline, pass `precacheRoutes: "all"` (a heavy precache) and set
|
|
323
352
|
`routeDiscovery: { mode: 'initial' }` in `react-router.config.ts` as well,
|
|
324
353
|
or the navigation asks `/__manifest` for the route and shows the offline page
|
|
325
354
|
([more](../troubleshooting.md#offline-a-client-navigation-to-a-route-never-visited-shows-the-offline-page)):
|
|
@@ -358,8 +387,8 @@ export const precache = [
|
|
|
358
387
|
];
|
|
359
388
|
```
|
|
360
389
|
|
|
361
|
-
`precacheList(manifest)` returns the manifest's own file first, then the
|
|
362
|
-
entry's and every route's module, imports and CSS, each once, as
|
|
390
|
+
`precacheList(manifest, routes?)` (`routes` is a `PrecacheRoutes`: `'shell'` by default, `'all'`, `'root'`, a RegExp or a predicate over route ids) returns the manifest's own file first, then the
|
|
391
|
+
entry's and, by default, only the root route's CSS (every route's module, imports and CSS with `'all'`), each once, as
|
|
363
392
|
`{ url, revision: null }`: a hashed name needs no revision. Only `/assets/`
|
|
364
393
|
files named `name-<8 hash characters>.js` or `.css` are kept, so a sprite or
|
|
365
394
|
an unhashed script is left out. `assetPrecache(files, include, base?)` adds
|
package/docs/roadmap.md
CHANGED
|
@@ -133,6 +133,14 @@ Nothing queued; see Later.
|
|
|
133
133
|
|
|
134
134
|
### Unreleased
|
|
135
135
|
|
|
136
|
+
- **A light worker precache.** `alxia({ worker: { precacheRoutes } })` and
|
|
137
|
+
`buildWorker` precache the app shell by default (`"shell"`: the client
|
|
138
|
+
entry and the root route's CSS), the root route's code (`"root"`), every
|
|
139
|
+
route (`"all"`, about 10 MB for a real app), or the root plus the routes a
|
|
140
|
+
RegExp or predicate keeps. `precacheFiles` adds files such as the manifest
|
|
141
|
+
icons, `maxPrecacheBytes` (4 MiB) fails the build past a cap, and a
|
|
142
|
+
directory is never listed. `injectedPrecache()` is exported from
|
|
143
|
+
`/pwa/worker`. See the [PWA guide](guide/pwa.md#with-buildworker).
|
|
136
144
|
- **`useStepUpRunner` in `@alxia/react-router/session/react`.** `run(request)`
|
|
137
145
|
posts a sensitive action and resolves with its outcome or `'cancelled'`;
|
|
138
146
|
the step-up opens and the same request is replayed once confirmed. See the
|
package/docs/troubleshooting.md
CHANGED
|
@@ -74,6 +74,7 @@ a loader, a message React Router or the browser prints, or an error from
|
|
|
74
74
|
- [`403 {"error":"proxy_secret_required"}` on `/mcp` or `/oauth/token` of the API](#403-errorproxy_secret_required-on-mcp-or-oauthtoken-of-the-api)
|
|
75
75
|
- [Approving a consent request answers 400 `Bad consent request`](#approving-a-consent-request-answers-400-bad-consent-request)
|
|
76
76
|
- [Every consent request shows the expired state with `requireBinding`](#every-consent-request-shows-the-expired-state-with-requirebinding)
|
|
77
|
+
- [`buildWorker(): the precache is N files, X MB, past the Y MB cap`](#buildworker-the-precache-is-n-files-x-mb-past-the-y-mb-cap)
|
|
77
78
|
- [`startWorker(): no precache list. …`](#startworker-no-precache-list-)
|
|
78
79
|
- [`TypeError: startWorker(): contract is required: …`](#typeerror-startworker-contract-is-required-)
|
|
79
80
|
- [`error: Could not resolve: "workbox-core". Maybe you need to "bun install"?`](#error-could-not-resolve-workbox-core-maybe-you-need-to-bun-install)
|
|
@@ -1571,6 +1572,24 @@ mcpRelay({ api: 'https://api.example.com', secret })
|
|
|
1571
1572
|
|
|
1572
1573
|
**Fix:** pass a positive number of milliseconds, or leave `timeout` out for the 60 000 ms default.
|
|
1573
1574
|
|
|
1575
|
+
### `buildWorker(): the precache is N files, X MB, past the Y MB cap`
|
|
1576
|
+
|
|
1577
|
+
```text
|
|
1578
|
+
buildWorker(): the precache is 388 files, 9.7 MB, past the 4.0 MB cap.
|
|
1579
|
+
```
|
|
1580
|
+
|
|
1581
|
+
**Why:** a worker precaches the app shell, and the build refuses a precache
|
|
1582
|
+
past `maxPrecacheBytes` (4 MiB by default): a heavy precache keeps the worker
|
|
1583
|
+
installing for seconds on a phone. A missing `precacheFiles` entry fails the
|
|
1584
|
+
build too, naming the file.
|
|
1585
|
+
|
|
1586
|
+
**Fix:** trim `precacheAssets`, `precacheFiles` or `precacheRoutes`
|
|
1587
|
+
(`'shell'` is the default, `'root'` is lighter), or raise the cap:
|
|
1588
|
+
|
|
1589
|
+
```ts
|
|
1590
|
+
alxia({ worker: { maxPrecacheBytes: 6 * 1024 * 1024 } });
|
|
1591
|
+
```
|
|
1592
|
+
|
|
1574
1593
|
### `startWorker(): no precache list. …`
|
|
1575
1594
|
|
|
1576
1595
|
**Why:** the full message ends "Build this worker with `alxia()` from
|
|
@@ -2921,6 +2940,11 @@ worker never caches that request.
|
|
|
2921
2940
|
**Fix:** set `routeDiscovery: { mode: 'initial' }` in `react-router.config.ts`,
|
|
2922
2941
|
so the client has every route from its first load.
|
|
2923
2942
|
|
|
2943
|
+
The same page also shows when `precacheRoutes` leaves the route out of the
|
|
2944
|
+
precache (the default `'shell'`, `'root'`, a filter) and the route was never
|
|
2945
|
+
visited online: set `precacheRoutes` to include it (`'all'` is a heavy
|
|
2946
|
+
precache), or visit it once online.
|
|
2947
|
+
|
|
2924
2948
|
### An update waits an hour
|
|
2925
2949
|
|
|
2926
2950
|
A new worker is deployed and tabs still run the old one for up to an hour.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@softistx/alxia-react-router",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.86.0",
|
|
4
4
|
"description": "alxia as the server of a React Router framework app: server rendering behind the app's hooks, loaders reading its typed context, the client's assets served; the code with no UI an installable app shares (`/pwa`), its hooks (`/pwa/react`), `noCache` for the worker's script (`/pwa/server`), the service worker on Workbox (`/pwa/worker`) and its build (`/pwa/build`), an API's refusals worded for the page (`/errors`), the BFF session: cookies, sign-in, step-up and mail links (`/session`), its page hooks (`/session/react`) and what it shares with the page (`/session/model`), a GraphQL subscription relayed to the browser over SSE (`/subscription`) and kept alive in the page (`/subscription/react`), an API's MCP and OAuth endpoints relayed on the app's origin (`/mcp`), per-role flow docs, the help panel's data and its lazy `HelpPanel`, and the role guide's `useGuideRole` (`/help`, `/help/check`), an API's media files read and uploaded through the app (`/media`) and uploaded from the page with progress (`/media/client`), the page's CSP nonce and inline boot scripts (`/document`) and a streaming `entry.server` (`/entry`), the consent screen of an OAuth server: a route's loader and action, the connected apps' list and revoke (`/oauth`) and the decision hook (`/oauth/react`), a user's API keys listed, created behind a step-up and revoked (`/api-keys`) and `/oidc`: a relying party of an external OpenID Connect issuer (authorization code + PKCE, id token validation, a sealed token cookie, refresh and RP-initiated logout)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
// src/pwa/worker/injected.ts
|
|
2
|
-
var PRECACHE_DEFINE = "globalThis.__ALXIA_PRECACHE__";
|
|
3
|
-
function injectedPrecache() {
|
|
4
|
-
return globalThis.__ALXIA_PRECACHE__;
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
export { PRECACHE_DEFINE, injectedPrecache };
|
|
8
|
-
|
|
9
|
-
//# debugId=CA917CBC5F688F4264756E2164756E21
|
|
10
|
-
//# sourceMappingURL=index-59vhfj6n.js.map
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/pwa/model/precache-list.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"/**\n * What the service worker precaches, read from a build: every script and\n * stylesheet React Router's manifest names (the client entry and each\n * route's module, imports and CSS), and the manifest itself, so a client\n * navigation offline to a route never visited still finds its code. Only\n * hashed `/assets/` files: a new build names new files, so each precaches\n * under its own URL, revision `null`. Chunks only a component loads on\n * demand stay out: a cache-first route stores them the first time they load.\n *\n * Dependency-free: a build script runs it at build time.\n */\n\n/** A route or the entry, as `window.__reactRouterManifest` lists it. */\ntype ManifestModule = { module?: string; imports?: string[]; css?: string[] };\n\n/** The parts of React Router's browser manifest the list reads. */\nexport type BrowserManifest = {\n\turl: string;\n\tentry: ManifestModule;\n\troutes: Record<string, ManifestModule>;\n};\n\n/** A Workbox precache entry: a hashed URL needs no revision. */\nexport type PrecacheEntry = { url: string; revision: string | null };\n\n/** A Vite-hashed file under `/assets/`: `name-<8 hash chars>.js|css`. */\nconst HASHED_ASSET = /^\\/assets\\/[^/]+-[\\w-]{8}\\.(?:js|css)$/;\n\n/** Reads `window.__reactRouterManifest={…};` (build/client/assets/manifest-*.js). */\nexport function parseBrowserManifest(source: string): BrowserManifest {\n\tconst start = source.indexOf('{');\n\tconst end = source.lastIndexOf('}');\n\tif (start < 0 || end < start) {\n\t\tthrow new Error(\n\t\t\t\"parseBrowserManifest(): not React Router's browser manifest (build/client/assets/manifest-*.js).\",\n\t\t);\n\t}\n\treturn JSON.parse(source.slice(start, end + 1)) as BrowserManifest;\n}\n\n/** The hashed scripts and stylesheets every route needs, the manifest's own file first. */\nexport function precacheList(manifest: BrowserManifest): PrecacheEntry[] {\n\tconst urls = new Set<string>([manifest.url]);\n\tfor (const part of [manifest.entry, ...Object.values(manifest.routes)]) {\n\t\tfor (const url of [\n\t\t\t...(part.module ? [part.module] : []),\n\t\t\t...(part.imports ?? []),\n\t\t\t...(part.css ?? []),\n\t\t]) {\n\t\t\turls.add(url);\n\t\t}\n\t}\n\treturn [...urls]\n\t\t.filter((url) => HASHED_ASSET.test(url))\n\t\t.map((url) => ({ url, revision: null }));\n}\n\n/**\n * The precache entries of the files among `assetFiles` (the names in\n * build/client/assets) that `include` matches, sorted, under `base`: fonts\n * an app keeps offline, say. The regex is the app's.\n */\nexport function assetPrecache(\n\tassetFiles: readonly string[],\n\tinclude: RegExp,\n\tbase = '/assets/',\n): PrecacheEntry[] {\n\treturn assetFiles\n\t\t.filter((file) => {\n\t\t\tinclude.lastIndex = 0; // a /g or /y regex remembers its last match\n\t\t\treturn include.test(file);\n\t\t})\n\t\t.sort()\n\t\t.map((file) => ({ url: `${base}${file}`, revision: null }));\n}\n"
|
|
6
|
-
],
|
|
7
|
-
"mappings": ";AA0BA,IAAM,eAAe;AAGd,SAAS,qBAAoB,CAAC,QAAiC;AAAA,EACrE,MAAM,QAAQ,OAAO,QAAQ,GAAG;AAAA,EAChC,MAAM,MAAM,OAAO,YAAY,GAAG;AAAA,EAClC,IAAI,QAAQ,KAAK,MAAM,OAAO;AAAA,IAC7B,MAAM,IAAI,MACT,kGACD;AAAA,EACD;AAAA,EACA,OAAO,KAAK,MAAM,OAAO,MAAM,OAAO,MAAM,CAAC,CAAC;AAAA;AAIxC,SAAS,aAAY,CAAC,UAA4C;AAAA,EACxE,MAAM,OAAO,IAAI,IAAY,CAAC,SAAS,GAAG,CAAC;AAAA,EAC3C,WAAW,QAAQ,CAAC,SAAS,OAAO,GAAG,OAAO,OAAO,SAAS,MAAM,CAAC,GAAG;AAAA,IACvE,WAAW,OAAO;AAAA,MACjB,GAAI,KAAK,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC;AAAA,MACnC,GAAI,KAAK,WAAW,CAAC;AAAA,MACrB,GAAI,KAAK,OAAO,CAAC;AAAA,IAClB,GAAG;AAAA,MACF,KAAK,IAAI,GAAG;AAAA,IACb;AAAA,EACD;AAAA,EACA,OAAO,CAAC,GAAG,IAAI,EACb,OAAO,CAAC,QAAQ,aAAa,KAAK,GAAG,CAAC,EACtC,IAAI,CAAC,SAAS,EAAE,KAAK,UAAU,KAAK,EAAE;AAAA;AAQlC,SAAS,cAAa,CAC5B,YACA,SACA,OAAO,YACW;AAAA,EAClB,OAAO,WACL,OAAO,CAAC,SAAS;AAAA,IACjB,QAAQ,YAAY;AAAA,IACpB,OAAO,QAAQ,KAAK,IAAI;AAAA,GACxB,EACA,KAAK,EACL,IAAI,CAAC,UAAU,EAAE,KAAK,GAAG,OAAO,QAAQ,UAAU,KAAK,EAAE;AAAA;",
|
|
8
|
-
"debugId": "812DDA9793A6A64B64756E2164756E21",
|
|
9
|
-
"names": []
|
|
10
|
-
}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/pwa/build/build-worker.ts", "../src/pwa/build/precache.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"import { existsSync } from 'node:fs';\nimport { readdir, readFile, stat } from 'node:fs/promises';\nimport { basename, dirname, join, resolve, sep } from 'node:path';\nimport type { PrecacheEntry } from '../model/precache-list';\nimport {\n\tOFFLINE_URL,\n\tSERVICE_WORKER_URL,\n\ttype WorkerContract,\n} from '../model/worker-contract';\nimport { PRECACHE_DEFINE } from '../worker/injected';\nimport { browserManifestFile, revisionOf, workerPrecache } from './precache';\n\nexport interface BuildWorkerOptions {\n\t/**\n\t * The worker's source, relative to `root`: `app/service-worker.ts`. Named\n\t * `file`, not `entry`: `reveal` reads `alxia({ entry })`.\n\t */\n\tfile: string;\n\t/** `process.cwd()` by default. */\n\troot?: string;\n\t/** The client build, relative to `root`: `build/client` by default. */\n\tclient?: string;\n\t/** Where the worker is written and which offline page is precached. */\n\tcontract?: Pick<WorkerContract, 'serviceWorkerUrl' | 'offlineUrl'>;\n\t/** Precache the offline page, which must then exist. `true` by default. */\n\toffline?: boolean;\n\t/** More files of `assets/` to precache, such as fonts: the app's regex. */\n\tprecacheAssets?: RegExp;\n\t/** `true` by default. */\n\tminify?: boolean;\n}\n\nexport interface WorkerBuild {\n\t/** The absolute path of the worker written. */\n\tfile: string;\n\tprecache: PrecacheEntry[];\n\t/** The precached files' size, before compression. */\n\tprecacheBytes: number;\n\t/** The worker's own size. */\n\tbytes: number;\n}\n\n/** Not `requireBun` of `vite/`: `/pwa/build` imports Node's built-ins only. */\nexport function assertBun(\n\tonBun = (globalThis as { Bun?: unknown }).Bun !== undefined,\n): void {\n\tif (onBun) return;\n\tthrow new Error(\n\t\t'buildWorker() runs on Bun: it is running on Node. Run it with bun, or run react-router build with bun --bun.',\n\t);\n}\n\n/**\n * The file a root-relative URL names inside `client`. It fails closed: a URL\n * that is absolute, protocol-relative, not rooted at `/`, or that resolves to\n * `client` itself or outside it, is refused.\n */\nfunction urlInClient(client: string, url: string): string {\n\tconst path = join(client, url);\n\tif (\n\t\t!url.startsWith('/') ||\n\t\t/^[a-z][a-z0-9+.-]*:|^\\/\\//i.test(url) ||\n\t\t!path.startsWith(client + sep) ||\n\t\tpath.endsWith(sep)\n\t) {\n\t\tthrow new Error(`buildWorker(): ${url} is outside ${client}.`);\n\t}\n\treturn path;\n}\n\n/**\n * Bundles the worker (Workbox included) into the client build, after\n * `react-router build`, with the precache list written in: the offline page\n * by its content, every route's code and `precacheAssets`. A new build\n * changes the list, so the worker's bytes, so the browser installs it.\n * Runs on Bun; the only imports of this module are Node's built-ins.\n */\nexport async function buildWorker(\n\toptions: BuildWorkerOptions,\n): Promise<WorkerBuild> {\n\tassertBun();\n\tconst root = resolve(options.root ?? process.cwd());\n\tconst client = resolve(root, options.client ?? 'build/client');\n\tconst source = resolve(root, options.file);\n\tconst workerUrl = options.contract?.serviceWorkerUrl ?? SERVICE_WORKER_URL;\n\tconst offlineUrl = options.contract?.offlineUrl ?? OFFLINE_URL;\n\tif (!existsSync(source)) {\n\t\tthrow new Error(`buildWorker(): ${options.file} does not exist.`);\n\t}\n\tconst assets = join(client, 'assets');\n\tconst files = await readdir(assets).catch(() => []);\n\tconst manifest = browserManifestFile(files);\n\tlet offline: PrecacheEntry | undefined;\n\tif (options.offline !== false) {\n\t\tconst page = urlInClient(client, offlineUrl);\n\t\tif (!existsSync(page)) {\n\t\t\tthrow new Error(\n\t\t\t\t`buildWorker(): ${options.client ?? 'build/client'}${offlineUrl} does not exist. Add public${offlineUrl}, or pass offline: false (\\`worker: { offline: false }\\` in alxia()), or pass the app's contract (\\`worker: { contract }\\` in alxia()).`,\n\t\t\t);\n\t\t}\n\t\toffline = { url: offlineUrl, revision: revisionOf(await readFile(page)) };\n\t}\n\tconst precache = workerPrecache({\n\t\tmanifestSource: await readFile(join(assets, manifest), 'utf8'),\n\t\tassetFiles: files,\n\t\toffline,\n\t\tinclude: options.precacheAssets,\n\t});\n\tconst out = urlInClient(client, workerUrl);\n\tconst result = await Bun.build({\n\t\tentrypoints: [source],\n\t\toutdir: dirname(out),\n\t\tnaming: basename(out),\n\t\ttarget: 'browser',\n\t\tformat: 'iife',\n\t\tminify: options.minify ?? true,\n\t\tdefine: {\n\t\t\t// Workbox's production build: no logging, no dev assertions.\n\t\t\t'process.env.NODE_ENV': '\"production\"',\n\t\t\t[PRECACHE_DEFINE]: JSON.stringify(precache),\n\t\t},\n\t}).catch((error: unknown) => {\n\t\tconst detail =\n\t\t\terror instanceof AggregateError\n\t\t\t\t? error.errors.map(String).join('\\n')\n\t\t\t\t: String(error);\n\t\tthrow new Error(`buildWorker(): Bun.build failed:\\n${detail}`);\n\t});\n\tif (!result.success) {\n\t\tthrow new Error(\n\t\t\t`buildWorker(): Bun.build failed:\\n${result.logs.map(String).join('\\n')}`,\n\t\t);\n\t}\n\tlet precacheBytes = 0;\n\tfor (const { url } of precache) {\n\t\tprecacheBytes += (await stat(join(client, url))).size;\n\t}\n\treturn {\n\t\tfile: out,\n\t\tprecache,\n\t\tprecacheBytes,\n\t\tbytes: (await stat(out)).size,\n\t};\n}\n",
|
|
6
|
-
"import { createHash } from 'node:crypto';\nimport {\n\tassetPrecache,\n\ttype PrecacheEntry,\n\tparseBrowserManifest,\n\tprecacheList,\n} from '../model/precache-list';\n\n/** The one React Router browser manifest among the names in build/client/assets. */\nexport function browserManifestFile(files: readonly string[]): string {\n\tconst found = files.filter((file) => /^manifest-[\\w-]+\\.js$/.test(file));\n\tconst [only] = found;\n\tif (found.length !== 1 || only === undefined) {\n\t\tthrow new Error(\n\t\t\t`buildWorker(): expected one React Router browser manifest, build/client/assets/manifest-*.js, found ${found.length}. Run react-router build first.`,\n\t\t);\n\t}\n\treturn only;\n}\n\n/** A file's revision: the first 16 hex characters of its sha256. */\nexport function revisionOf(bytes: Uint8Array): string {\n\treturn createHash('sha256').update(bytes).digest('hex').slice(0, 16);\n}\n\n/**\n * The worker's precache list: the offline page (revisioned by its content),\n * every route's code, then the asset files `include` matches. Each URL once,\n * the first kept.\n */\nexport function workerPrecache(input: {\n\tmanifestSource: string;\n\tassetFiles: readonly string[];\n\toffline?: PrecacheEntry | undefined;\n\tinclude?: RegExp | undefined;\n}): PrecacheEntry[] {\n\tconst all = [\n\t\t...(input.offline ? [input.offline] : []),\n\t\t...precacheList(parseBrowserManifest(input.manifestSource)),\n\t\t...(input.include ? assetPrecache(input.assetFiles, input.include) : []),\n\t];\n\tconst seen = new Set<string>();\n\treturn all.filter(({ url }) => !seen.has(url) && seen.add(url));\n}\n"
|
|
7
|
-
],
|
|
8
|
-
"mappings": ";;;;;;;;;;;;;;AAAA;AACA;AACA;;;ACFA;AASO,SAAS,mBAAmB,CAAC,OAAkC;AAAA,EACrE,MAAM,QAAQ,MAAM,OAAO,CAAC,SAAS,wBAAwB,KAAK,IAAI,CAAC;AAAA,EACvE,OAAO,QAAQ;AAAA,EACf,IAAI,MAAM,WAAW,KAAK,SAAS,WAAW;AAAA,IAC7C,MAAM,IAAI,MACT,uGAAuG,MAAM,uCAC9G;AAAA,EACD;AAAA,EACA,OAAO;AAAA;AAID,SAAS,UAAU,CAAC,OAA2B;AAAA,EACrD,OAAO,WAAW,QAAQ,EAAE,OAAO,KAAK,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,EAAE;AAAA;AAQ7D,SAAS,cAAc,CAAC,OAKX;AAAA,EACnB,MAAM,MAAM;AAAA,IACX,GAAI,MAAM,UAAU,CAAC,MAAM,OAAO,IAAI,CAAC;AAAA,IACvC,GAAG,cAAa,sBAAqB,MAAM,cAAc,CAAC;AAAA,IAC1D,GAAI,MAAM,UAAU,eAAc,MAAM,YAAY,MAAM,OAAO,IAAI,CAAC;AAAA,EACvE;AAAA,EACA,MAAM,OAAO,IAAI;AAAA,EACjB,OAAO,IAAI,OAAO,GAAG,UAAU,CAAC,KAAK,IAAI,GAAG,KAAK,KAAK,IAAI,GAAG,CAAC;AAAA;;;ADCxD,SAAS,SAAS,CACxB,QAAS,WAAiC,QAAQ,WAC3C;AAAA,EACP,IAAI;AAAA,IAAO;AAAA,EACX,MAAM,IAAI,MACT,8GACD;AAAA;A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