netjes 0.0.2 → 0.0.3

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 (148) hide show
  1. package/README.md +11 -11
  2. package/cli/agents.mjs +25 -2
  3. package/cli/commands.mjs +56 -6
  4. package/cli/help.mjs +7 -2
  5. package/cli/info.mjs +7 -2
  6. package/cli/scaffold.mjs +31 -4
  7. package/dist/actions.d.ts +7 -2
  8. package/dist/actions.d.ts.map +1 -1
  9. package/dist/actions.js +9 -3
  10. package/dist/actions.js.map +1 -1
  11. package/dist/client-entry.d.ts +1 -0
  12. package/dist/client-entry.d.ts.map +1 -1
  13. package/dist/client-entry.js +19 -2
  14. package/dist/client-entry.js.map +1 -1
  15. package/dist/deferred.d.ts +11 -0
  16. package/dist/deferred.d.ts.map +1 -1
  17. package/dist/deferred.js +15 -1
  18. package/dist/deferred.js.map +1 -1
  19. package/dist/document.d.ts.map +1 -1
  20. package/dist/document.js +10 -1
  21. package/dist/document.js.map +1 -1
  22. package/dist/errors.d.ts +7 -0
  23. package/dist/errors.d.ts.map +1 -0
  24. package/dist/errors.js +11 -0
  25. package/dist/errors.js.map +1 -0
  26. package/dist/form.d.ts +5 -5
  27. package/dist/form.d.ts.map +1 -1
  28. package/dist/form.js +5 -2
  29. package/dist/form.js.map +1 -1
  30. package/dist/href.d.ts +24 -3
  31. package/dist/href.d.ts.map +1 -1
  32. package/dist/href.js +117 -7
  33. package/dist/href.js.map +1 -1
  34. package/dist/image.d.ts +3 -3
  35. package/dist/image.d.ts.map +1 -1
  36. package/dist/image.js.map +1 -1
  37. package/dist/index.d.ts +2 -1
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +2 -1
  40. package/dist/index.js.map +1 -1
  41. package/dist/link.d.ts +15 -7
  42. package/dist/link.d.ts.map +1 -1
  43. package/dist/link.js +38 -7
  44. package/dist/link.js.map +1 -1
  45. package/dist/metadata.d.ts +8 -2
  46. package/dist/metadata.d.ts.map +1 -1
  47. package/dist/metadata.js +14 -5
  48. package/dist/metadata.js.map +1 -1
  49. package/dist/modules.d.ts +15 -1
  50. package/dist/modules.d.ts.map +1 -1
  51. package/dist/modules.js.map +1 -1
  52. package/dist/navigation-focus.d.ts +38 -0
  53. package/dist/navigation-focus.d.ts.map +1 -0
  54. package/dist/navigation-focus.js +71 -0
  55. package/dist/navigation-focus.js.map +1 -0
  56. package/dist/query.d.ts +5 -2
  57. package/dist/query.d.ts.map +1 -1
  58. package/dist/query.js +11 -8
  59. package/dist/query.js.map +1 -1
  60. package/dist/render-document.d.ts +60 -0
  61. package/dist/render-document.d.ts.map +1 -0
  62. package/dist/render-document.js +330 -0
  63. package/dist/render-document.js.map +1 -0
  64. package/dist/route-announcer.d.ts +18 -0
  65. package/dist/route-announcer.d.ts.map +1 -0
  66. package/dist/route-announcer.js +58 -0
  67. package/dist/route-announcer.js.map +1 -0
  68. package/dist/route-tree.d.ts +6 -2
  69. package/dist/route-tree.d.ts.map +1 -1
  70. package/dist/route-tree.js +17 -7
  71. package/dist/route-tree.js.map +1 -1
  72. package/dist/router.d.ts +28 -5
  73. package/dist/router.d.ts.map +1 -1
  74. package/dist/router.js +71 -26
  75. package/dist/router.js.map +1 -1
  76. package/dist/script.d.ts +28 -5
  77. package/dist/script.d.ts.map +1 -1
  78. package/dist/script.js +192 -21
  79. package/dist/script.js.map +1 -1
  80. package/dist/server-render.d.ts.map +1 -1
  81. package/dist/server-render.js +4 -1
  82. package/dist/server-render.js.map +1 -1
  83. package/dist/testing-vitest.d.ts +8 -0
  84. package/dist/testing-vitest.d.ts.map +1 -0
  85. package/dist/testing-vitest.js +26 -0
  86. package/dist/testing-vitest.js.map +1 -0
  87. package/dist/testing.d.ts +11 -1
  88. package/dist/testing.d.ts.map +1 -1
  89. package/dist/testing.js +17 -3
  90. package/dist/testing.js.map +1 -1
  91. package/dist/zod-jitless.d.ts +2 -0
  92. package/dist/zod-jitless.d.ts.map +1 -0
  93. package/dist/zod-jitless.js +4 -0
  94. package/dist/zod-jitless.js.map +1 -0
  95. package/package.json +1 -1
  96. package/sidecar/server.mjs +73 -6
  97. package/skills/netjes/SKILL.md +13 -6
  98. package/skills/netjes/references/caching-and-streaming.md +37 -4
  99. package/skills/netjes/references/data-and-actions.md +9 -5
  100. package/skills/netjes/references/deployment.md +7 -3
  101. package/skills/netjes/references/routing.md +18 -6
  102. package/skills/netjes/references/testing.md +23 -7
  103. package/src/actions.tsx +9 -3
  104. package/src/client-entry.tsx +20 -2
  105. package/src/deferred.ts +14 -1
  106. package/src/document.tsx +22 -3
  107. package/src/errors.ts +12 -0
  108. package/src/form.tsx +10 -7
  109. package/src/href.ts +123 -8
  110. package/src/image.tsx +3 -3
  111. package/src/index.ts +2 -1
  112. package/src/link.tsx +47 -13
  113. package/src/metadata.tsx +19 -6
  114. package/src/modules.ts +15 -2
  115. package/src/navigation-focus.ts +75 -0
  116. package/src/query.tsx +14 -8
  117. package/src/render-document.tsx +386 -0
  118. package/src/route-announcer.tsx +69 -0
  119. package/src/route-tree.tsx +17 -6
  120. package/src/router.tsx +116 -31
  121. package/src/script.tsx +214 -23
  122. package/src/server-render.tsx +4 -1
  123. package/src/testing-vitest.ts +37 -0
  124. package/src/testing.tsx +31 -5
  125. package/src/virtual.d.ts +2 -0
  126. package/src/zod-jitless.ts +15 -0
  127. package/template/.dockerignore +3 -0
  128. package/template/Dockerfile +11 -1
  129. package/template/README.md +11 -7
  130. package/template/_AGENTS.md +36 -8
  131. package/template/__NAME__.csproj +2 -0
  132. package/template/app/document.test.ts +29 -0
  133. package/template/app/error.tsx +3 -2
  134. package/template/app/layout.tsx +10 -1
  135. package/template/docker-compose.override.yml +4 -3
  136. package/template/docker-compose.prod.yml +2 -1
  137. package/template/e2e/home.spec.ts +32 -0
  138. package/template/generated/netjes.ts +43 -14
  139. package/template/package.json +4 -1
  140. package/template/playwright.config.ts +36 -0
  141. package/template/tests/__NAME__.Tests/AppFactory.cs +31 -0
  142. package/template/tests/__NAME__.Tests/HomePageTests.cs +55 -0
  143. package/template/tests/__NAME__.Tests/__NAME__.Tests.csproj +30 -0
  144. package/template/tsconfig.app.json +20 -0
  145. package/template/tsconfig.json +2 -17
  146. package/template/tsconfig.node.json +8 -0
  147. package/vite/plugin.d.ts +9 -1
  148. package/vite/plugin.mjs +17 -5
