@drupflare/spool 0.4.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/README.md +206 -1756
  2. package/dist/angular/index.d.ts +13 -0
  3. package/dist/angular/index.js +25 -0
  4. package/dist/angular/pages.d.ts +28 -0
  5. package/dist/angular/pages.js +85 -0
  6. package/dist/cdn/client.js +1 -1
  7. package/dist/cdn/location.d.ts +6 -0
  8. package/dist/cdn/location.js +8 -0
  9. package/dist/cdn/manifest.json +7 -7
  10. package/dist/cdn/spool-sw.js +1 -1
  11. package/dist/client/bootstrap.d.ts +57 -0
  12. package/dist/client/bootstrap.js +307 -0
  13. package/dist/client/contact.d.ts +24 -0
  14. package/dist/client/contact.js +66 -0
  15. package/dist/client/declared.d.ts +23 -0
  16. package/dist/client/declared.js +68 -0
  17. package/dist/client/entry.js +91 -2
  18. package/dist/client/gate.d.ts +1 -0
  19. package/dist/client/gate.js +148 -0
  20. package/dist/client/index.d.ts +25 -0
  21. package/dist/client/index.js +1 -0
  22. package/dist/client/live.d.ts +66 -0
  23. package/dist/client/live.js +225 -0
  24. package/dist/client/navigate-entry.d.ts +1 -0
  25. package/dist/client/navigate-entry.js +4 -0
  26. package/dist/client/navigate.d.ts +54 -0
  27. package/dist/client/navigate.js +272 -0
  28. package/dist/client/persist.d.ts +2 -0
  29. package/dist/client/persist.js +9 -0
  30. package/dist/client/register.d.ts +11 -1
  31. package/dist/client/register.js +19 -8
  32. package/dist/express/index.d.ts +11 -0
  33. package/dist/express/index.js +209 -0
  34. package/dist/hono/index.d.ts +19 -0
  35. package/dist/hono/index.js +49 -0
  36. package/dist/next/index.d.ts +33 -0
  37. package/dist/next/index.js +41 -0
  38. package/dist/next/pages.d.ts +22 -0
  39. package/dist/next/pages.js +39 -0
  40. package/dist/node/listener.d.ts +3 -0
  41. package/dist/node/listener.js +57 -2
  42. package/dist/nuxt/index.d.ts +22 -0
  43. package/dist/nuxt/index.js +104 -0
  44. package/dist/nuxt/pages.d.ts +26 -0
  45. package/dist/nuxt/pages.js +48 -0
  46. package/dist/nuxt/runtime/index.d.ts +24 -0
  47. package/dist/nuxt/runtime/index.js +58 -0
  48. package/dist/plugins/coverage.d.ts +14 -0
  49. package/dist/plugins/coverage.js +27 -0
  50. package/dist/plugins/mode.d.ts +19 -0
  51. package/dist/plugins/mode.js +20 -0
  52. package/dist/plugins/path.d.ts +16 -0
  53. package/dist/plugins/path.js +139 -0
  54. package/dist/plugins/report.d.ts +22 -0
  55. package/dist/plugins/report.js +18 -0
  56. package/dist/plugins/routes.d.ts +38 -0
  57. package/dist/plugins/routes.js +52 -0
  58. package/dist/plugins/static.d.ts +42 -0
  59. package/dist/plugins/static.js +97 -0
  60. package/dist/protocol/bundle.d.ts +111 -0
  61. package/dist/protocol/bundle.js +428 -0
  62. package/dist/protocol/config.d.ts +65 -1
  63. package/dist/protocol/config.js +28 -0
  64. package/dist/protocol/dataset.d.ts +6 -0
  65. package/dist/protocol/dataset.js +6 -0
  66. package/dist/protocol/envelope.d.ts +33 -1
  67. package/dist/protocol/envelope.js +15 -1
  68. package/dist/protocol/errors.d.ts +1 -1
  69. package/dist/protocol/index-rows.d.ts +22 -0
  70. package/dist/protocol/index-rows.js +53 -0
  71. package/dist/protocol/index.d.ts +2 -0
  72. package/dist/protocol/index.js +2 -0
  73. package/dist/protocol/normalise.d.ts +4 -4
  74. package/dist/protocol/normalise.js +9 -5
  75. package/dist/protocol/ring.d.ts +58 -0
  76. package/dist/protocol/ring.js +6 -0
  77. package/dist/protocol/route.d.ts +57 -11
  78. package/dist/protocol/route.js +95 -3
  79. package/dist/protocol/tag.d.ts +22 -2
  80. package/dist/protocol/tag.js +25 -4
  81. package/dist/protocol/view.d.ts +2 -0
  82. package/dist/protocol/view.js +8 -2
  83. package/dist/protocol/views.d.ts +6 -0
  84. package/dist/protocol/views.js +15 -0
  85. package/dist/protocol/write.d.ts +92 -4
  86. package/dist/protocol/write.js +251 -9
  87. package/dist/proxy/eligible.d.ts +22 -1
  88. package/dist/proxy/eligible.js +62 -15
  89. package/dist/proxy/proxy.js +28 -18
  90. package/dist/react-router/index.d.ts +20 -0
  91. package/dist/react-router/index.js +60 -0
  92. package/dist/react-router/pages.d.ts +34 -0
  93. package/dist/react-router/pages.js +83 -0
  94. package/dist/report/demand.d.ts +49 -0
  95. package/dist/report/demand.js +60 -0
  96. package/dist/report/economics.d.ts +55 -0
  97. package/dist/report/economics.js +189 -0
  98. package/dist/report/headline.d.ts +158 -0
  99. package/dist/report/headline.js +473 -0
  100. package/dist/report/index.d.ts +2 -0
  101. package/dist/report/index.js +2 -0
  102. package/dist/report/inputs.d.ts +79 -0
  103. package/dist/report/inputs.js +115 -0
  104. package/dist/report/measurement.d.ts +1 -1
  105. package/dist/report/measurement.js +5 -1
  106. package/dist/report/traffic.d.ts +8 -0
  107. package/dist/report/traffic.js +7 -0
  108. package/dist/server/bundle.d.ts +55 -0
  109. package/dist/server/bundle.js +172 -0
  110. package/dist/server/dataset.d.ts +8 -2
  111. package/dist/server/dataset.js +51 -4
  112. package/dist/server/embedded.d.ts +7 -3
  113. package/dist/server/embedded.js +7 -3
  114. package/dist/server/index.d.ts +5 -1
  115. package/dist/server/index.js +5 -1
  116. package/dist/server/live-sockets.d.ts +54 -0
  117. package/dist/server/live-sockets.js +131 -0
  118. package/dist/server/live.d.ts +146 -0
  119. package/dist/server/live.js +228 -0
  120. package/dist/server/ring.d.ts +77 -0
  121. package/dist/server/ring.js +311 -0
  122. package/dist/server/spool.d.ts +139 -4
  123. package/dist/server/spool.js +457 -28
  124. package/dist/server/static.d.ts +42 -0
  125. package/dist/server/static.js +29 -0
  126. package/dist/server/stub.d.ts +43 -5
  127. package/dist/server/stub.js +126 -8
  128. package/dist/server/write.d.ts +23 -1
  129. package/dist/server/write.js +96 -0
  130. package/dist/stores/durable-object.d.ts +46 -0
  131. package/dist/stores/durable-object.js +114 -0
  132. package/dist/sw/analytics.d.ts +1 -1
  133. package/dist/sw/analytics.js +2 -2
  134. package/dist/sw/coverage.d.ts +6 -0
  135. package/dist/sw/coverage.js +34 -0
  136. package/dist/sw/family.d.ts +15 -0
  137. package/dist/sw/family.js +48 -0
  138. package/dist/sw/idb.d.ts +2 -0
  139. package/dist/sw/idb.js +2 -2
  140. package/dist/sw/index.d.ts +2 -0
  141. package/dist/sw/index.js +1 -0
  142. package/dist/sw/pack/store.d.ts +128 -0
  143. package/dist/sw/pack/store.js +737 -0
  144. package/dist/sw/policy.d.ts +2 -0
  145. package/dist/sw/policy.js +11 -0
  146. package/dist/sw/probe.d.ts +16 -0
  147. package/dist/sw/probe.js +25 -0
  148. package/dist/sw/router.d.ts +3 -2
  149. package/dist/sw/router.js +15 -2
  150. package/dist/sw/runtime.d.ts +48 -1
  151. package/dist/sw/runtime.js +548 -68
  152. package/dist/sw/scheduler.d.ts +6 -1
  153. package/dist/sw/scheduler.js +22 -5
  154. package/dist/sw/write.d.ts +41 -1
  155. package/dist/sw/write.js +188 -5
  156. package/dist/version.d.ts +1 -1
  157. package/dist/version.js +1 -2
  158. package/dist/vite/index.d.ts +26 -0
  159. package/dist/vite/index.js +66 -0
  160. package/dist/vue/index.d.ts +36 -0
  161. package/dist/vue/index.js +53 -0
  162. package/package.json +64 -4
