@ultimat3/render 31.49.0 → 31.50.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/render",
3
- "version": "31.49.0",
3
+ "version": "31.50.0",
4
4
  "description": "The route primitive and the five render modes: static, isr, ssr, stream, spa.",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -52,12 +52,12 @@
52
52
  "test": "bun test"
53
53
  },
54
54
  "dependencies": {
55
- "@ultimat3/cache": "31.49.0",
56
- "@ultimat3/core": "31.49.0",
57
- "@ultimat3/http": "31.49.0",
58
- "@ultimat3/i18n": "31.49.0",
59
- "@ultimat3/schema": "31.49.0",
60
- "@ultimat3/seo": "31.49.0",
61
- "sass": "1.107.1"
55
+ "@ultimat3/cache": "31.50.0",
56
+ "@ultimat3/core": "31.50.0",
57
+ "@ultimat3/http": "31.50.0",
58
+ "@ultimat3/i18n": "31.50.0",
59
+ "@ultimat3/schema": "31.50.0",
60
+ "@ultimat3/seo": "31.50.0",
61
+ "sass": "1.108.1"
62
62
  }
63
63
  }
package/src/asset.ts CHANGED
@@ -107,7 +107,7 @@ export function asset(path: AssetPath): string {
107
107
  if (resolver === undefined) {
108
108
  throw new AssetMissingError(
109
109
  `asset(${renderCauseValue(path)}) ran with no site asset table installed — in a browser (an island), or in a test that never loaded the app`,
110
- 'asset(path) // in the page, the URL passed to the island as a prop; a unit test installs a table with setAssetResolver((path) => "/" + path)',
110
+ 'asset(path) // in the page, the URL passed to the island as a prop; a test run from the app root gets the app\'s table from @ultimat3/testing/preload, any other installs one with setAssetResolver((path) => "/" + path)',
111
111
  );
112
112
  }
113
113
  return resolver(path);
package/src/errors.ts CHANGED
@@ -54,7 +54,7 @@ export const RENDER_ERROR_TITLES: Readonly<Record<RenderErrorCode, string>> = {
54
54
  X_ASSET_MISSING: 'a page names a site asset the app does not have',
55
55
  X_ROUTE_POST_INVALID: "a page route's post binding cannot be mounted",
56
56
  X_ROUTE_NAVIGATION_INVALID:
57
- "a route's navigation is not 'prefetch', 'document', 'modal' or { modal: true, prefetch: 'intent' }, or its surface has no client navigation",
57
+ "a route's navigation is not 'prefetch', 'document', 'modal' or { modal: true, prefetch: 'intent' }, or is a mode other than 'document' on a surface with no client navigation",
58
58
  X_NAVIGATION_MODAL_PATH_INVALID:
59
59
  'openModal was given something that is not a path of this origin',
60
60
  };
@@ -209,7 +209,7 @@ export class RoutePostInvalidError extends UltimateError {
209
209
  /**
210
210
  * `defineRoute({ navigation })` that says nothing a process can honour: a value other than
211
211
  * `'prefetch'`, `'document'`, `'modal'` or `{ modal: true, prefetch: 'intent' }`, or — at boot — a
212
- * page whose surface has no client navigation.
212
+ * mode other than `'document'` on a page whose surface has no client navigation.
213
213
  */
214
214
  export class RouteNavigationInvalidError extends UltimateError {
215
215
  static readonly code = 'X_ROUTE_NAVIGATION_INVALID' as const;
@@ -217,7 +217,7 @@ export class RouteNavigationInvalidError extends UltimateError {
217
217
  super({
218
218
  code: RouteNavigationInvalidError.code,
219
219
  cause,
220
- fix: "defineRoute({ ..., navigation: 'prefetch' | 'document' | 'modal' | { modal: true, prefetch: 'intent' } }) on a page whose surface is listed in app.config.ts navigation.client, or remove the key",
220
+ fix: "defineRoute({ ..., navigation: 'prefetch' | 'document' | 'modal' | { modal: true, prefetch: 'intent' } }) on a page whose surface is listed in app.config.ts navigation.client — navigation: 'document' needs no router and boots on any surface — or remove the key",
221
221
  });
222
222
  }
223
223
  }
@@ -4,8 +4,9 @@
4
4
  *
5
5
  * The headers: purpose, the document's `<app>:<surface>`, its principal, its build on a GET.
6
6
  * `redirect: 'manual'` so no redirect is followed behind the router's back; `cache: 'no-cache'` so
7
- * the browser's HTTP cache never answers. The `Answer` is the page's text, or a non-page's bytes to
8
- * hand over (a prefetch's are dropped unread).
7
+ * the browser's HTTP cache never answers. The `Answer` is the page's text (a soft visit's streamed
8
+ * page: its shell, and the rest to read), or a non-page's bytes to hand over (a prefetch's are
9
+ * dropped unread).
9
10
  */
10
11
 
11
12
  import {
@@ -18,6 +19,7 @@ import {
18
19
  } from '@ultimat3/core/page';
19
20
  import type { NavigationCache } from './navigation-cache';
20
21
  import { NAVIGATION_META, type ResponseFacts, reusable } from './navigation-rules';
22
+ import { type PageRest, readShell } from './navigation-stream';
21
23
 
22
24
  /** One fetched answer, read once — a prefetch and the click after it share it. */
23
25
  export interface Answer {
@@ -28,6 +30,11 @@ export interface Answer {
28
30
  readonly contentType: string;
29
31
  readonly build: string | null;
30
32
  readonly html: string | null;
33
+ /**
34
+ * A soft visit's page that streams holes: `html` is its shell, and this the rest, read by the
35
+ * router once the shell is on screen. `null` for a page read whole (and every prefetch).
36
+ */
37
+ readonly rest: PageRest | null;
31
38
  readonly noStore: boolean;
32
39
  /** A non-page answer's bytes, kept to hand over — never for a prefetch. */
33
40
  readonly body: Blob | null;
@@ -68,7 +75,14 @@ export function fetchDocument(
68
75
  const contentType = response.headers.get('content-type') ?? '';
69
76
  const opaqueRedirect = response.type === 'opaqueredirect';
70
77
  const isHtml = /^\s*text\/html\b/i.test(contentType);
71
- const html = !opaqueRedirect && isHtml ? await response.text() : null;
78
+ // A prefetch is read whole: it is held for a click that may never come, and a held stream
79
+ // would keep its request open until its slowest hole closed.
80
+ const page =
81
+ opaqueRedirect || !isHtml
82
+ ? { html: null, rest: null }
83
+ : purpose === 'soft' && response.body !== null
84
+ ? await readShell(response.body)
85
+ : { html: await response.text(), rest: null };
72
86
  let body: Blob | null = null;
73
87
  if (!opaqueRedirect && !isHtml && response.status !== 204) {
74
88
  if (purpose === 'prefetch') await response.body?.cancel();
@@ -81,7 +95,8 @@ export function fetchDocument(
81
95
  location: location === null ? null : new URL(location, url).href,
82
96
  contentType,
83
97
  build: response.headers.get(CLIENT_BUILD_META),
84
- html,
98
+ html: page.html,
99
+ rest: page.rest,
85
100
  noStore: /\bno-store\b/i.test(response.headers.get('cache-control') ?? ''),
86
101
  body,
87
102
  disposition: response.headers.get('content-disposition') ?? '',
@@ -78,3 +78,42 @@ export function scrollAfter(win: Window, doc: Document, url: string, mode: Histo
78
78
  else if (target !== null) target.scrollIntoView({ behavior: 'instant' as ScrollBehavior });
79
79
  else to(0, 0);
80
80
  }
81
+
82
+ /**
83
+ * `url` loaded for real. One that differs from the page on screen only by its fragment is reloaded:
84
+ * `assign` there is a same-document fragment navigation, which scrolls and leaves the page as it is.
85
+ * An empty fragment (`/a#`) is one too, though `URL.hash` reads it as none. Another fragment is
86
+ * pushed first, as `assign` would: a reload of the address bar's own would land on that anchor.
87
+ */
88
+ export function loadForReal(win: Window, url: string): void {
89
+ const here = win.location.href;
90
+ if (url.includes('#') && withoutFragment(url) === withoutFragment(here)) {
91
+ if (url !== here) win.history.pushState(null, '', url);
92
+ win.location.reload();
93
+ } else win.location.assign(url);
94
+ }
95
+
96
+ /**
97
+ * The fragment's element, scrolled to once a hole brings it — when the swap found none to scroll to
98
+ * and the visitor has not moved since: `true` once there is nothing left to wait for. Back/Forward
99
+ * restored a saved offset, which a late element never overrides.
100
+ */
101
+ export function lateFragment(
102
+ win: Window,
103
+ doc: Document,
104
+ url: string,
105
+ mode: HistoryMode,
106
+ ): (() => boolean) | undefined {
107
+ const raw = new URL(url).hash.slice(1);
108
+ if (raw === '' || mode === 'none') return undefined;
109
+ const id = decodeSegment(raw) ?? raw;
110
+ if (doc.getElementById(id) !== null) return undefined;
111
+ const at = [win.scrollX, win.scrollY, win.location.hash] as const;
112
+ return () => {
113
+ if (win.scrollX !== at[0] || win.scrollY !== at[1] || win.location.hash !== at[2]) return true;
114
+ const target = doc.getElementById(id);
115
+ if (target === null) return false;
116
+ target.scrollIntoView({ behavior: 'instant' as ScrollBehavior });
117
+ return true;
118
+ };
119
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * A soft visit's page read as it arrives, so it paints before its slowest hole: the shell up to the
3
+ * server's first `STREAM_FLUSH_MARK`, then each hole's chunk as its mark lands, appended to the
4
+ * live body with its scripts run — the reveal a full load's parser runs. No mark: read whole.
5
+ */
6
+
7
+ import { runScripts } from './navigation-swap';
8
+ import { STREAM_FLUSH_MARK, STREAM_KEEPALIVE_CHUNK } from './stream-scripts';
9
+
10
+ /** `Node.ELEMENT_NODE`, without reading a global the router's tests do not have. */
11
+ const ELEMENT_NODE = 1;
12
+
13
+ /** What follows a streamed shell: whole chunks, until the document ends or is cancelled. */
14
+ export interface PageRest {
15
+ /** The next run of whole chunks; `null` once the document ended (its tail is dropped). */
16
+ next(): Promise<string | null>;
17
+ /** Stops reading: the request is cancelled, and the server aborts each open hole's signal. */
18
+ cancel(): void;
19
+ }
20
+
21
+ /** The page's markup up to the shell's end, and the rest when the page streams any. */
22
+ export interface PageHead {
23
+ readonly html: string;
24
+ readonly rest: PageRest | null;
25
+ }
26
+
27
+ export async function readShell(body: ReadableStream<Uint8Array>): Promise<PageHead> {
28
+ const reader = body.getReader();
29
+ const decoder = new TextDecoder();
30
+ let buffer = '';
31
+ for (;;) {
32
+ const { done, value } = await reader.read();
33
+ if (done) return { html: buffer + decoder.decode(), rest: null };
34
+ buffer += decoder.decode(value, { stream: true });
35
+ const end = buffer.indexOf(STREAM_FLUSH_MARK);
36
+ if (end === -1) continue;
37
+ const html = buffer.slice(0, end);
38
+ buffer = buffer.slice(end + STREAM_FLUSH_MARK.length);
39
+ return { html, rest: restOf(reader, decoder, buffer) };
40
+ }
41
+ }
42
+
43
+ function restOf(
44
+ reader: ReadableStreamDefaultReader<Uint8Array>,
45
+ decoder: TextDecoder,
46
+ start: string,
47
+ ): PageRest {
48
+ let buffer = withoutKeepAlives(start);
49
+ return {
50
+ async next() {
51
+ for (;;) {
52
+ const end = buffer.lastIndexOf(STREAM_FLUSH_MARK);
53
+ if (end !== -1) {
54
+ // Keep-alives between two chunks of one read never reach the page either.
55
+ const whole = buffer
56
+ .slice(0, end)
57
+ .split(STREAM_FLUSH_MARK)
58
+ .map(withoutKeepAlives)
59
+ .join(STREAM_FLUSH_MARK);
60
+ buffer = buffer.slice(end + STREAM_FLUSH_MARK.length);
61
+ return whole;
62
+ }
63
+ const { done, value } = await reader.read();
64
+ if (done) return null;
65
+ buffer = withoutKeepAlives(buffer + decoder.decode(value, { stream: true }));
66
+ }
67
+ },
68
+ cancel() {
69
+ // Settles once the request is torn down; a cancel that fails has nothing left to stop.
70
+ reader.cancel().catch(() => undefined);
71
+ },
72
+ };
73
+ }
74
+
75
+ /**
76
+ * The buffer with the keep-alive frames at its head dropped. The server writes one between two whole
77
+ * chunks every second a hole is open, so this is the only place one can stand: kept, a hole with no
78
+ * deadline grew the buffer for as long as it stayed open.
79
+ */
80
+ function withoutKeepAlives(buffer: string): string {
81
+ let start = 0;
82
+ while (buffer.startsWith(STREAM_KEEPALIVE_CHUNK, start)) start += STREAM_KEEPALIVE_CHUNK.length;
83
+ return start === 0 ? buffer : buffer.slice(start);
84
+ }
85
+
86
+ /** Everything left, for an answer shown whole (a modal): the chunks joined, the tail dropped. */
87
+ export async function drain(rest: PageRest): Promise<string> {
88
+ let html = '';
89
+ for (let chunk = await rest.next(); chunk !== null; chunk = await rest.next()) html += chunk;
90
+ return html;
91
+ }
92
+
93
+ /**
94
+ * Each chunk into the live body, in arrival order, then its scripts: the hole's `$X()` reveal and
95
+ * whatever its `after` carries (a hole's islands). Stops at `signal` — a newer page took the body —
96
+ * and cancels the request either way. Rejects when the stream broke under a page still on screen.
97
+ * `landed`, after each chunk, until it answers `true`: what waits on a hole's content (a fragment).
98
+ */
99
+ export async function fillHoles(
100
+ doc: Document,
101
+ rest: PageRest,
102
+ ran: Set<string>,
103
+ signal: AbortSignal,
104
+ landed?: () => boolean,
105
+ ): Promise<void> {
106
+ let waiting = landed;
107
+ const stop = (): void => rest.cancel();
108
+ signal.addEventListener('abort', stop, { once: true });
109
+ try {
110
+ for (let chunk = await rest.next(); chunk !== null; chunk = await rest.next()) {
111
+ if (signal.aborted) return;
112
+ const parsed = new DOMParser().parseFromString(`<body>${chunk}`, 'text/html');
113
+ const nodes = [...parsed.body.childNodes].map((node) => doc.adoptNode(node));
114
+ doc.body.append(...nodes);
115
+ const scripts = nodes
116
+ .filter((node): node is Element => node.nodeType === ELEMENT_NODE)
117
+ .flatMap((el) =>
118
+ el.tagName === 'SCRIPT' ? [el as HTMLScriptElement] : [...el.querySelectorAll('script')],
119
+ );
120
+ await runScripts(scripts, ran, (fresh, inert) => inert.replaceWith(fresh));
121
+ // A stop or a newer page while the scripts ran: this page is no longer the visitor's.
122
+ if (signal.aborted) return;
123
+ if (waiting?.() === true) waiting = undefined;
124
+ }
125
+ } catch (error) {
126
+ if (!signal.aborted) throw error;
127
+ } finally {
128
+ signal.removeEventListener('abort', stop);
129
+ rest.cancel();
130
+ }
131
+ }
package/src/navigation.ts CHANGED
@@ -18,7 +18,7 @@
18
18
 
19
19
  import { navigationCache } from './navigation-cache';
20
20
  import { withinDeadline } from './navigation-deadline';
21
- import { announcer, handOver } from './navigation-dom';
21
+ import { announcer, handOver, isAttachment } from './navigation-dom';
22
22
  import {
23
23
  type Answer,
24
24
  fetchDocument,
@@ -26,7 +26,13 @@ import {
26
26
  metaOf,
27
27
  responseFactsOf,
28
28
  } from './navigation-fetch';
29
- import { recordEntry, scrollAfter, withoutFragment } from './navigation-history';
29
+ import {
30
+ lateFragment,
31
+ loadForReal,
32
+ recordEntry,
33
+ scrollAfter,
34
+ withoutFragment,
35
+ } from './navigation-history';
30
36
  import { interceptNavigation } from './navigation-intercept';
31
37
  import { modalController } from './navigation-modal';
32
38
  import { addressOf, modalAddress, modalHistory } from './navigation-modal-rules';
@@ -51,6 +57,7 @@ import {
51
57
  responseVerdict,
52
58
  } from './navigation-rules';
53
59
  import { scrollKeeper } from './navigation-scroll';
60
+ import { drain, fillHoles, type PageRest } from './navigation-stream';
54
61
  import {
55
62
  documentHead,
56
63
  loadStylesheets,
@@ -116,6 +123,10 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
116
123
  let untrusted = false;
117
124
  let backing = false; // a Back this router started is traversing: the URL is still the one left
118
125
  let inflight: AbortController | undefined;
126
+ /** The page on screen still filling its holes; aborted by the next swap and by `stop()`. */
127
+ let filling: AbortController | undefined;
128
+ /** A broken stream's recovery, held while a newer navigation is on its way (`fill`). */
129
+ let recoverOnSettle: (() => void) | undefined;
119
130
  const live = announcer(doc);
120
131
  const owned = documentHead(doc);
121
132
  notePersisted(doc);
@@ -144,14 +155,33 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
144
155
  cache.set(url, request(url, 'prefetch'));
145
156
  };
146
157
 
158
+ /**
159
+ * The tab is about to be the browser's: the page on screen stops reading its holes and a held
160
+ * recovery (`fill`) is dropped. Either would otherwise load the page being left, over the load the
161
+ * browser has not committed yet.
162
+ */
163
+ const abandon = (): void => {
164
+ recoverOnSettle = undefined;
165
+ filling?.abort();
166
+ };
167
+
168
+ // Back/Forward put `url` in the address bar already: `assign` of it would only scroll (loadForReal).
169
+ // The visit in flight goes too: a POST whose `ultimate:navigated` listener started this never fills.
170
+ const loadInstead = (url: string): void => {
171
+ inflight?.abort();
172
+ abandon();
173
+ loadForReal(win, url);
174
+ };
175
+
147
176
  /** Cancelable; its default is a GET of the page the visitor is on. Nothing is re-sent. */
148
177
  const failed = (url: string, method: string, reason: string): void => {
149
178
  const detail = { url, method, reason };
150
179
  const event = new CustomEvent(NAVIGATION_ERROR_EVENT, { detail, cancelable: true });
151
180
  if (!doc.dispatchEvent(event)) return;
181
+ abandon();
152
182
  // Under a modal the URL differs only by its hash, which `assign` merely scrolls to: reloaded,
153
183
  // the page and its modal are both asked for again (the entry is the router's own GET).
154
- if (modal.address === undefined) win.location.assign(win.location.href);
184
+ if (modal.address === undefined) loadForReal(win, win.location.href);
155
185
  else win.location.reload();
156
186
  };
157
187
 
@@ -181,7 +211,7 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
181
211
  // trusted to swap: every navigation is a real load (`answerMovesTab`).
182
212
  if (untrusted && method === 'GET') {
183
213
  if (options.fromHash === true) modal.clear();
184
- else win.location.assign(url);
214
+ else loadInstead(url);
185
215
  return;
186
216
  }
187
217
  if (refreshYields(options.refresh, inflight)) return;
@@ -200,6 +230,8 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
200
230
  () => doc.documentElement.setAttribute(NAVIGATING_ATTRIBUTE, ''),
201
231
  NAVIGATION_PROGRESS_DELAY_MS,
202
232
  );
233
+ /** A streamed answer's rest no page took: cancelled on the way out, so its request ends. */
234
+ let unread: PageRest | null = null;
203
235
  try {
204
236
  let answer: Answer;
205
237
  try {
@@ -207,10 +239,11 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
207
239
  } catch {
208
240
  if (mine.signal.aborted || refreshFailsQuietly(options.refresh)) return;
209
241
  // A GET that never arrived is the browser's to try; a POST that failed is never re-sent.
210
- if (method === 'GET') win.location.assign(url);
242
+ if (method === 'GET') loadInstead(url);
211
243
  else failed(url, method, 'the request failed on the network');
212
244
  return;
213
245
  }
246
+ unread = answer.rest;
214
247
  if (mine.signal.aborted) return;
215
248
  const next =
216
249
  answer.html === null ? null : new DOMParser().parseFromString(answer.html, 'text/html');
@@ -239,7 +272,7 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
239
272
  // A principal change the router saw, or one the server may have signalled by handing
240
273
  // over the very URL it was asked for (it cannot say which): every tab forgets.
241
274
  if (verdict.reason === 'another principal' || verdict.url === url) forget();
242
- win.location.assign(verdict.url);
275
+ loadInstead(verdict.url);
243
276
  return;
244
277
  case 'follow':
245
278
  await navigate(verdict.url, {
@@ -249,6 +282,9 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
249
282
  });
250
283
  return;
251
284
  case 'hand-over':
285
+ // A download leaves the page on screen, still filling; anything else is shown by the
286
+ // browser in its place.
287
+ if (!isAttachment(answer.disposition)) abandon();
252
288
  if (answer.body !== null) handOver(win, answer.body, answer.disposition);
253
289
  return;
254
290
  default:
@@ -270,12 +306,19 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
270
306
  if (!sheetsLoaded) {
271
307
  if (refreshFailsQuietly(options.refresh)) return;
272
308
  if (method === 'GET') {
273
- win.location.assign(url);
309
+ loadInstead(url);
274
310
  return;
275
311
  }
276
312
  }
277
313
  if (shown === 'modal') {
278
- await modal.present(next, addressOf(landed), landed, modalHistory(method, history));
314
+ // A modal is shown whole: its holes are read to the end first.
315
+ let whole = next;
316
+ if (unread !== null) {
317
+ const rest = await drain(unread);
318
+ if (mine.signal.aborted) return;
319
+ whole = new DOMParser().parseFromString(`${answer.html ?? ''}${rest}`, 'text/html');
320
+ }
321
+ await modal.present(whole, addressOf(landed), landed, modalHistory(method, history));
279
322
  doc.dispatchEvent(new CustomEvent(NAVIGATED_EVENT, { detail: { url: landed } }));
280
323
  return;
281
324
  }
@@ -286,6 +329,7 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
286
329
  modal.release();
287
330
  modal.dismiss();
288
331
  let swapped: ReturnType<typeof swapDocument> | undefined;
332
+ let scrolled: (() => boolean) | undefined;
289
333
  const hold = holdFor(doc, options.refresh);
290
334
  if (hold === null) return;
291
335
  await swapIn(
@@ -294,6 +338,8 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
294
338
  () => {
295
339
  // A newer navigation started while the sheets loaded: this answer is no longer asked for.
296
340
  if (mine.signal.aborted) return;
341
+ // The page leaving stops reading its holes: nothing of it lands in this one.
342
+ filling?.abort();
297
343
  swapped = swapDocument(doc, next, owned, sheetsLoaded);
298
344
  // Emptied here and filled after the scripts, so a page with the same title still reads out.
299
345
  if (hold === undefined) live.textContent = '';
@@ -302,6 +348,8 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
302
348
  recordEntry(win, landed, rendered, history);
303
349
  // Inside the swap, so a view transition's "after" frame is already where the page lands.
304
350
  scrollAfter(win, doc, landed, history);
351
+ // Where the visitor is now, before any script or listener moves them.
352
+ scrolled = lateFragment(win, doc, landed, history);
305
353
  },
306
354
  press.track,
307
355
  );
@@ -321,13 +369,23 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
321
369
  landFocus(doc, live, hold);
322
370
  doc.dispatchEvent(new CustomEvent(NAVIGATED_EVENT, { detail: { url: landed } }));
323
371
  reconcile();
372
+ // Scripts and listeners ran since the swap: a newer navigation, or `stop()`, may have
373
+ // taken the body. The holes left unread are then cancelled below, never filled.
374
+ if (mine.signal.aborted) return;
375
+ if (unread !== null) {
376
+ fill(unread, landed, method, scrolled);
377
+ unread = null;
378
+ }
324
379
  } catch {
325
380
  // A swap that failed part-way leaves a page nobody rendered: a GET is loaded for real; a
326
381
  // POST's answer cannot be asked for again, so the visitor is told and shown this page.
327
- if (method === 'GET') win.location.assign(landed);
328
- else failed(url, method, 'the answer could not be shown');
382
+ if (method === 'GET') {
383
+ abandon();
384
+ loadForReal(win, landed);
385
+ } else failed(url, method, 'the answer could not be shown');
329
386
  }
330
387
  } finally {
388
+ unread?.cancel();
331
389
  win.clearTimeout(progress);
332
390
  if (inflight === mine) {
333
391
  inflight = undefined;
@@ -335,10 +393,39 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
335
393
  // Whatever the answer was, a frame nothing filled goes; an open modal is no longer busy.
336
394
  modal.settle();
337
395
  doc.documentElement.removeAttribute(NAVIGATING_ATTRIBUTE);
396
+ const recover = recoverOnSettle;
397
+ recoverOnSettle = undefined;
398
+ recover?.();
338
399
  }
339
400
  }
340
401
  };
341
402
 
403
+ /**
404
+ * The holes of the page just shown, filled as they arrive: the shell painted without them. A
405
+ * stream that breaks under the page is a page nobody rendered — a GET is loaded for real, a POST
406
+ * (never re-sent) is reported. One the next swap cut short is nobody's failure; one that breaks
407
+ * while the visitor's next page is on its way waits for it, and recovers only if that visit
408
+ * stayed or failed quietly — one that took the body, or handed the tab to the browser, drops it.
409
+ */
410
+ function fill(
411
+ rest: PageRest,
412
+ landed: string,
413
+ method: 'GET' | 'POST',
414
+ scrolled: (() => boolean) | undefined,
415
+ ): void {
416
+ const own = new AbortController();
417
+ filling = own;
418
+ fillHoles(doc, rest, ran, own.signal, scrolled).catch(() => {
419
+ const recover = (): void => {
420
+ if (own.signal.aborted) return;
421
+ if (method === 'GET') loadForReal(win, landed);
422
+ else failed(landed, method, 'the answer could not be shown');
423
+ };
424
+ if (inflight === undefined) recover();
425
+ else recoverOnSettle = recover;
426
+ });
427
+ }
428
+
342
429
  /**
343
430
  * The modal follows the URL's hash, once the page on screen is the URL's: opened (fetched, as a
344
431
  * hash address, so a stale one degrades), kept, or dismissed. On start, on Back/Forward, on a
@@ -395,6 +482,9 @@ export function startNavigation(win: RouterWindow = window): NavigationRouter |
395
482
  closeModal: () => modal.close(),
396
483
  stop() {
397
484
  stopListening();
485
+ // The answer still being read, too: a stopped router mutates nothing after this.
486
+ inflight?.abort();
487
+ filling?.abort();
398
488
  modal.dismiss();
399
489
  scroll.stop();
400
490
  tabs.stop();
@@ -22,7 +22,12 @@ import {
22
22
  } from '@ultimat3/core';
23
23
  import { finiteStatus } from './finite-status';
24
24
  import type { RenderResult } from './route';
25
- import { REVEAL_BODY, REVEAL_CALL } from './stream-scripts';
25
+ import {
26
+ REVEAL_BODY,
27
+ REVEAL_CALL,
28
+ STREAM_FLUSH_MARK,
29
+ STREAM_KEEPALIVE_CHUNK,
30
+ } from './stream-scripts';
26
31
 
27
32
  export interface StreamHole {
28
33
  /** Stable within a response; becomes the DOM id, so keep it short. */
@@ -118,8 +123,8 @@ export interface StreamOptions {
118
123
  /** Under the shortest `idleTimeout` `@ultimat3/http` derives: `ceil(requestTimeoutMs / 1000) + 2` ≥ 3 s. */
119
124
  export const DEFAULT_STREAM_KEEPALIVE_MS = 1_000;
120
125
 
121
- /** The keep-alive write: a comment, inert wherever the parser is between two chunks. */
122
- export const STREAM_KEEPALIVE_CHUNK = '<!---->';
126
+ /** The keep-alive write, declared beside the flush mark so the client router reads the same one. */
127
+ export { STREAM_KEEPALIVE_CHUNK } from './stream-scripts';
123
128
 
124
129
  /**
125
130
  * `null` is the declared "this hole owns its own timeout" opt-out; every other value is a
@@ -233,8 +238,12 @@ export function renderStreamHtml(
233
238
  controller.close();
234
239
  };
235
240
 
236
- // No holes, no reveal script: a page that streams nothing pays nothing.
237
- write(plan.head + (plan.holes.length > 0 ? REVEAL_SCRIPT : '') + plan.shell);
241
+ // No holes, no reveal script and no mark: a page that streams nothing pays nothing.
242
+ write(
243
+ plan.holes.length > 0
244
+ ? plan.head + REVEAL_SCRIPT + plan.shell + STREAM_FLUSH_MARK
245
+ : plan.head + plan.shell,
246
+ );
238
247
 
239
248
  let pending = plan.holes.length;
240
249
  if (pending === 0) {
@@ -268,7 +277,7 @@ export function renderStreamHtml(
268
277
  if (revealed) return;
269
278
  revealed = true;
270
279
  if (timer !== undefined) clearTimeout(timer);
271
- write(revealChunk(hole.id, html, after));
280
+ write(revealChunk(hole.id, html, after) + STREAM_FLUSH_MARK);
272
281
  settle();
273
282
  };
274
283
  const failed = (): string => hole.error ?? fallbackOf(errorFallback, hole.id);
package/src/server.ts CHANGED
@@ -99,4 +99,15 @@ export {
99
99
  } from './render-stream';
100
100
  // ---- the Sass compile cache: where it lives, and how often this process ran Sass instead --------
101
101
  export { sassCompilations, setSassCacheDir } from './sass-cache';
102
+ export type { SiteAsset, SiteAssetTable } from './site-assets';
103
+ export {
104
+ ASSET_CONTENT_TYPES,
105
+ hashedAssetUrl,
106
+ parseHashedAssetUrl,
107
+ SITE_ASSET_BASE_PATH,
108
+ SITE_ASSETS_SOURCE,
109
+ siteAssetTable,
110
+ } from './site-assets';
111
+ /** The comment a `stream` page writes after its shell and after each hole: what a reader splits on. */
112
+ export { STREAM_FLUSH_MARK } from './stream-scripts';
102
113
  export { serverTsxBuildPlugin } from './tsx-build-plugin';
@@ -0,0 +1,160 @@
1
+ // The site asset table: every file under `apps/web/site/assets/` by content-hashed URL, one per app
2
+ // root, answering `asset()`, `/assets/*` and the static export's copy alike. Below the CLI so the
3
+ // test preload installs the same table the boot does.
4
+
5
+ // why: `asset()` is called from a synchronous render, so the table answers synchronously — and Bun
6
+ // ships no sync stat or sync read; `join`/`relative` because Bun ships no path API either.
7
+ import { readFileSync, statSync } from 'node:fs';
8
+ import { join } from 'node:path'; // why: Bun ships no path API.
9
+ import { renderFixShellArg } from '@ultimat3/core';
10
+ import { ASSET_DIR, type AssetExtension, type AssetPath, assetPathProblem } from './asset';
11
+ import { AssetMissingError } from './errors';
12
+ import { contentHash } from './render-static';
13
+
14
+ /** App-root-relative, beside `favicon.ico`: `apps/web/site/` is where an app's public files live. */
15
+ export const SITE_ASSETS_SOURCE = `apps/web/site/${ASSET_DIR}`;
16
+
17
+ /** The URL prefix every hashed asset is served under, and the export directory it is copied to. */
18
+ export const SITE_ASSET_BASE_PATH = `/${ASSET_DIR}`;
19
+
20
+ /** What each served extension IS. `vtt` carries a charset: captions are text a player decodes. */
21
+ export const ASSET_CONTENT_TYPES: Readonly<Record<AssetExtension, string>> = {
22
+ avif: 'image/avif',
23
+ webp: 'image/webp',
24
+ png: 'image/png',
25
+ jpg: 'image/jpeg',
26
+ jpeg: 'image/jpeg',
27
+ gif: 'image/gif',
28
+ svg: 'image/svg+xml',
29
+ ico: 'image/x-icon',
30
+ woff2: 'font/woff2',
31
+ mp4: 'video/mp4',
32
+ webm: 'video/webm',
33
+ vtt: 'text/vtt; charset=utf-8',
34
+ };
35
+
36
+ export interface SiteAsset {
37
+ /** As `asset()` names it: `assets/brand/logo.svg`. */
38
+ readonly path: AssetPath;
39
+ /** Absolute path on disk. */
40
+ readonly file: string;
41
+ /** `@ultimat3/render`'s `contentHash` of the bytes, 8 hex characters — the one CSS and HTML get. */
42
+ readonly hash: string;
43
+ /** `/assets/brand/logo.<hash>.svg`. */
44
+ readonly url: string;
45
+ readonly contentType: string;
46
+ readonly bytes: number;
47
+ }
48
+
49
+ const splitExtension = (path: string): { readonly stem: string; readonly extension: string } => {
50
+ const dot = path.lastIndexOf('.');
51
+ return { stem: path.slice(0, dot), extension: path.slice(dot + 1) };
52
+ };
53
+
54
+ /** The hash goes before the extension, so a static host still infers the type from the name. */
55
+ export function hashedAssetUrl(path: AssetPath, hash: string): string {
56
+ const { stem, extension } = splitExtension(path);
57
+ return `/${stem}.${hash}.${extension}`;
58
+ }
59
+
60
+ const HASHED = /^\/(assets\/.+)\.([0-9a-f]{8})\.([a-z0-9]+)$/i;
61
+
62
+ /** The inverse of `hashedAssetUrl`: which asset a request names, and at which content. */
63
+ export function parseHashedAssetUrl(
64
+ pathname: string,
65
+ ): { readonly path: AssetPath; readonly hash: string } | undefined {
66
+ const match = HASHED.exec(pathname);
67
+ if (match === null) return undefined;
68
+ const path = `${match[1] ?? ''}.${match[3] ?? ''}`;
69
+ if (assetPathProblem(path) !== undefined) return undefined;
70
+ return { path: path as AssetPath, hash: match[2] ?? '' };
71
+ }
72
+
73
+ export interface SiteAssetTable {
74
+ /** The asset `asset()` named, hashed as the bytes are NOW. Throws `X_ASSET_MISSING`. */
75
+ resolve(path: AssetPath): SiteAsset;
76
+ /** Every servable file under the source directory, sorted by path. */
77
+ all(): readonly SiteAsset[];
78
+ }
79
+
80
+ const missing = (path: string, cause: string): AssetMissingError =>
81
+ new AssetMissingError(
82
+ `asset(${JSON.stringify(path)}): ${cause}`,
83
+ `ls ${renderFixShellArg(SITE_ASSETS_SOURCE, '<assets>')} # add ${SITE_ASSETS_SOURCE}/${path.slice(ASSET_DIR.length + 1)} there, or correct the path passed to asset(); then x build --target static --json`,
84
+ );
85
+
86
+ /**
87
+ * A stat per call, a read only when the file changed: `x dev` sees an edited image under a new URL
88
+ * on the next render with no watcher, and the container — whose files never change — pays one
89
+ * `stat` per `asset()` call and nothing else. One behaviour in both, never a dev-only rescan.
90
+ */
91
+ function createSiteAssetTable(root: string): SiteAssetTable {
92
+ const source = join(root, SITE_ASSETS_SOURCE);
93
+ const cache = new Map<string, { readonly stamp: string; readonly asset: SiteAsset }>();
94
+
95
+ const resolve = (path: AssetPath): SiteAsset => {
96
+ const problem = assetPathProblem(path);
97
+ if (problem !== undefined) throw missing(path, problem);
98
+ const file = join(source, path.slice(ASSET_DIR.length + 1));
99
+ let stamp: string;
100
+ try {
101
+ const stat = statSync(file);
102
+ if (!stat.isFile()) throw missing(path, `${file} is not a file`);
103
+ stamp = `${String(stat.mtimeMs)}:${String(stat.size)}`;
104
+ } catch (error) {
105
+ if (error instanceof AssetMissingError) throw error;
106
+ throw missing(path, `no file at ${SITE_ASSETS_SOURCE}/${path.slice(ASSET_DIR.length + 1)}`);
107
+ }
108
+ const cached = cache.get(path);
109
+ if (cached !== undefined && cached.stamp === stamp) return cached.asset;
110
+ const bytes = readFileSync(file);
111
+ const hash = contentHash(bytes);
112
+ // `assetPathProblem` already refused an unknown extension; the guard keeps `constructor` from
113
+ // ever answering an `Object` member if that check is loosened.
114
+ const extension = splitExtension(path).extension.toLowerCase();
115
+ const asset: SiteAsset = {
116
+ path,
117
+ file,
118
+ hash,
119
+ url: hashedAssetUrl(path, hash),
120
+ contentType: Object.hasOwn(ASSET_CONTENT_TYPES, extension)
121
+ ? ASSET_CONTENT_TYPES[extension as AssetExtension]
122
+ : 'application/octet-stream',
123
+ bytes: bytes.byteLength,
124
+ };
125
+ cache.set(path, { stamp, asset });
126
+ return asset;
127
+ };
128
+
129
+ const all = (): readonly SiteAsset[] => {
130
+ const found: SiteAsset[] = [];
131
+ let files: string[];
132
+ try {
133
+ files = [...new Bun.Glob('**/*').scanSync({ cwd: source, onlyFiles: true })];
134
+ } catch {
135
+ // No `assets/` directory is an app with no assets, not an error.
136
+ return [];
137
+ }
138
+ for (const relativePath of files.sort()) {
139
+ const path = `${ASSET_DIR}/${relativePath.split('\\').join('/')}`;
140
+ // A source file beside its renditions (a `.psd`, a `README.md`) is not a served asset.
141
+ if (assetPathProblem(path) !== undefined) continue;
142
+ found.push(resolve(path as AssetPath));
143
+ }
144
+ return found;
145
+ };
146
+
147
+ return { resolve, all };
148
+ }
149
+
150
+ /** One table per root, so the renderer and the route read the same cache. */
151
+ const tables = new Map<string, SiteAssetTable>();
152
+
153
+ export function siteAssetTable(root: string): SiteAssetTable {
154
+ let table = tables.get(root);
155
+ if (table === undefined) {
156
+ table = createSiteAssetTable(root);
157
+ tables.set(root, table);
158
+ }
159
+ return table;
160
+ }
@@ -16,3 +16,16 @@ export const REVEAL_CALL = '$X()';
16
16
  * every template that has arrived.
17
17
  */
18
18
  export const STREAM_REVEAL_BODIES: readonly string[] = Object.freeze([REVEAL_BODY, REVEAL_CALL]);
19
+
20
+ /**
21
+ * Written after the shell and after each hole's chunk, in the same write: everything before it is
22
+ * whole markup. The client router reads a soft visit as it arrives and swaps the shell at the first
23
+ * mark, then fills each hole at the next; a full load's parser reads it as an empty comment.
24
+ */
25
+ export const STREAM_FLUSH_MARK = '<!--x:flush-->';
26
+
27
+ /**
28
+ * Written every `keepAliveMs` while a hole is open, always between two whole chunks: a comment the
29
+ * parser reads as nothing, and the client router drops as it arrives (`navigation-stream.ts`).
30
+ */
31
+ export const STREAM_KEEPALIVE_CHUNK = '<!---->';