package/src/query.tsx CHANGED
@@ -11,14 +11,20 @@ export type QueryShellOptions = {
11
11
 
12
12
  const DEFAULTS: DefaultOptions = { queries: { staleTime: 60_000 } };
13
13
 
14
- /** The Netjes defaults with the app's options merged over them, as the built-in client and the test harness use. */
15
- export function mergeOptions(options: DefaultOptions | undefined): DefaultOptions {
16
- return {
17
- ...DEFAULTS,
18
- ...options,
19
- queries: { ...DEFAULTS.queries, ...options?.queries },
20
- mutations: { ...DEFAULTS.mutations, ...options?.mutations },
21
- };
14
+ /**
15
+ * The Netjes defaults with each layer of options merged over the ones before it, query and mutation options one by
16
+ * one: the built-in client merges the app's options, and the test harness more layers.
17
+ */
18
+ export function mergeOptions(...layers: ReadonlyArray<DefaultOptions | undefined>): DefaultOptions {
19
+ return [DEFAULTS, ...layers].reduce<DefaultOptions>(
20
+ (merged, layer) => ({
21
+ ...merged,
22
+ ...layer,
23
+ queries: { ...merged.queries, ...layer?.queries },
24
+ mutations: { ...merged.mutations, ...layer?.mutations },
25
+ }),
26
+ {},
27
+ );
22
28
  }
23
29
 
24
30
  /**
@@ -0,0 +1,386 @@
1
+ // renderDocument and inlineScriptHashes, which netjes/testing exports: a page's whole document, rendered from its
2
+ // props as the Node sidecar renders it for a crawler, and the hashes of the inline scripts in it. The server builds
3
+ // the payload the sidecar renders; documentPayload builds one here from the pages map and the test's options, by the
4
+ // server's rules for the route and the segments (RouteTable and PageRenderer in src/Netjes). The two are checked
5
+ // against the same cases, test/fixtures/segments/cases.json, so a change to either rule fails a suite until both agree.
6
+ import { htmlSafeJson } from './deferred.ts';
7
+ import type { InitialPayload, PageKind, Params, SegmentRef } from './payload.ts';
8
+
9
+ /** What {@link renderDocument} renders a page with: what the server would send with it. */
10
+ export type RenderDocumentOptions = {
11
+ /** The page's props, as its C# loader sends them. A Promise anywhere in them is a `Page.Defer` value. */
12
+ props?: Record<string, unknown>;
13
+ /** The route values, as `useParams()` returns them: a string per segment, an array per catch-all. Default none. */
14
+ params?: Params;
15
+ /** The page's URL, its path and query. Default `/`. */
16
+ url?: string;
17
+ /**
18
+ * The props of each layout's C# layout loader, by the layout's file, such as `app/blog/layout.tsx`. A Promise in
19
+ * them is a `Page.Defer` value. A layout that is not named here gets none.
20
+ */
21
+ layouts?: Record<string, Record<string, unknown>>;
22
+ /** What the server sends as the shared props (`UseSharedProps`). Default `null`. */
23
+ shared?: unknown;
24
+ /**
25
+ * The page's status. Default 200, or the status the server gives the file: 404 for a not-found file, 403 for a
26
+ * forbidden one, 401 for an unauthorized one and 500 for an error or global-error one.
27
+ */
28
+ status?: number;
29
+ /** A Content-Security-Policy nonce, which goes on every script and stylesheet, as for a policy with `{nonce}`. */
30
+ nonce?: string;
31
+ /** The `lang` of `<html>`. Default `en`, as `NetjesOptions.Lang`. */
32
+ lang?: string;
33
+ /** What `usePublicConfig()` reads, as the `Netjes:PublicConfig` section. */
34
+ publicConfig?: Record<string, unknown>;
35
+ /** The page files, keyed `/app/...` as `import.meta.glob` keys them. Default: the app's, from the `netjes()` plugin. */
36
+ modules?: Record<string, () => Promise<unknown>>;
37
+ /** Stops the render, which then rejects with the signal's reason: for a page that waits on a Promise that never settles. */
38
+ signal?: AbortSignal;
39
+ };
40
+
41
+ /** The options {@link documentPayload} reads, with any Promise in the props already a placeholder. */
42
+ type DocumentOptions = Omit<RenderDocumentOptions, 'modules' | 'signal'>;
43
+
44
+ /** The files renderDocument renders besides pages, with the kind and the status the server gives them. */
45
+ const BOUNDARIES = new Map<string, { kind: PageKind; status: number }>([
46
+ ['not-found', { kind: 'notFound', status: 404 }],
47
+ ['forbidden', { kind: 'forbidden', status: 403 }],
48
+ ['unauthorized', { kind: 'unauthorized', status: 401 }],
49
+ ['error', { kind: 'error', status: 500 }],
50
+ ['global-error', { kind: 'error', status: 500 }],
51
+ ]);
52
+
53
+ /** The files that make a folder a segment of the pages below it; the payload names the first four. */
54
+ const SEGMENT_FILES = ['layout', 'template', 'loading', 'error', 'not-found', 'forbidden', 'unauthorized'];
55
+
56
+ const PAGE_EXTENSION = /\.(?:tsx|jsx)$/i;
57
+ const isGroup = (folder: string) => folder.length > 2 && folder.startsWith('(') && folder.endsWith(')');
58
+ const isSlot = (folder: string) => folder.length > 1 && folder.startsWith('@');
59
+ const isPrivate = (folder: string) => folder.startsWith('_');
60
+ /** UTF-16 code unit order, as the server's ordinal order. */
61
+ const ordinal = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
62
+
63
+ /** "a", "a and b", "a, b and c". */
64
+ function list(items: readonly string[]): string {
65
+ return items.length < 2 ? (items[0] ?? '') : `${items.slice(0, -1).join(', ')} and ${items.at(-1) ?? ''}`;
66
+ }
67
+
68
+ /** A file in the app directory: the folders below the directory and the file's name without its extension; null for any other file. */
69
+ function parse(file: string, appDir: string): { folders: string[]; name: string } | null {
70
+ if (!file.startsWith(`${appDir}/`) || !PAGE_EXTENSION.test(file)) return null;
71
+ const folders = file.slice(appDir.length + 1).split('/');
72
+ const name = (folders.pop() ?? '').replace(PAGE_EXTENSION, '');
73
+ return { folders, name };
74
+ }
75
+
76
+ type AppFiles = {
77
+ /** Each folder's convention files by name, by its path below the app directory (`''` for the directory itself). */
78
+ folders: Map<string, Map<string, string>>;
79
+ /** The folders with parallel route slots, each with the first of its slots. */
80
+ slots: Map<string, string>;
81
+ };
82
+
83
+ /** The convention files the server routes: none in private folders, and the slots that pages and defaults make. */
84
+ function appFiles(files: readonly string[], appDir: string): AppFiles {
85
+ const folders = new Map<string, Map<string, string>>();
86
+ const slots = new Map<string, string>();
87
+ for (const file of [...files].sort(ordinal)) {
88
+ const parsed = parse(file, appDir);
89
+ if (!parsed || parsed.folders.some(isPrivate)) continue;
90
+ const slot = parsed.folders.findIndex(isSlot);
91
+ if (slot >= 0) {
92
+ const parent = parsed.folders.slice(0, slot).join('/');
93
+ if ((parsed.name === 'page' || parsed.name === 'default') && !slots.has(parent)) {
94
+ slots.set(parent, [appDir, ...parsed.folders.slice(0, slot + 1)].join('/'));
95
+ }
96
+ continue;
97
+ }
98
+ const folder = parsed.folders.join('/');
99
+ let conventions = folders.get(folder);
100
+ if (!conventions) folders.set(folder, (conventions = new Map()));
101
+ if (!conventions.has(parsed.name)) conventions.set(parsed.name, file);
102
+ }
103
+ return { folders, slots };
104
+ }
105
+
106
+ /**
107
+ * How many URL segments a layout's folders cover for these route values, as the server counts them: one per folder,
108
+ * none for a route group, and a catch-all as many as its value has.
109
+ */
110
+ function urlDepth(folders: readonly string[], params: Params): number {
111
+ let depth = 0;
112
+ for (const folder of folders.filter((name) => !isGroup(name))) {
113
+ if (!folder.startsWith('[...') && !folder.startsWith('[[...')) {
114
+ depth++;
115
+ continue;
116
+ }
117
+ const value = params[folder.replace(/^[[\]]+|[[\]]+$/g, '').slice(3)];
118
+ depth += (Array.isArray(value) ? value.join('/') : (value ?? '')).split('/').filter(Boolean).length;
119
+ }
120
+ return depth;
121
+ }
122
+
123
+ function slotError(page: string, where: string, slot: string): Error {
124
+ return new Error(
125
+ `netjes: renderDocument cannot render ${page}, which ${where} the parallel route slot ${slot}: the server chooses what a slot renders.`,
126
+ );
127
+ }
128
+
129
+ /**
130
+ * The folders above `folders` and the folder itself that are segments, outermost first, as the server sends them:
131
+ * each folder with a segment file, its layout's props from `layouts` and, for a layout, the URL depth it covers.
132
+ */
133
+ function segmentsFor(page: string, app: AppFiles, folders: readonly string[], appDir: string, options: DocumentOptions): SegmentRef[] {
134
+ const segments: SegmentRef[] = [];
135
+ for (let end = 0; end <= folders.length; end++) {
136
+ const path = folders.slice(0, end);
137
+ const folder = path.join('/');
138
+ const slot = app.slots.get(folder);
139
+ if (slot) throw slotError(page, 'renders under', slot);
140
+ const conventions = app.folders.get(folder);
141
+ if (!conventions || !SEGMENT_FILES.some((name) => conventions.has(name))) continue;
142
+ const segment: SegmentRef = { id: folder ? `${appDir}/${folder}` : appDir };
143
+ for (const name of ['layout', 'template', 'loading', 'error'] as const) {
144
+ const file = conventions.get(name);
145
+ if (file) segment[name] = file;
146
+ }
147
+ if (segment.layout) {
148
+ if (options.layouts && Object.hasOwn(options.layouts, segment.layout)) segment.props = options.layouts[segment.layout];
149
+ segment.depth = urlDepth(path, options.params ?? {});
150
+ }
151
+ segments.push(segment);
152
+ }
153
+ return segments;
154
+ }
155
+
156
+ /** Every file renderDocument could render from these: the pages and the boundary files, in ordinal order. */
157
+ function renderable(files: readonly string[], appDir: string): string[] {
158
+ return files
159
+ .filter((file) => {
160
+ const parsed = parse(file, appDir);
161
+ if (!parsed || parsed.folders.some((folder) => isPrivate(folder) || isSlot(folder))) return false;
162
+ return parsed.name === 'page' || (BOUNDARIES.has(parsed.name) && (parsed.name !== 'global-error' || parsed.folders.length === 0));
163
+ })
164
+ .sort(ordinal);
165
+ }
166
+
167
+ /**
168
+ * The payload the server sends with the document of `page`, a file of the pages map named without its leading slash,
169
+ * for the values in `options`: the route, kind, status and segments by the server's rules, and a build with no
170
+ * stylesheets or scripts. Throws for a file it cannot render: one not in `files`, a layout, or a page in a private
171
+ * folder or under a parallel route slot.
172
+ */
173
+ export function documentPayload(page: string, options: DocumentOptions, files: readonly string[], appDir: string): InitialPayload {
174
+ const paths = files.map((file) => file.replace(/^\//, ''));
175
+ if (!paths.includes(page)) {
176
+ const hint = page.startsWith('/') && paths.includes(page.slice(1))
177
+ ? `; name the file without the leading slash: ${page.slice(1)}.`
178
+ : `. The files it can render are ${list(renderable(paths, appDir))}.`;
179
+ throw new Error(`netjes: renderDocument has no ${page} in the pages map${hint}`);
180
+ }
181
+ const parsed = parse(page, appDir);
182
+ if (!parsed) throw new Error(`netjes: renderDocument cannot render ${page}, which is not in the app's directory, ${appDir}.`);
183
+ if (parsed.folders.some(isPrivate)) throw new Error(`netjes: renderDocument cannot render ${page}: a private folder is not routed.`);
184
+ const slot = parsed.folders.findIndex(isSlot);
185
+ if (slot >= 0) throw slotError(page, 'is in', [appDir, ...parsed.folders.slice(0, slot + 1)].join('/'));
186
+ const boundary = BOUNDARIES.get(parsed.name);
187
+ if ((parsed.name !== 'page' && !boundary) || (parsed.name === 'global-error' && parsed.folders.length > 0)) {
188
+ throw new Error(
189
+ `netjes: renderDocument renders a page or a not-found, error, forbidden, unauthorized or global-error file, not ${page}.`,
190
+ );
191
+ }
192
+
193
+ // The global error page renders without any layout, the others inside the segments down to their own folder.
194
+ const segments = parsed.name === 'global-error' ? [] : segmentsFor(page, appFiles(paths, appDir), parsed.folders, appDir, options);
195
+ for (const file of Object.keys(options.layouts ?? {})) {
196
+ if (!segments.some((segment) => segment.layout === file)) {
197
+ const layouts = segments.flatMap((segment) => (segment.layout ? [segment.layout] : []));
198
+ throw new Error(
199
+ `netjes: renderDocument has props for ${file}, which is not a layout of ${page}. ` +
200
+ (layouts.length > 0 ? `Its layouts are ${list(layouts)}.` : 'It has no layouts.'),
201
+ );
202
+ }
203
+ }
204
+ // An error boundary renders in place of the pages below its folder, so it is not wrapped in itself.
205
+ for (const segment of segments) if (segment.error === page) delete segment.error;
206
+
207
+ return {
208
+ kind: 'page',
209
+ route: parsed.name === 'page' ? `/${parsed.folders.filter((folder) => !isGroup(folder)).join('/')}` : null,
210
+ page,
211
+ ...(boundary ? { pageKind: boundary.kind } : {}),
212
+ segments,
213
+ props: options.props ?? {},
214
+ params: options.params ?? {},
215
+ shared: options.shared ?? null,
216
+ status: options.status ?? boundary?.status ?? 200,
217
+ url: options.url ?? '/',
218
+ version: 'test',
219
+ document: {
220
+ lang: options.lang ?? 'en',
221
+ assets: { stylesheets: [], modulePreloads: [], scripts: [] },
222
+ errorPage: null,
223
+ ...(options.publicConfig ? { publicConfig: options.publicConfig } : {}),
224
+ ...(options.nonce ? { nonce: options.nonce } : {}),
225
+ },
226
+ };
227
+ }
228
+
229
+ function isThenable(value: unknown): value is PromiseLike<unknown> {
230
+ if ((typeof value !== 'object' && typeof value !== 'function') || value === null) return false;
231
+ return typeof (value as { then?: unknown }).then === 'function';
232
+ }
233
+
234
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
235
+ if (typeof value !== 'object' || value === null) return false;
236
+ const prototype: unknown = Object.getPrototypeOf(value);
237
+ return prototype === Object.prototype || prototype === null;
238
+ }
239
+
240
+ /** A JSON value with each Promise in it, at any depth, replaced by a `Page.Defer` placeholder; `values` keeps the Promises by id. */
241
+ function withPlaceholders(value: unknown, values: Map<string, PromiseLike<unknown>>): unknown {
242
+ if (isThenable(value)) {
243
+ const id = `d${values.size}`;
244
+ values.set(id, value);
245
+ // Read once the document renders; until then a rejection is not an unhandled one.
246
+ Promise.resolve(value).catch(() => {});
247
+ return { $netjes: 'deferred', id };
248
+ }
249
+ if (Array.isArray(value)) return value.map((item: unknown) => withPlaceholders(item, values));
250
+ return isPlainObject(value) ? placeholdersIn(value, values) : value;
251
+ }
252
+
253
+ function placeholdersIn(props: Record<string, unknown>, values: Map<string, PromiseLike<unknown>>): Record<string, unknown> {
254
+ // Keys are defined, not assigned, so a "__proto__" key stays a key.
255
+ return Object.fromEntries(Object.entries(props).map(([key, item]) => [key, withPlaceholders(item, values)]));
256
+ }
257
+
258
+ async function text(stream: AsyncIterable<unknown>): Promise<string> {
259
+ const decoder = new TextDecoder();
260
+ let html = '';
261
+ for await (const chunk of stream) {
262
+ html += chunk instanceof Uint8Array ? decoder.decode(chunk, { stream: true }) : decoder.decode() + String(chunk);
263
+ }
264
+ return html + decoder.decode();
265
+ }
266
+
267
+ /**
268
+ * Renders a page's whole document, from `<!DOCTYPE html>` to `</html>`, as the Node sidecar renders it for a crawler:
269
+ * the page from `page`, a file of the pages map such as `app/blog/[slug]/page.tsx`, inside the layouts the server
270
+ * would wrap it in, with the head, Netjes's inline scripts and the payload. It waits for every Suspense boundary, and
271
+ * a Promise in the props or in a layout's props is a `Page.Defer` value: rendered in place once it resolves, left as its
272
+ * Suspense fallback when it rejects. The build's stylesheets and scripts, development styles and an antiforgery token
273
+ * are left out, and no C# runs: the props come from `options`. Runs in Vitest's node environment, with the `netjes()`
274
+ * plugin, which provides the pages map, the app's folder and the query shell, also when `modules` is given.
275
+ */
276
+ export async function renderDocument(page: string, options: RenderDocumentOptions = {}): Promise<string> {
277
+ const { modules, signal, props, layouts, ...rest } = options;
278
+ // Before the first await, so that a Promise that has failed already gets its handler before Node looks for one.
279
+ const values = new Map<string, PromiseLike<unknown>>();
280
+ const sent: DocumentOptions = {
281
+ ...rest,
282
+ props: placeholdersIn(props ?? {}, values),
283
+ ...(layouts
284
+ ? { layouts: Object.fromEntries(Object.entries(layouts).map(([file, layoutProps]) => [file, placeholdersIn(layoutProps, values)])) }
285
+ : {}),
286
+ };
287
+ // A form's server action, the query client and the router's first URL take their browser path where these exist.
288
+ if (typeof window !== 'undefined' || typeof document !== 'undefined') {
289
+ throw new Error(
290
+ 'netjes: renderDocument renders a page as the Node sidecar does, without a DOM. ' +
291
+ "Put '// @vitest-environment node' at the top of the test file.",
292
+ );
293
+ }
294
+ signal?.throwIfAborted();
295
+ const app = await import('virtual:netjes/pages');
296
+ const pages = modules ?? app.pages;
297
+ const payload = documentPayload(page, sent, Object.keys(pages), app.appDir);
298
+ // Loaded here, so that component tests, which import netjes/testing too, never load react-dom/server.
299
+ const { createServerRenderer } = await import('./server-render.tsx');
300
+ const stream = await createServerRenderer(pages).renderToStream(htmlSafeJson(payload), {
301
+ waitForAll: true,
302
+ deferred: (id) => values.get(id) ?? new Promise<never>(() => {}),
303
+ ...(signal ? { signal } : {}),
304
+ });
305
+ return text(stream);
306
+ }
307
+
308
+ /** JavaScript MIME type essences: a script element whose type is one of them, in any case, runs as a classic script. */
309
+ const JAVASCRIPT_TYPES = new Set([
310
+ 'application/ecmascript',
311
+ 'application/javascript',
312
+ 'application/x-ecmascript',
313
+ 'application/x-javascript',
314
+ 'text/ecmascript',
315
+ 'text/javascript',
316
+ 'text/javascript1.0',
317
+ 'text/javascript1.1',
318
+ 'text/javascript1.2',
319
+ 'text/javascript1.3',
320
+ 'text/javascript1.4',
321
+ 'text/javascript1.5',
322
+ 'text/jscript',
323
+ 'text/livescript',
324
+ 'text/x-ecmascript',
325
+ 'text/x-javascript',
326
+ ]);
327
+
328
+ /** The other script types whose inline text a browser checks against a policy's script sources. */
329
+ const OTHER_SCRIPT_TYPES = new Set(['module', 'importmap', 'speculationrules']);
330
+
331
+ /** A script element: its start tag's attributes (quoted values can hold a `>`) and its text, up to `</script`. */
332
+ const SCRIPT = /<script(?=[\s/>])((?:"[^"]*"|'[^']*'|[^'">])*)>([\s\S]*?)<\/script(?=[\s/>])[^>]*>/gi;
333
+ const ATTRIBUTE = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
334
+
335
+ const asciiLowerCase = (text: string) => text.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
336
+
337
+ function attributesOf(source: string): Map<string, string> {
338
+ const attributes = new Map<string, string>();
339
+ for (const [, name = '', double, single, bare] of source.matchAll(ATTRIBUTE)) {
340
+ const key = asciiLowerCase(name);
341
+ // As in HTML, the first of two attributes with one name counts.
342
+ if (!attributes.has(key)) attributes.set(key, double ?? single ?? bare ?? '');
343
+ }
344
+ return attributes;
345
+ }
346
+
347
+ /** Whether a browser runs an inline script element with these attributes, by HTML's rules for its type. */
348
+ function runs(attributes: Map<string, string>): boolean {
349
+ const type = attributes.get('type');
350
+ const language = attributes.get('language');
351
+ const typeString =
352
+ type === '' || (type === undefined && !language)
353
+ ? 'text/javascript'
354
+ : type === undefined
355
+ ? `text/${language ?? ''}`
356
+ : type.replace(/^[\t\n\f\r ]+|[\t\n\f\r ]+$/g, '');
357
+ const kind = asciiLowerCase(typeString);
358
+ if (JAVASCRIPT_TYPES.has(kind)) return !attributes.has('nomodule');
359
+ return OTHER_SCRIPT_TYPES.has(kind);
360
+ }
361
+
362
+ async function hashSource(script: string): Promise<string> {
363
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(script)));
364
+ let bytes = '';
365
+ for (const byte of digest) bytes += String.fromCharCode(byte);
366
+ return `'sha256-${btoa(bytes)}'`;
367
+ }
368
+
369
+ /**
370
+ * The hash-sources, `'sha256-…'` in their quotes, of the inline scripts in `html` that a browser runs and checks
371
+ * against a Content-Security-Policy's script sources: each script element without `src` whose type a browser runs
372
+ * (none, a JavaScript type, `module`, `importmap` or `speculationrules`), with text. Each hash is listed once, in the
373
+ * order of the first script with it. Data blocks such as the page payload (`application/json`) are left out.
374
+ */
375
+ export async function inlineScriptHashes(html: string): Promise<string[]> {
376
+ const scripts: string[] = [];
377
+ for (const [, tag = '', body = ''] of html.matchAll(SCRIPT)) {
378
+ const attributes = attributesOf(tag);
379
+ if (attributes.has('src') || !runs(attributes)) continue;
380
+ // The HTML parser turns each CR LF, and each CR on its own, into LF before the script sees its text.
381
+ const script = body.replace(/\r\n?/g, '\n');
382
+ // A browser checks an empty script against no policy, since it does not run it.
383
+ if (script !== '') scripts.push(script);
384
+ }
385
+ return [...new Set(await Promise.all(scripts.map(hashSource)))];
386
+ }
@@ -0,0 +1,69 @@
1
+ import { type CSSProperties, useEffect, useRef, useState, useSyncExternalStore } from 'react';
2
+
3
+ /**
4
+ * Out of sight and still read by screen readers. React sets these styles through the CSSOM on an element it creates
5
+ * in the browser, which a Content-Security-Policy without `'unsafe-inline'` in `style-src` allows.
6
+ */
7
+ const VISUALLY_HIDDEN: CSSProperties = {
8
+ position: 'absolute',
9
+ width: 1,
10
+ height: 1,
11
+ margin: -1,
12
+ padding: 0,
13
+ border: 0,
14
+ overflow: 'hidden',
15
+ clip: 'rect(0 0 0 0)',
16
+ clipPath: 'inset(50%)',
17
+ whiteSpace: 'nowrap',
18
+ };
19
+
20
+ const subscribe = () => () => {};
21
+ const inBrowser = () => true;
22
+ const onServer = () => false;
23
+
24
+ /** A segment as a person reads it, `café` rather than `caf%C3%A9`; one that does not decode stays as it is. */
25
+ function decodeSegment(segment: string): string {
26
+ try {
27
+ return decodeURIComponent(segment);
28
+ } catch {
29
+ return segment;
30
+ }
31
+ }
32
+
33
+ /** How a screen reader can name the page on screen: its title, else its first `h1`, else its path, decoded. */
34
+ function pageName(path: string): string {
35
+ return document.title.trim() || document.querySelector('h1')?.textContent?.trim() || path.split('/').map(decodeSegment).join('/');
36
+ }
37
+
38
+ type RouteAnnouncerProps = {
39
+ /** The page's path and query: a navigation that changes neither (a refresh, a fragment link) names no page. */
40
+ location: string;
41
+ /** The path without the base path, the name of a page with neither a title nor an `h1`. */
42
+ path: string;
43
+ };
44
+
45
+ /**
46
+ * A polite live region that names the page after a client navigation, as a screen reader names the page a document
47
+ * load opens. It renders in the browser only, after hydration, so the server's HTML has none. It has no role, which
48
+ * would make it one more `status` or `alert` for an app's tests to find. Its effect runs after the app's, as a later
49
+ * sibling of the pages, so it reads the title and headings the new page has set. The first run records the name of
50
+ * the page the document loaded with; a later one, for another path or query, puts the new page's name in the region
51
+ * when it differs from the name of the page before. An intercepted page keeps the title of the page under it, so it
52
+ * is not named.
53
+ */
54
+ export function RouteAnnouncer({ location, path }: RouteAnnouncerProps) {
55
+ const rendered = useSyncExternalStore(subscribe, inBrowser, onServer);
56
+ const [message, setMessage] = useState('');
57
+ const named = useRef<string | null>(null);
58
+ useEffect(() => {
59
+ const name = pageName(path);
60
+ if (named.current !== null && name !== named.current) setMessage(name);
61
+ named.current = name;
62
+ }, [location, path]);
63
+ if (!rendered) return null;
64
+ return (
65
+ <div aria-live="polite" aria-atomic="true" data-netjes-route-announcer="" style={VISUALLY_HIDDEN}>
66
+ {message}
67
+ </div>
68
+ );
69
+ }
@@ -1,4 +1,5 @@
1
1
  import { Component, type ReactElement, type ReactNode, Suspense, createContext } from 'react';