@@ -0,0 +1,33 @@
1
+ import type { Spool } from '../server/spool.js';
2
+ export { nextPages } from './pages.js';
3
+ export type { NextBuildInput, NextPageRegistration } from './pages.js';
4
+ /** the file the adapter writes into Next's dist directory; the app reads it when it starts */
5
+ export declare const SPOOL_PAGES_FILE = "spool-pages.json";
6
+ export type BuildContext = {
7
+ distDir: string;
8
+ config: {
9
+ cacheComponents?: boolean;
10
+ };
11
+ outputs: {
12
+ appPages: Array<{
13
+ pathname: string;
14
+ }>;
15
+ prerenders: Array<{
16
+ pathname: string;
17
+ }>;
18
+ };
19
+ };
20
+ /**
21
+ * The Next adapter. Point `adapterPath` in `next.config` at this subpath; after `next build` it
22
+ * writes the page registrations to `SPOOL_PAGES_FILE` and prints the report. Next runs no adapter
23
+ * in `next dev`, so the report is a build report and lists no uncovered GETs.
24
+ */
25
+ declare const _default: {
26
+ name: string;
27
+ onBuildComplete(ctx: BuildContext): void;
28
+ };
29
+ export default _default;
30
+ /** the page runtime script tag, for the app layout; spool adds it to a page at most once */
31
+ export declare function spoolTag(spool: Spool): string;
32
+ /** a route handler for `/spool-sw.js` and `/.spool/**`; any other request it sees gets a 404 */
33
+ export declare function spoolRouteHandler(spool: Spool): (request: Request) => Promise<Response>;
@@ -0,0 +1,41 @@
1
+ import { writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { formatDevReport } from '../plugins/report.js';
4
+ import { nextPages } from './pages.js';
5
+ export { nextPages } from './pages.js';
6
+ /** the file the adapter writes into Next's dist directory; the app reads it when it starts */
7
+ export const SPOOL_PAGES_FILE = 'spool-pages.json';
8
+ /**
9
+ * The Next adapter. Point `adapterPath` in `next.config` at this subpath; after `next build` it
10
+ * writes the page registrations to `SPOOL_PAGES_FILE` and prints the report. Next runs no adapter
11
+ * in `next dev`, so the report is a build report and lists no uncovered GETs.
12
+ */
13
+ export default {
14
+ name: '@drupflare/spool/next',
15
+ onBuildComplete(ctx) {
16
+ // next also lists each page's rsc payload and its own /_ routes, which are not pages
17
+ const isPage = (pathname) => !pathname.endsWith('.rsc') && !pathname.startsWith('/_');
18
+ const pages = nextPages({
19
+ pages: ctx.outputs.appPages.map((output) => output.pathname).filter(isPage),
20
+ prerendered: ctx.outputs.prerenders.map((output) => output.pathname).filter(isPage),
21
+ cacheComponents: ctx.config.cacheComponents === true
22
+ });
23
+ writeFileSync(join(ctx.distDir, SPOOL_PAGES_FILE), JSON.stringify(pages));
24
+ console.info(formatDevReport({
25
+ registered: pages.flatMap((page) => page.pattern && page.register !== 'network'
26
+ ? [{ pattern: page.pattern, register: page.register, maxAge: page.maxAge }]
27
+ : []),
28
+ network: pages
29
+ .filter((page) => page.register === 'network')
30
+ .map((page) => ({ path: page.path, reason: page.reason }))
31
+ }));
32
+ }
33
+ };
34
+ /** the page runtime script tag, for the app layout; spool adds it to a page at most once */
35
+ export function spoolTag(spool) {
36
+ return spool.config.clientTag;
37
+ }
38
+ /** a route handler for `/spool-sw.js` and `/.spool/**`; any other request it sees gets a 404 */
39
+ export function spoolRouteHandler(spool) {
40
+ return (request) => spool.handle(request, () => new Response('not found', { status: 404 }));
41
+ }
@@ -0,0 +1,22 @@
1
+ import { type Registration } from '../plugins/mode.js';
2
+ /** what the Next build reports: the app page pathnames, and the concrete paths Next prerendered */
3
+ export type NextBuildInput = {
4
+ /** app page pathnames as the adapter gives them, such as `/articles/[id]` */
5
+ pages: readonly string[];
6
+ /** concrete pathnames Next prerendered, such as `/articles/1` */
7
+ prerendered: readonly string[];
8
+ /** the top-level `cacheComponents` config flag */
9
+ cacheComponents?: boolean;
10
+ };
11
+ /** how one page is registered; `pattern` is set only when the path converts */
12
+ export type NextPageRegistration = Registration & {
13
+ path: string;
14
+ pattern?: string;
15
+ /** the prerendered paths that match the pattern */
16
+ prerendered: string[];
17
+ };
18
+ /**
19
+ * Registers every app page of a Next build. A page with params becomes a family only when Next
20
+ * prerendered some of its params (`generateStaticParams`); the rest stay on the network.
21
+ */
22
+ export declare function nextPages(input: NextBuildInput): NextPageRegistration[];
@@ -0,0 +1,39 @@
1
+ import { registerMode } from '../plugins/mode.js';
2
+ import { toSpoolPattern } from '../plugins/path.js';
3
+ // next lists a dynamic page's fallback shell, such as `/blog/[slug]`, as a prerender; it is no param set
4
+ function matches(pattern, path) {
5
+ if (path.includes('['))
6
+ return false;
7
+ const want = pattern.split('/');
8
+ const got = path.split('/');
9
+ return (want.length === got.length &&
10
+ want.every((part, at) => (part.startsWith(':') ? got[at] !== '' : part === got[at])));
11
+ }
12
+ function registerPage(page, input) {
13
+ const converted = toSpoolPattern('next', page);
14
+ if (converted.kind === 'network') {
15
+ return { path: page, register: 'network', reason: converted.reason, prerendered: [] };
16
+ }
17
+ const { pattern } = converted;
18
+ const prerendered = input.prerendered.filter((path) => matches(pattern, path));
19
+ const mode = {
20
+ rendering: input.cacheComponents
21
+ ? 'streaming'
22
+ : prerendered.length > 0
23
+ ? 'prerender'
24
+ : 'server',
25
+ enumerable: !pattern.includes(':') || prerendered.length > 0
26
+ };
27
+ const registration = registerMode(mode);
28
+ if (registration.register === 'network' && !mode.enumerable && mode.rendering !== 'streaming') {
29
+ registration.reason = `params not enumerable: declare a dataset family for ${pattern}`;
30
+ }
31
+ return { path: page, pattern, ...registration, prerendered };
32
+ }
33
+ /**
34
+ * Registers every app page of a Next build. A page with params becomes a family only when Next
35
+ * prerendered some of its params (`generateStaticParams`); the rest stay on the network.
36
+ */
37
+ export function nextPages(input) {
38
+ return input.pages.map((page) => registerPage(page, input));
39
+ }
@@ -1,4 +1,7 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { StaticSink } from '../server/static.js';
3
+ /** a static sink that writes each path under `root`, creating folders as it goes */
4
+ export declare function fileStaticSink(root: string): StaticSink;
2
5
  /** a Fetch-style handler; return `undefined` to hand the request to the next Node middleware */
3
6
  export type FetchHandler = (request: Request) => Response | undefined | Promise<Response | undefined>;
4
7
  /** options for {@link toNodeListener} */
@@ -1,5 +1,19 @@
1
+ import { access, mkdir, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
1
3
  import { Readable } from 'node:stream';
2
- import { pipeline } from 'node:stream/promises';
4
+ /** a static sink that writes each path under `root`, creating folders as it goes */
5
+ export function fileStaticSink(root) {
6
+ return {
7
+ async put(path, bytes) {
8
+ const file = join(root, path);
9
+ await mkdir(dirname(file), { recursive: true });
10
+ await writeFile(file, bytes);
11
+ },
12
+ async has(path) {
13
+ return access(join(root, path)).then(() => true, () => false);
14
+ }
15
+ };
16
+ }
3
17
  /** the Fetch `Request` for a Node request */
4
18
  export function toRequest(req, res, options = {}) {
5
19
  const encrypted = req.socket.encrypted === true;
@@ -37,10 +51,51 @@ export async function writeResponse(res, response, head = false) {
37
51
  if (cookies.length > 0)
38
52
  res.setHeader('set-cookie', cookies);
39
53
  if (head || !response.body) {
54
+ void response.body?.cancel().catch(() => undefined);
40
55
  res.end();
41
56
  return;
42
57
  }
43
- await pipeline(Readable.fromWeb(response.body), res);
58
+ // pipeline attaches many close listeners to the reply; pipe with ended attaches few
59
+ const body = Readable.fromWeb(response.body);
60
+ // the reply only sees 'close' when the socket is destroyed, so the body's own error is kept for the caller
61
+ let failure;
62
+ body.on('error', (error) => {
63
+ failure = error;
64
+ res.destroy(error);
65
+ });
66
+ res.once('close', () => body.destroy());
67
+ body.pipe(res);
68
+ await ended(res).catch((error) => {
69
+ throw failure ?? error;
70
+ });
71
+ }
72
+ /**
73
+ * Settles when the reply finishes, fails or closes, and removes its own listeners. `stream.finished`
74
+ * keeps listeners on the response after it settles.
75
+ */
76
+ function ended(res) {
77
+ return new Promise((resolve, reject) => {
78
+ const detach = () => {
79
+ res.off('finish', onFinish);
80
+ res.off('error', onError);
81
+ res.off('close', onClose);
82
+ };
83
+ const onFinish = () => {
84
+ detach();
85
+ resolve();
86
+ };
87
+ const onError = (error) => {
88
+ detach();
89
+ reject(error);
90
+ };
91
+ const onClose = () => {
92
+ detach();
93
+ reject(new Error('the connection closed before the reply ended'));
94
+ };
95
+ res.on('finish', onFinish);
96
+ res.on('error', onError);
97
+ res.on('close', onClose);
98
+ });
44
99
  }
45
100
  /**
46
101
  * Bridges `node:http` to a Fetch handler, with no dependency. The result is also an Express
@@ -0,0 +1,22 @@
1
+ import { type StaticOption } from '../plugins/static.js';
2
+ export type { StaticBuildContext, StaticBuildOptions, StaticOption } from '../plugins/static.js';
3
+ /** what the module takes */
4
+ export type SpoolNuxtOptions = {
5
+ /** a path, relative to the project, to a module whose default export is a `Spool` */
6
+ spool: string;
7
+ /**
8
+ * Publishes the static tier into Nitro's public directory (`.output/public`) when a production
9
+ * build runs: the page runtime, the worker script, the packs and a `_headers` rule. On by
10
+ * default; `false` turns it off, and an object sets `policy`, `url` or a `spool`. The build loads
11
+ * the `spool` module in Node, so its stores must be reachable from the build machine.
12
+ */
13
+ static?: StaticOption;
14
+ };
15
+ /**
16
+ * A Nuxt module that serves spool from the Nitro server. It exposes the page registrations as
17
+ * `#spool/pages`, serves `/spool-sw.js` and `/.spool/**` from the `spool` module, and adds the page
18
+ * runtime tag to server-rendered HTML. The `spool` module imports `#spool/pages` to declare its routes.
19
+ * A production build also publishes the static tier into Nitro's public directory (see `static`).
20
+ */
21
+ declare const _default: import("@nuxt/schema").NuxtModule<SpoolNuxtOptions, SpoolNuxtOptions, false>;
22
+ export default _default;
@@ -0,0 +1,104 @@
1
+ import { addNitroPlugin, addServerHandler, addServerTemplate, addTemplate, defineNuxtModule, logger, resolvePath } from '@nuxt/kit';
2
+ import { mkdir, writeFile } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
4
+ import { join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { formatDevReport } from '../plugins/report.js';
7
+ import { publishStaticBuild } from '../plugins/static.js';
8
+ import { PATHS } from '../protocol/config.js';
9
+ import { flattenPages, registerPage } from './pages.js';
10
+ /**
11
+ * Loads the `spool` module the way Nitro will, in the build process. `#spool/pages` is a Nitro
12
+ * virtual module, so it is written to the build directory for the load; the project's aliases carry over.
13
+ */
14
+ async function loadSpool(entry, rootDir, buildDir, aliases, pages) {
15
+ const file = join(buildDir, 'spool', 'pages.mjs');
16
+ await mkdir(join(buildDir, 'spool'), { recursive: true });
17
+ await writeFile(file, `export const pages = ${JSON.stringify(pages)};\n`);
18
+ const jiti = createRequire(join(rootDir, 'package.json'))('jiti');
19
+ const loaded = await jiti
20
+ .createJiti(entry, {
21
+ alias: { ...aliases, '#spool/pages': file },
22
+ moduleCache: false,
23
+ interopDefault: true
24
+ })
25
+ .import(entry, { default: true });
26
+ const spool = loaded;
27
+ if (typeof spool?.publishStatic !== 'function') {
28
+ throw new Error(`${entry} has no default export that is a Spool`);
29
+ }
30
+ return spool;
31
+ }
32
+ /**
33
+ * A Nuxt module that serves spool from the Nitro server. It exposes the page registrations as
34
+ * `#spool/pages`, serves `/spool-sw.js` and `/.spool/**` from the `spool` module, and adds the page
35
+ * runtime tag to server-rendered HTML. The `spool` module imports `#spool/pages` to declare its routes.
36
+ * A production build also publishes the static tier into Nitro's public directory (see `static`).
37
+ */
38
+ export default defineNuxtModule({
39
+ meta: { name: '@drupflare/spool/nuxt', configKey: 'spool' },
40
+ defaults: { spool: '' },
41
+ async setup(options, nuxt) {
42
+ if (!options.spool) {
43
+ throw new Error('the spool option is required: a path to a module that exports a Spool');
44
+ }
45
+ const entry = await resolvePath(options.spool, { cwd: nuxt.options.rootDir });
46
+ const runtime = fileURLToPath(new URL('./runtime/index.js', import.meta.url));
47
+ let pages = [];
48
+ nuxt.hook('pages:resolved', (resolved) => {
49
+ pages = flattenPages(resolved).map(registerPage);
50
+ if (!nuxt.options.dev)
51
+ return;
52
+ logger.info(formatDevReport({
53
+ registered: pages.flatMap((page) => page.pattern && page.register !== 'network'
54
+ ? [
55
+ {
56
+ pattern: page.pattern,
57
+ register: page.register,
58
+ maxAge: page.maxAge
59
+ }
60
+ ]
61
+ : []),
62
+ network: pages
63
+ .filter((page) => page.register === 'network')
64
+ .map((page) => ({ path: page.path, reason: page.reason })),
65
+ uncovered: []
66
+ }));
67
+ });
68
+ nuxt.hook('nitro:build:public-assets', async (nitro) => {
69
+ if (nuxt.options.dev || options.static === false)
70
+ return;
71
+ await publishStaticBuild({
72
+ spool: await loadSpool(entry, nuxt.options.rootDir, nuxt.options.buildDir, nuxt.options.alias, pages),
73
+ option: options.static,
74
+ outDir: nitro.options.output.publicDir,
75
+ log: (line) => logger.info(line)
76
+ });
77
+ });
78
+ addServerTemplate({
79
+ filename: '#spool/entry',
80
+ getContents: () => `export { default } from ${JSON.stringify(entry)};\n`
81
+ });
82
+ addServerTemplate({
83
+ filename: '#spool/pages',
84
+ getContents: () => `export const pages = ${JSON.stringify(pages)};\n`
85
+ });
86
+ addServerTemplate({
87
+ filename: '#spool/handler',
88
+ getContents: () => `import spool from '#spool/entry';\n` +
89
+ `import { spoolHandler } from ${JSON.stringify(runtime)};\n` +
90
+ `export default spoolHandler(spool);\n`
91
+ });
92
+ // a Nitro plugin is a file path, so the plugin is written to the build directory
93
+ const plugin = addTemplate({
94
+ filename: 'spool/plugin.mjs',
95
+ write: true,
96
+ getContents: () => `import spool from '#spool/entry';\n` +
97
+ `import { spoolPlugin } from ${JSON.stringify(runtime)};\n` +
98
+ `export default spoolPlugin(spool);\n`
99
+ });
100
+ addServerHandler({ route: PATHS.worker, handler: '#spool/handler' });
101
+ addServerHandler({ route: '/.spool/**', handler: '#spool/handler' });
102
+ addNitroPlugin(plugin.dst);
103
+ }
104
+ });
@@ -0,0 +1,26 @@
1
+ import { type Registration } from '../plugins/mode.js';
2
+ /** the fields of a Nuxt page the registration reads */
3
+ export type NuxtPageInput = {
4
+ /** the vue-router path Nuxt emits, such as `/articles/:id()` */
5
+ path: string;
6
+ /** `client` renders in the browser; `server` and `all` render on the server */
7
+ mode?: 'client' | 'server' | 'all';
8
+ /** the page's route rules, from `defineRouteRules()` */
9
+ rules?: object;
10
+ };
11
+ /** a page with its nested children, as `pages:resolved` gives them */
12
+ export type NuxtPageTree = NuxtPageInput & {
13
+ children?: NuxtPageTree[];
14
+ };
15
+ /** how one page is registered; `pattern` is set only when the path converts */
16
+ export type PageRegistration = Registration & {
17
+ path: string;
18
+ pattern?: string;
19
+ };
20
+ /** every page of the tree, parents before children, with full paths */
21
+ export declare function flattenPages(pages: readonly NuxtPageTree[], parent?: string): NuxtPageInput[];
22
+ /**
23
+ * Registers one Nuxt page. A path that does not convert stays on the network; a page with params
24
+ * is not enumerable here, because the module cannot know the params its data has.
25
+ */
26
+ export declare function registerPage(page: NuxtPageInput): PageRegistration;
@@ -0,0 +1,48 @@
1
+ import { registerMode } from '../plugins/mode.js';
2
+ import { toSpoolPattern } from '../plugins/path.js';
3
+ function join(base, child) {
4
+ if (child.startsWith('/'))
5
+ return child;
6
+ if (child === '')
7
+ return base || '/';
8
+ return `${base.replace(/\/$/, '')}/${child}`;
9
+ }
10
+ /** every page of the tree, parents before children, with full paths */
11
+ export function flattenPages(pages, parent = '') {
12
+ return pages.flatMap((page) => {
13
+ const path = join(parent, page.path);
14
+ return [{ ...page, path }, ...flattenPages(page.children ?? [], path)];
15
+ });
16
+ }
17
+ function renderingOf(page, rules) {
18
+ if (page.mode === 'client' || rules.ssr === false)
19
+ return 'client';
20
+ if (rules.streaming === true)
21
+ return 'streaming';
22
+ if (rules.prerender === true)
23
+ return 'prerender';
24
+ return 'server';
25
+ }
26
+ /**
27
+ * Registers one Nuxt page. A path that does not convert stays on the network; a page with params
28
+ * is not enumerable here, because the module cannot know the params its data has.
29
+ */
30
+ export function registerPage(page) {
31
+ const converted = toSpoolPattern('nuxt', page.path);
32
+ if (converted.kind === 'network') {
33
+ return { path: page.path, register: 'network', reason: converted.reason };
34
+ }
35
+ const rules = (page.rules ?? {});
36
+ const mode = {
37
+ rendering: renderingOf(page, rules),
38
+ enumerable: !converted.pattern.includes(':')
39
+ };
40
+ const seconds = typeof rules.swr === 'number' ? rules.swr : rules.isr;
41
+ if (typeof seconds === 'number')
42
+ mode.revalidate = seconds;
43
+ const registration = registerMode(mode);
44
+ if (registration.register === 'network' && !mode.enumerable && mode.rendering !== 'streaming') {
45
+ registration.reason = `params not enumerable: declare a dataset family for ${converted.pattern}`;
46
+ }
47
+ return { path: page.path, pattern: converted.pattern, ...registration };
48
+ }
@@ -0,0 +1,24 @@
1
+ import { type H3Event } from 'h3';
2
+ import type { Spool } from '../../server/spool.js';
3
+ /** the Nitro handler for `/spool-sw.js` and `/.spool/**`, answered from `spool` */
4
+ export declare function spoolHandler(spool: Spool): import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<Response>>;
5
+ type RenderResponse = {
6
+ body?: unknown;
7
+ headers?: Record<string, string | string[]>;
8
+ statusCode?: number;
9
+ };
10
+ type NitroApp = {
11
+ hooks: {
12
+ hook(name: 'render:response', fn: (response: RenderResponse, context: {
13
+ event: H3Event;
14
+ }) => Promise<void>): unknown;
15
+ hook(name: 'request', fn: (event: H3Event) => void): unknown;
16
+ };
17
+ };
18
+ /**
19
+ * The Nitro plugin that decorates each server-rendered page with spool's envelope and tag. In
20
+ * development (`NODE_ENV` is not `production`) it also logs each fetch or XHR GET of this server that
21
+ * no data family covers.
22
+ */
23
+ export declare function spoolPlugin(spool: Spool): (nitroApp: NitroApp) => void;
24
+ export {};
@@ -0,0 +1,58 @@
1
+ import { defineEventHandler, toWebRequest } from 'h3';
2
+ import { devCoverage } from '../../plugins/coverage.js';
3
+ import { PATHS } from '../../protocol/config.js';
4
+ /** the Nitro handler for `/spool-sw.js` and `/.spool/**`, answered from `spool` */
5
+ export function spoolHandler(spool) {
6
+ return defineEventHandler(async (event) => {
7
+ const request = toWebRequest(event);
8
+ if (new URL(request.url).pathname === PATHS.worker && request.method === 'GET') {
9
+ return spool.stub(request);
10
+ }
11
+ return (await spool.respond(request)) ?? new Response('not found', { status: 404 });
12
+ });
13
+ }
14
+ /**
15
+ * The Nitro plugin that decorates each server-rendered page with spool's envelope and tag. In
16
+ * development (`NODE_ENV` is not `production`) it also logs each fetch or XHR GET of this server that
17
+ * no data family covers.
18
+ */
19
+ export function spoolPlugin(spool) {
20
+ return (nitroApp) => {
21
+ const env = globalThis
22
+ .process?.env;
23
+ if (env !== undefined && env['NODE_ENV'] !== 'production') {
24
+ const watch = devCoverage(spool.config.routes, (line) => console.info(line));
25
+ nitroApp.hooks.hook('request', (event) => {
26
+ const request = toWebRequest(event);
27
+ watch({
28
+ method: request.method,
29
+ url: request.url,
30
+ fetchDest: request.headers.get('sec-fetch-dest')
31
+ });
32
+ });
33
+ }
34
+ nitroApp.hooks.hook('render:response', async (response, { event }) => {
35
+ if (typeof response.body !== 'string')
36
+ return;
37
+ const headers = new Headers();
38
+ for (const [name, value] of Object.entries(response.headers ?? {})) {
39
+ headers.set(name, String(value));
40
+ }
41
+ const answer = new Response(response.body, {
42
+ status: response.statusCode ?? 200,
43
+ headers
44
+ });
45
+ const decorated = await spool.decorate(toWebRequest(event), answer);
46
+ const out = {};
47
+ for (const [name, value] of decorated.headers) {
48
+ if (name !== 'set-cookie' && name !== 'content-length')
49
+ out[name] = value;
50
+ }
51
+ const cookies = decorated.headers.getSetCookie();
52
+ if (cookies.length > 0)
53
+ out['set-cookie'] = cookies;
54
+ response.headers = out;
55
+ response.body = await decorated.text();
56
+ });
57
+ };
58
+ }
@@ -0,0 +1,14 @@
1
+ import type { SerializedRoute } from '../protocol/route.js';
2
+ /** one line of the development report for a GET that no data family covers */
3
+ export declare function uncoveredLine(path: string): string;
4
+ /**
5
+ * Watches the requests a development server receives and calls `print` once for each fetch or XHR
6
+ * GET that no data family in `families` covers. A navigation, a script, a stylesheet and an image
7
+ * are not page reads, so only `Sec-Fetch-Dest: empty` counts. The server sees its own origin only:
8
+ * a request to another origin never reaches it, so a cross-origin read is not reported here.
9
+ */
10
+ export declare function devCoverage(families: readonly SerializedRoute[], print: (line: string) => void): (request: {
11
+ method: string;
12
+ url: string;
13
+ fetchDest: string | null;
14
+ }) => void;
@@ -0,0 +1,27 @@
1
+ import { PATHS } from '../protocol/config.js';
2
+ import { coverageReport } from '../sw/coverage.js';
3
+ /** one line of the development report for a GET that no data family covers */
4
+ export function uncoveredLine(path) {
5
+ return `spool: uncovered GET ${path}`;
6
+ }
7
+ /**
8
+ * Watches the requests a development server receives and calls `print` once for each fetch or XHR
9
+ * GET that no data family in `families` covers. A navigation, a script, a stylesheet and an image
10
+ * are not page reads, so only `Sec-Fetch-Dest: empty` counts. The server sees its own origin only:
11
+ * a request to another origin never reaches it, so a cross-origin read is not reported here.
12
+ */
13
+ export function devCoverage(families, print) {
14
+ const seen = new Set();
15
+ return ({ method, url, fetchDest }) => {
16
+ if (method !== 'GET' || fetchDest !== 'empty')
17
+ return;
18
+ const parsed = new URL(url);
19
+ if (parsed.pathname === PATHS.worker || parsed.pathname.startsWith('/.spool'))
20
+ return;
21
+ const [uncovered] = coverageReport([{ method, url }], families, parsed.origin);
22
+ if (uncovered === undefined || seen.has(uncovered))
23
+ return;
24
+ seen.add(uncovered);
25
+ print(uncoveredLine(`${parsed.pathname}${parsed.search}`));
26
+ };
27
+ }
@@ -0,0 +1,19 @@
1
+ /** how a framework renders a route, as the plugin reads it */
2
+ export type RenderMode = {
3
+ /** `prerender` is built ahead, `server` per request, `client` in the browser, `streaming` as a stream */
4
+ rendering: 'prerender' | 'server' | 'client' | 'streaming';
5
+ /** every param set is known: no params, a declared dataset, or a params() enumerator */
6
+ enumerable: boolean;
7
+ /** seconds a revalidating route may serve stale; absent when the route does not revalidate */
8
+ revalidate?: number;
9
+ };
10
+ /** what a route becomes in spool; `template` is for the server-side adapters, not framework routes */
11
+ export type Register = 'family' | 'template' | 'shell' | 'network';
12
+ /** the registration of one route, with `maxAge` in seconds when it revalidates */
13
+ export type Registration = {
14
+ register: Register;
15
+ maxAge?: number;
16
+ reason: string;
17
+ };
18
+ /** maps a route's render mode to how spool registers it */
19
+ export declare function registerMode(mode: RenderMode): Registration;
@@ -0,0 +1,20 @@
1
+ /** maps a route's render mode to how spool registers it */
2
+ export function registerMode(mode) {
3
+ if (mode.rendering === 'streaming') {
4
+ return {
5
+ register: 'network',
6
+ reason: 'streaming or server components: payload not captured per param'
7
+ };
8
+ }
9
+ if (mode.rendering === 'client') {
10
+ return { register: 'shell', reason: 'client-only: app shell plus data routes' };
11
+ }
12
+ const rendered = mode.rendering === 'prerender' ? 'prerendered' : 'server-rendered';
13
+ if (!mode.enumerable) {
14
+ return { register: 'network', reason: `${rendered} without enumerable params` };
15
+ }
16
+ const reason = `${rendered} with enumerable params`;
17
+ return mode.revalidate === undefined
18
+ ? { register: 'family', reason }
19
+ : { register: 'family', maxAge: mode.revalidate, reason };
20
+ }
@@ -0,0 +1,16 @@
1
+ /** the framework path syntaxes the converter reads */
2
+ export type PathSyntax = 'vue-router' | 'nuxt' | 'react-router' | 'next' | 'angular';
3
+ /** a spool pattern, or the reason the path stays a network route */
4
+ export type Conversion = {
5
+ kind: 'pattern';
6
+ pattern: string;
7
+ } | {
8
+ kind: 'network';
9
+ reason: string;
10
+ };
11
+ /**
12
+ * Converts a framework route path to a spool pattern. A static segment and a single-segment
13
+ * parameter convert; anything else returns `network` with the reason, never a pattern that would
14
+ * match a different set of URLs. Angular paths may omit the leading slash.
15
+ */
16
+ export declare function toSpoolPattern(syntax: PathSyntax, path: string): Conversion;