@ultimat3/render 30.8.0 → 31.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.
package/src/render-isr.ts CHANGED
@@ -22,6 +22,7 @@ import { finiteCount, logger, renderThrowable, singleFlight } from '@ultimat3/co
22
22
  import { finiteStatus } from './finite-status';
23
23
  import type { RouteDescriptor } from './registry';
24
24
  import { describePages } from './registry';
25
+ import { timedRender } from './render-instrument';
25
26
  import { DEFAULT_ISR_FAILURE_COOLDOWN_MS, failureCooldown } from './render-isr-cooldown';
26
27
  import { entryTtlMs, isrResult } from './render-isr-result';
27
28
  import type { IsrPolicy } from './render-isr-routes';
@@ -96,6 +97,8 @@ export function isrController(options: IsrControllerOptions = {}): IsrController
96
97
  */
97
98
  const latest = new Map<string, object>();
98
99
  const registered = new Set<string>();
100
+ /** How many pages the store held at the last listing — what `forgetEvictedPaths` compares. */
101
+ let heldAtLastListing = 0;
99
102
  const fences = options.fence ?? PROCESS_FENCE;
100
103
  const failed = failureCooldown<Generation>(
101
104
  finiteCount(
@@ -149,11 +152,24 @@ export function isrController(options: IsrControllerOptions = {}): IsrController
149
152
  * the cache graph behind it only ever grew: `/blog/:slug` retains one edge per slug ever
150
153
  * requested, 404-shaped ones included, for the life of the process.
151
154
  */
152
- function forgetEvictedPaths(): void {
153
- if (registered.size === 0) return;
155
+ async function forgetEvictedPaths(): Promise<void> {
156
+ // Only once registrations outgrew what the store last held: a page only leaves the store when
157
+ // a newer one pushes it out, and over a shared disk every listing is a round trip per page of
158
+ // keys — once per generation was a full listing per render.
159
+ if (registered.size <= heldAtLastListing) return;
160
+ let held: readonly string[];
161
+ try {
162
+ held = await store.paths();
163
+ } catch (error) {
164
+ // After the page was kept and the result decided: a listing that failed leaves edges for a
165
+ // later generation to reconcile, never a render that succeeded turned into a rejection.
166
+ logger.warn('isr.store.paths_failed', { error: renderThrowable(error) });
167
+ return;
168
+ }
169
+ heldAtLastListing = held.length;
154
170
  // A page whose FIRST render is still running is in no store yet and is not evicted: forgotten
155
171
  // here, a bust arriving before it settled found it in neither the graph nor the store.
156
- const live = new Set([...store.paths(), ...flight.keys()]);
172
+ const live = new Set([...held, ...flight.keys()]);
157
173
  for (const path of registered) if (!live.has(path)) forgetPath(path);
158
174
  }
159
175
 
@@ -196,8 +212,15 @@ export function isrController(options: IsrControllerOptions = {}): IsrController
196
212
  const fence = fences.sample({ key: path, tags: policy.tags });
197
213
  // And the STORE's own fence, for a store another process writes: read before the rows are.
198
214
  const entities = entitiesOf(policy.tags);
199
- const reading = store.tagFence?.sample(entities);
200
- const rendered = renderedOf(await render(path));
215
+ const reading = await store.tagFence?.sample(entities);
216
+ // One event per GENERATION — the requests that joined this flight are not renders.
217
+ const rendered = renderedOf(
218
+ await timedRender(
219
+ 'render.isr.regenerate',
220
+ { route: descriptor?.path ?? path, path },
221
+ async () => await render(path),
222
+ ),
223
+ );
201
224
  const entry: IsrEntry = {
202
225
  path,
203
226
  html: rendered.html,
@@ -215,7 +238,16 @@ export function isrController(options: IsrControllerOptions = {}): IsrController
215
238
  // Kept only when nothing invalidated the page while it rendered — in this process (the
216
239
  // fence) or in any other (the store's) — and no newer run started. Refused, never
217
240
  // published stale-flagged: the next request re-renders from rows that include the write.
218
- const kept = !unstorable && fence.isValid() && current && write(entry, entities, reading);
241
+ let kept =
242
+ !unstorable && fence.isValid() && current && (await write(entry, entities, reading));
243
+ // Asked AGAIN once the write settled: over a shared store the write is a round trip, and an
244
+ // invalidation landing inside it found no page to mark or delete — then the put landed
245
+ // fresh, and a tag-only page answered as a fresh hit for good. Undone the route's way.
246
+ if (kept && !fence.isValid()) {
247
+ kept = false;
248
+ if (policy.onInvalidate === 'purge') await store.delete(path);
249
+ else await store.markStale(path);
250
+ }
219
251
  if (isServerError(rendered.status)) {
220
252
  // Never stored, and never over a good copy: one upstream blip stored for the TTL plus a
221
253
  // stale serve was minutes of 503 for a read that recovered in a second. The copy the
@@ -226,9 +258,9 @@ export function isrController(options: IsrControllerOptions = {}): IsrController
226
258
  tellUnowned(path);
227
259
  } else if (rendered.noStore === true) {
228
260
  // The loader's answer is not a failure, so the copy held is no longer the page.
229
- if (current) store.delete(path);
261
+ if (current) await store.delete(path);
230
262
  }
231
- forgetEvictedPaths();
263
+ await forgetEvictedPaths();
232
264
  // What the store did not keep, the edge may not keep either: a page rendered from rows
233
265
  // read BEFORE a purge would otherwise reach the CDN after the purge had already run there.
234
266
  return { entry, cacheable: kept, fenced: !unstorable && !kept };
@@ -239,13 +271,13 @@ export function isrController(options: IsrControllerOptions = {}): IsrController
239
271
  }
240
272
 
241
273
  /** The one write: through the store's own fence when it has one, so a stale reading is refused. */
242
- function write(
274
+ async function write(
243
275
  entry: IsrEntry,
244
276
  entities: readonly string[],
245
277
  reading: string | undefined,
246
- ): boolean {
278
+ ): Promise<boolean> {
247
279
  if (store.tagFence === undefined || reading === undefined) {
248
- store.set(entry);
280
+ await store.set(entry);
249
281
  return true;
250
282
  }
251
283
  return store.tagFence.setIfCurrent(entry, entities, reading);
@@ -272,10 +304,11 @@ export function isrController(options: IsrControllerOptions = {}): IsrController
272
304
  return (await generate(path, render)).entry;
273
305
  }
274
306
 
275
- function markStale(path: string): boolean {
307
+ async function markStale(path: string): Promise<boolean> {
276
308
  // The mark is recorded whether or not the store holds the page: a regeneration already in
277
309
  // flight for a path this store has never held is exactly the case the fence above exists for,
278
- // and `invalidateTags`' own fanout only marks the TAGS.
310
+ // and `invalidateTags`' own fanout only marks the TAGS. Before the first await, so a render
311
+ // that settles while the store answers is fenced already.
279
312
  fences.mark({ key: path });
280
313
  return store.markStale(path);
281
314
  }
@@ -288,16 +321,18 @@ export function isrController(options: IsrControllerOptions = {}): IsrController
288
321
  * and its FLIGHT is evicted, so a request arriving after this call leads a render of its own
289
322
  * instead of joining one that read its rows before the write (up to the 30 s deadline of them).
290
323
  */
291
- function invalidate(path: string): void {
324
+ async function invalidate(path: string): Promise<void> {
325
+ // Everything this process knows changes before the first await: a request arriving while the
326
+ // store answers already finds the flight gone and the fence marked.
292
327
  failed.clear(path);
293
328
  flight.evict(path);
294
329
  if (isrPolicyOf(descriptorFor(path)).onInvalidate !== 'purge') {
295
- markStale(path);
330
+ await markStale(path);
296
331
  return;
297
332
  }
298
333
  fences.mark({ key: path });
299
- store.delete(path);
300
334
  forgetPath(path);
335
+ await store.delete(path);
301
336
  }
302
337
 
303
338
  /**
@@ -310,7 +345,10 @@ export function isrController(options: IsrControllerOptions = {}): IsrController
310
345
  * By ROUTE tags: a row bust (`post:1`) reaches every stored page of a route tagged `post`. An
311
346
  * entry records no tags of its own, so this errs toward one render too many, never one too few.
312
347
  */
313
- function revalidateHeld(tags: readonly CacheTag[] | typeof EVERY_TAG): readonly string[] {
348
+ async function revalidateHeld(
349
+ tags: readonly CacheTag[] | typeof EVERY_TAG,
350
+ invalidated: ReadonlySet<string> = new Set(),
351
+ ): Promise<readonly string[]> {
314
352
  const table = routes();
315
353
  // A flush (`EVERY_TAG`) is a bust of every tag at once: every route that carries one owns.
316
354
  const owns = (route: RouteDescriptor): boolean =>
@@ -326,11 +364,16 @@ export function isrController(options: IsrControllerOptions = {}): IsrController
326
364
  // The store's fence FIRST: a write racing this call from another process is refused from here.
327
365
  const busted =
328
366
  tags === EVERY_TAG ? [...owners].flatMap((r) => r.revalidateTags.map(parseTag)) : tags;
329
- store.tagFence?.bump(entitiesOf(busted));
330
- for (const key of flight.keys()) if (owned(key)) invalidate(key);
331
- const held = store.paths().filter(owned);
332
- // A page the graph already named was marked a moment ago; it is reported, not marked twice.
333
- for (const path of held) if (store.get(path)?.stale !== true) invalidate(path);
367
+ // Awaited before the store is listed: a write that passed its check before this bump landed is
368
+ // in the listing below and is taken down; one that checks after it is refused there.
369
+ await store.tagFence?.bump(entitiesOf(busted));
370
+ const pending = [...flight.keys()].filter(owned).map(invalidate);
371
+ const held = (await store.paths()).filter(owned);
372
+ // A page `revalidateByTags` already invalidated through the graph is reported, not done twice.
373
+ // Nothing is read back to decide it: a `get` per page was a round trip each over a shared
374
+ // store, and in `memoryIsrStore` it made every busted page the most recently used.
375
+ for (const path of held) if (!invalidated.has(path)) pending.push(invalidate(path));
376
+ await Promise.all(pending);
334
377
  return held;
335
378
  }
336
379
 
@@ -351,11 +394,11 @@ export function isrController(options: IsrControllerOptions = {}): IsrController
351
394
  cacheable,
352
395
  ageMs: Math.max(0, now() - entry.generatedAt),
353
396
  });
354
- let cached = store.get(path);
397
+ let cached = await store.get(path);
355
398
  // A copy under a key no route owns (a shared store an earlier release wrote) is not served:
356
399
  // nothing could have invalidated it since.
357
400
  if (cached !== undefined && (descriptor === undefined || pastMaxStale(cached, policy))) {
358
- store.delete(path);
401
+ await store.delete(path);
359
402
  cached = undefined;
360
403
  }
361
404
 
@@ -393,21 +436,20 @@ export function isrController(options: IsrControllerOptions = {}): IsrController
393
436
  return { state: 'stale', entry: cached, result: answer(cached, true), regenerating: started };
394
437
  },
395
438
 
396
- revalidateByTags(tags) {
439
+ async revalidateByTags(tags) {
397
440
  // By TAG first, as `invalidateTags` does before it calls in here: a cold page whose first
398
441
  // render is running may be in neither the graph nor the store, and only its fence finds it.
399
442
  fences.mark({ tags });
400
443
  const affected = new Set<string>(isrDependents(tags));
401
- for (const path of affected) invalidate(path);
402
- for (const path of revalidateHeld(tags)) affected.add(path);
444
+ const marking = [...affected].map(invalidate);
445
+ for (const path of await revalidateHeld(tags, affected)) affected.add(path);
446
+ await Promise.all(marking);
403
447
  return [...affected].sort();
404
448
  },
405
449
 
406
450
  attach() {
407
451
  // The cache fanout owns the trigger; render owns only "what does an invalidation mean here".
408
- const revalidate: Revalidator = (path) => {
409
- invalidate(path);
410
- };
452
+ const revalidate: Revalidator = (path) => invalidate(path);
411
453
  const revalidateTags: TagRevalidator = (tags) => revalidateHeld(tags);
412
454
  registerRevalidator(revalidate, revalidateTags);
413
455
  installedRevalidator = revalidate;
@@ -0,0 +1,275 @@
1
+ /**
2
+ * The tree walker: a JSX node in, HTML pieces out, appended to one flat buffer per render. A
3
+ * subtree pays for a promise only where it holds one — an awaited component, a `<Hole>` shell —
4
+ * so a 50k-row table is one synchronous pass and one `join` (plan 101 slice 14 P1).
5
+ */
6
+
7
+ import { escapeHtml } from '@ultimat3/core';
8
+ import { JSX_NODE } from '@ultimat3/core/render-node';
9
+ import { PrerenderFailedError } from './errors';
10
+ import type { HoleNode } from './hole';
11
+ import { isHoleNode } from './hole';
12
+ import { renderAttributes, VOID_ELEMENTS } from './html';
13
+ import { emitIslandAttributes, emitIslandProps } from './hydrate';
14
+ import type { IslandNode } from './island';
15
+ import { isIslandNode } from './island';
16
+ import { islandWithoutCollector } from './island-collector';
17
+ import type { JsxNode, JsxProps } from './jsx';
18
+ import type { RenderHtmlOptions } from './render-html';
19
+ import { holeMarker } from './render-stream';
20
+
21
+ /** Depth is bounded so a component that renders itself fails with a cause instead of a stack trace. */
22
+ const MAX_DEPTH = 500;
23
+
24
+ /**
25
+ * Asserted on every recursion, not only the element path: `children` is routinely an array or a
26
+ * thunk, and a self-referencing one escaped as a bare `RangeError` with no code and no `fix:`.
27
+ */
28
+ function assertDepth(depth: number): void {
29
+ if (depth <= MAX_DEPTH) return;
30
+ throw new PrerenderFailedError(
31
+ `component tree exceeded ${MAX_DEPTH} levels, so it renders itself`,
32
+ 'remove the self-reference from the component that renders its own tag',
33
+ );
34
+ }
35
+
36
+ /** What a subtree renders to: the string while it stayed synchronous, a promise once it awaited. */
37
+ export type Rendered = string | Promise<string>;
38
+
39
+ /**
40
+ * One render's output, in tree order. A pending subtree is a slot; everything else is a string.
41
+ * Side effects (a component call, an island's `record`, a hole's id) therefore run in tree order:
42
+ * every sibling's synchronous prefix runs before anything awaits, exactly as the all-async walker
43
+ * this replaced ran them.
44
+ */
45
+ interface Buffer {
46
+ /** Everything since the last slot, as FLAT segments: a rope of a few thousand flat leaves. */
47
+ html: string;
48
+ /** The segment being written: a rope of up to `FLATTEN_EVERY` fragments. */
49
+ tail: string;
50
+ /** Fragments in `tail`. */
51
+ appends: number;
52
+ /** Text before each pending slot, then the slot; absent while the render is synchronous. */
53
+ parts: Rendered[] | undefined;
54
+ }
55
+
56
+ /**
57
+ * Fragments per flattened segment. `+=` builds a rope that keeps every fragment alive until it is
58
+ * read: a 50k-row table held ~3.2M string cells, ~100 MiB, until the final join. Flattening every
59
+ * segment frees them as the walk goes, and each byte is copied once more, not once per segment.
60
+ * Measured 2026-11-10 (Bun 1.4.4, `scripts/bench/render-html.bench.ts --live-only`): 100.5 → 10.6
61
+ * MiB live at the walk's end; 256 and 1,024 time alike, 64 and 4,096 slower.
62
+ */
63
+ const FLATTEN_EVERY = 1024;
64
+
65
+ /**
66
+ * Resolves a rope into one flat string. JSC flattens a rope a regular expression reads; neither
67
+ * `charCodeAt` nor `.length` does on a rope this size. The pattern (two noncharacters) costs one
68
+ * scan, and its answer is unused.
69
+ */
70
+ const ROPE_READ = /\uFFFF\uFFFE/;
71
+
72
+ function write(out: Buffer, text: string): void {
73
+ out.tail += text;
74
+ out.appends += 1;
75
+ if (out.appends < FLATTEN_EVERY) return;
76
+ ROPE_READ.test(out.tail);
77
+ out.html += out.tail;
78
+ out.tail = '';
79
+ out.appends = 0;
80
+ }
81
+
82
+ /** Everything written since the last slot, and the buffer emptied for what follows. */
83
+ function take(out: Buffer): string {
84
+ const text = out.html + out.tail;
85
+ out.html = '';
86
+ out.tail = '';
87
+ out.appends = 0;
88
+ return text;
89
+ }
90
+
91
+ const noop = (): void => undefined;
92
+
93
+ /**
94
+ * Renders `value` into a buffer of its own and settles it. A synchronous throw leaves the slots
95
+ * already started unobserved, so each is marked handled before the throw goes on: the old
96
+ * `Promise.all` observed every sibling, and an unhandled rejection kills a Bun process.
97
+ */
98
+ export function renderAlone(value: unknown, depth: number, walk: RenderHtmlOptions): Rendered {
99
+ const out: Buffer = { html: '', tail: '', appends: 0, parts: undefined };
100
+ try {
101
+ emit(value, depth, walk, out);
102
+ } catch (error) {
103
+ for (const part of out.parts ?? []) if (typeof part !== 'string') part.catch(noop);
104
+ throw error;
105
+ }
106
+ if (out.parts === undefined) return take(out);
107
+ out.parts.push(take(out));
108
+ return Promise.all(out.parts).then((done) => done.join(''));
109
+ }
110
+
111
+ function slot(out: Buffer, pending: Promise<string>): void {
112
+ out.parts ??= [];
113
+ out.parts.push(take(out), pending);
114
+ }
115
+
116
+ /**
117
+ * A thunk is called, not stringified: Solid's reactive reads are accessors (`count()`), and a
118
+ * `children` prop is routinely a function — evaluating it once is exactly the server's job.
119
+ */
120
+ function emit(value: unknown, depth: number, walk: RenderHtmlOptions, out: Buffer): void {
121
+ assertDepth(depth);
122
+ if (value === null || value === undefined || value === false || value === true) return;
123
+ if (typeof value === 'string') {
124
+ write(out, escapeHtml(value));
125
+ return;
126
+ }
127
+ // A number's spelling is digits, `-`, `.`, `e`, `+`, `Infinity` or `NaN`: nothing to escape.
128
+ if (typeof value === 'number' || typeof value === 'bigint') {
129
+ write(out, String(value));
130
+ return;
131
+ }
132
+ if (typeof value === 'function') {
133
+ emit((value as () => unknown)(), depth + 1, walk, out);
134
+ return;
135
+ }
136
+ if (typeof value !== 'object') {
137
+ write(out, escapeHtml(String(value)));
138
+ return;
139
+ }
140
+ // The common case first. An island or hole node never carries `JSX_NODE`, so testing it before
141
+ // them changes no answer — only the arrays below must be told apart from those two.
142
+ if (JSX_NODE in value) {
143
+ emitNode(value as JsxNode, depth, walk, out);
144
+ return;
145
+ }
146
+ if (value instanceof Promise) {
147
+ slot(
148
+ out,
149
+ value.then((settled) => renderAlone(settled, depth, walk)),
150
+ );
151
+ return;
152
+ }
153
+ // Before the array branch, never after: an island node IS an array — the only object shape the
154
+ // configured `JSX.Element` admits — so the generic branch would drop the island, its props
155
+ // script and its budget line without a word.
156
+ if (isIslandNode(value)) {
157
+ emitIsland(value, depth, walk, out);
158
+ return;
159
+ }
160
+ if (isHoleNode(value)) {
161
+ emitHole(value, depth, walk, out);
162
+ return;
163
+ }
164
+ if (Array.isArray(value)) {
165
+ for (const item of value) emit(item, depth + 1, walk, out);
166
+ return;
167
+ }
168
+ write(out, escapeHtml(String(value)));
169
+ }
170
+
171
+ /**
172
+ * `innerHTML` is the one escape hatch that emits unescaped markup, and it is deliberate: the
173
+ * `<head>` renderers and the streaming reveal chunks are already-serialized HTML, and re-escaping
174
+ * them would print the tags. Nothing else in the walk trusts a string.
175
+ */
176
+ function emitNode(node: JsxNode, depth: number, walk: RenderHtmlOptions, out: Buffer): void {
177
+ const { type, props } = node;
178
+ if (typeof type !== 'string') {
179
+ emit(type(props), depth + 1, walk, out);
180
+ return;
181
+ }
182
+ write(out, `<${type}${renderAttributes(props)}>`);
183
+ if (VOID_ELEMENTS.has(type)) return;
184
+ const raw = (props as { innerHTML?: unknown }).innerHTML;
185
+ if (raw === undefined || raw === null) {
186
+ emit((props as { children?: unknown }).children, depth + 1, walk, out);
187
+ } else write(out, String(raw));
188
+ write(out, `</${type}>`);
189
+ }
190
+
191
+ /**
192
+ * An island renders its SHELL on the server — the children the page wrote — and nothing of the
193
+ * client module: the specifier is data, so there is no import to follow and the static page's
194
+ * bundle graph never grows. The props script travels inside the wrapper.
195
+ */
196
+ function emitIsland(node: IslandNode, depth: number, walk: RenderHtmlOptions, out: Buffer): void {
197
+ const collector = walk.islands;
198
+ if (collector === undefined) throw islandWithoutCollector(node.spec);
199
+ const directive = collector.record(node.spec, node.props);
200
+ const tag = node.spec.tag;
201
+ write(out, `<${tag} ${emitIslandAttributes(directive)}>`);
202
+ emit((node.props as { children?: unknown }).children, depth + 1, walk, out);
203
+ write(out, `${emitIslandProps(directive)}</${tag}>`);
204
+ }
205
+
206
+ /**
207
+ * A promise already running when the tree was built is awaited only once the stream starts, after
208
+ * the fallback rendered; a rejection before then is unhandled. Marked through arrays and JSX
209
+ * children — never by calling a thunk or a component, which have not run — and the hole still
210
+ * awaits and sees it. `seen` stops a self-referencing array.
211
+ */
212
+ function observeEagerPromises(value: unknown, seen: Set<object>): void {
213
+ if (value instanceof Promise) {
214
+ value.catch(noop);
215
+ return;
216
+ }
217
+ if (typeof value !== 'object' || value === null || seen.has(value)) return;
218
+ seen.add(value);
219
+ if (Array.isArray(value)) for (const item of value) observeEagerPromises(item, seen);
220
+ // An island or hole node is an array whose own items are empty: its tree is in `props`.
221
+ if (JSX_NODE in value || isIslandNode(value) || isHoleNode(value)) {
222
+ const props = (value as { props: JsxProps }).props as {
223
+ children?: unknown;
224
+ fallback?: unknown;
225
+ error?: unknown;
226
+ };
227
+ observeEagerPromises(props.children, seen);
228
+ observeEagerPromises(props.fallback, seen);
229
+ observeEagerPromises(props.error, seen);
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Everything under a hole walks with no sink: a nested hole is inline inside the outer one, since
235
+ * the set of pending holes is fixed at the first flush (`renderStreamHtml`). `resolve` is a thunk,
236
+ * so `children` start inside `start()`, in the request's async context, after the shell is out.
237
+ */
238
+ function emitHole(node: HoleNode, depth: number, walk: RenderHtmlOptions, out: Buffer): void {
239
+ const sink = walk.holes;
240
+ const inner: RenderHtmlOptions = walk.islands === undefined ? {} : { islands: walk.islands };
241
+ const { children, error, fallback } = node.props;
242
+ if (sink === undefined) {
243
+ emit(children, depth + 1, inner, out);
244
+ return;
245
+ }
246
+ const id = sink.nextId();
247
+ observeEagerPromises(children, new Set());
248
+ const shown = renderAlone(fallback, depth + 1, inner);
249
+ let failed: Rendered | undefined;
250
+ try {
251
+ failed = error === undefined ? undefined : renderAlone(error, depth + 1, inner);
252
+ } catch (thrown) {
253
+ if (typeof shown !== 'string') shown.catch(noop);
254
+ throw thrown;
255
+ }
256
+ const settle = (fallbackHtml: string, errorHtml: string | undefined): string => {
257
+ sink.add({
258
+ id,
259
+ fallback: fallbackHtml,
260
+ ...(errorHtml === undefined ? {} : { error: errorHtml }),
261
+ resolve: (signal) => sink.enter(signal, async () => renderAlone(children, depth + 1, inner)),
262
+ });
263
+ return holeMarker(id, fallbackHtml);
264
+ };
265
+ if (typeof shown === 'string' && typeof failed !== 'object') {
266
+ write(out, settle(shown, failed));
267
+ return;
268
+ }
269
+ slot(
270
+ out,
271
+ Promise.all([shown, failed]).then(([fallbackHtml, errorHtml]) =>
272
+ settle(fallbackHtml, errorHtml),
273
+ ),
274
+ );
275
+ }
package/src/server.ts CHANGED
@@ -49,13 +49,21 @@ export { DEFAULT_ISR_FAILURE_COOLDOWN_MS } from './render-isr-cooldown';
49
49
  export { ISR_LOCALE_PARAM, isrKey, isrRequestUrl, undeclaredQuery } from './render-isr-key';
50
50
  export { isrRouteFor } from './render-isr-routes';
51
51
  export type {
52
+ IsrAnswer,
52
53
  IsrEntry,
53
54
  IsrState,
54
55
  IsrStore,
55
56
  IsrTagFence,
57
+ MemoryIsrStore,
56
58
  MemoryIsrStoreOptions,
57
59
  } from './render-isr-store';
58
- export { DEFAULT_ISR_MAX_ENTRIES, memoryIsrStore } from './render-isr-store';
60
+ export { DEFAULT_ISR_MAX_BYTES, DEFAULT_ISR_MAX_ENTRIES, memoryIsrStore } from './render-isr-store';
61
+ export type {
62
+ IsrDisk,
63
+ IsrDiskEntry,
64
+ StorageIsrStoreOptions,
65
+ } from './render-isr-store-storage';
66
+ export { storageIsrStore } from './render-isr-store-storage';
59
67
  export type {
60
68
  IsrController,
61
69
  IsrControllerOptions,
package/src/surfaces.ts CHANGED
@@ -5,11 +5,13 @@
5
5
  * aspirational. Violations are build errors, resolved through the whole chain.
6
6
  */
7
7
 
8
- import type { RenderMode } from '@ultimat3/core';
8
+ import type { RenderMode, Surface } from '@ultimat3/core';
9
9
  import { byCodeUnit } from './code-unit-order';
10
10
  import { SurfaceBoundaryError } from './errors';
11
11
 
12
- export type Surface = 'site' | 'app' | 'api' | 'shared';
12
+ // Core's route vocabulary. The TYPE rides along for the boundary API's signatures; the `SURFACES`
13
+ // value is imported from `@ultimat3/core` alone (`X_HELPER_COPY` refuses a second import path).
14
+ export type { Surface };
13
15
 
14
16
  /**
15
17
  * The two surfaces a route file lives on. `api/` is a surface for the import boundary only: it holds
@@ -17,8 +19,6 @@ export type Surface = 'site' | 'app' | 'api' | 'shared';
17
19
  */
18
20
  export type RouteSurface = Exclude<Surface, 'api' | 'shared'>;
19
21
 
20
- export const SURFACES = ['site', 'app', 'api', 'shared'] as const;
21
-
22
22
  export interface SurfaceSpec {
23
23
  readonly surface: Surface;
24
24
  readonly defaultMode: RenderMode | null;
@@ -70,6 +70,24 @@ export const SURFACE_SPECS = Object.freeze<Record<Surface, SurfaceSpec>>({
70
70
  });
71
71
 
72
72
  const SURFACE_SEGMENT = /(?:^|\/)(site|app|api|shared)\//;
73
+ /**
74
+ * The surface directly under an app workspace, `apps/<name>/<surface>/`. Read first, so a workspace
75
+ * named like a surface (`apps/api/site/…`) and a root that contains one (`/srv/app/apps/web/…`)
76
+ * resolve to the real surface; `SURFACE_SEGMENT` alone took the first matching segment, and
77
+ * `apps/api/site/x/page.tsx` was surface `api` — `X_ROUTE_FILE_INVALID` for every route there.
78
+ */
79
+ const WORKSPACE_SURFACE = /(?<=^|\/)apps\/[^/]+\/(site|app|api|shared)\//g;
80
+
81
+ /**
82
+ * The LAST `apps/<name>/<surface>/`: an absolute path's checkout root may hold one of its own
83
+ * (`/home/u/apps/acme/app/apps/web/site/…` is surface `site`, never `app`). Lookbehind, not a
84
+ * consumed `/`, so two adjacent matches are both seen.
85
+ */
86
+ const lastWorkspaceSurface = (path: string): RegExpExecArray | null => {
87
+ let last: RegExpExecArray | null = null;
88
+ for (const match of path.matchAll(WORKSPACE_SURFACE)) last = match as RegExpExecArray;
89
+ return last;
90
+ };
73
91
 
74
92
  /** Where the surface segment is, and what follows it — the two halves of one match. */
75
93
  export interface SurfaceLocation {
@@ -86,7 +104,7 @@ export interface SurfaceLocation {
86
104
  */
87
105
  export function locateSurface(file: string): SurfaceLocation | null {
88
106
  const normalized = normalize(file);
89
- const match = SURFACE_SEGMENT.exec(normalized);
107
+ const match = lastWorkspaceSurface(normalized) ?? SURFACE_SEGMENT.exec(normalized);
90
108
  const found = match?.[1];
91
109
  if (found === undefined || match === null) return null;
92
110
  return { surface: found as Surface, rest: normalized.slice(match.index + match[0].length) };