2
+ import { withheldError } from './errors.ts';
2
3
  import { type Metadata, MetadataTags, resolveMetadata } from './metadata.tsx';
3
4
  import type { ErrorPageProps, LoadedSegment, RouteModules } from './modules.ts';
4
5
  import type { PageKind, Params, SegmentRef } from './payload.ts';
@@ -17,6 +18,8 @@ type RouteTreeProps = {
17
18
  pageKey: string;
18
19
  /** What `reset` does on an error page the server chose: load the page again. */
19
20
  retry?: () => void;
21
+ /** The error an error page (`pageKind` error) gets in place of the one the server's props describe: one caught here. */
22
+ error?: ErrorPageProps['error'];
20
23
  /** Metadata from the C# loader. */
21
24
  metadata?: Metadata | undefined;
22
25
  };
@@ -53,15 +56,23 @@ export class ErrorBoundary extends Component<BoundaryProps, { error: unknown; fa
53
56
  }
54
57
  }
55
58
 
56
- function asError(error: unknown): Error {
57
- return error instanceof Error ? error : new Error(typeof error === 'string' ? error : 'Something went wrong');
59
+ /** What a boundary caught, as the Error `error.tsx` gets: an Error as it is, a string as its message, else a stand-in. */
60
+ export function asError(error: unknown): ErrorPageProps['error'] {
61
+ if (error instanceof Error) return error;
62
+ return typeof error === 'string' ? new Error(error) : withheldError();
58
63
  }
59
64
 
60
- /** The error the server reported (props of the error page it rendered), as an Error for `error.tsx`. */
65
+ /**
66
+ * The error the server reported (props of the error page it rendered), as an Error for `error.tsx`: marked withheld
67
+ * when the server says its message stands in for the exception's, and with the server's stack or none, never the
68
+ * stack of the code here that built it.
69
+ */
61
70
  function serverError(props: Record<string, unknown>): ErrorPageProps['error'] {
62
71
  const error: ErrorPageProps['error'] = new Error(typeof props.message === 'string' ? props.message : 'Something went wrong');
63
72
  if (typeof props.status === 'number') error.status = props.status;
64
- if (typeof props.stack === 'string') error.stack = props.stack;
73
+ if (props.withheld === true) error.withheld = true;
74
+ // Defined rather than assigned, as an own property: Firefox keeps the stack in an accessor on Error.prototype.
75
+ Object.defineProperty(error, 'stack', { value: typeof props.stack === 'string' ? props.stack : undefined, writable: true, configurable: true });
65
76
  return error;
66
77
  }
67
78
 
@@ -70,9 +81,9 @@ function serverError(props: Record<string, unknown>): ErrorPageProps['error'] {
70
81
  * layout > template > error boundary > Suspense (loading) > the next segment or the page. Layouts keep their state
71
82
  * while the page underneath changes; templates remount.
72
83
  */
73
- export function RouteTree({ modules, segments = [], props, params, status, pageKind, pageKey, retry, metadata }: RouteTreeProps): ReactElement {
84
+ export function RouteTree({ modules, segments = [], props, params, status, pageKind, pageKey, retry, metadata, error }: RouteTreeProps): ReactElement {
74
85
  const Page = modules.page;
75
- const pageProps = pageKind === 'error' ? { ...props, error: serverError(props), reset: retry ?? (() => {}) } : props;
86
+ const pageProps = pageKind === 'error' ? { ...props, error: error ?? serverError(props), reset: retry ?? (() => {}) } : props;
76
87
  let element: ReactElement = Page ? <Page key={pageKey} {...pageProps} /> : <BuiltInPage key={pageKey} status={status} props={props} />;
77
88
  for (let i = modules.segments.length - 1; i >= 0; i--) {
78
89
  const { Layout, Template, Loading, Error: SegmentError, slots } = modules.segments[i]!;