@krate/runtime 0.5.0-alpha.4 → 0.5.0-beta.2

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 (165) hide show
  1. package/dist/action-context.d.ts +5 -1
  2. package/dist/action-context.js +33 -3
  3. package/dist/action-context.test.js +26 -1
  4. package/dist/actions.d.ts +12 -1
  5. package/dist/actions.js +84 -4
  6. package/dist/actions.test.js +61 -1
  7. package/dist/assets-static.d.ts +5 -0
  8. package/dist/assets-static.js +31 -0
  9. package/dist/boundary.d.ts +12 -0
  10. package/dist/boundary.js +53 -13
  11. package/dist/cache-adapter.d.ts +113 -0
  12. package/dist/cache-adapter.js +217 -0
  13. package/dist/cache-adapter.test.d.ts +1 -0
  14. package/dist/cache-adapter.test.js +244 -0
  15. package/dist/cache-redis.d.ts +27 -0
  16. package/dist/cache-redis.js +110 -0
  17. package/dist/cache-scope.d.ts +25 -9
  18. package/dist/cache-scope.js +64 -13
  19. package/dist/cache.d.ts +1 -0
  20. package/dist/cache.js +3 -3
  21. package/dist/cache.test.js +16 -0
  22. package/dist/class-component.js +6 -0
  23. package/dist/class-component.test.js +53 -2
  24. package/dist/class-helpers.d.ts +4 -4
  25. package/dist/class-helpers.js +357 -32
  26. package/dist/class-helpers.test.d.ts +1 -0
  27. package/dist/class-helpers.test.js +169 -0
  28. package/dist/context.d.ts +16 -2
  29. package/dist/context.js +44 -3
  30. package/dist/dev-overlay.js +85 -12
  31. package/dist/dev-overlay.test.js +22 -0
  32. package/dist/dom.d.ts +15 -0
  33. package/dist/dom.js +97 -3
  34. package/dist/effect-errors.test.d.ts +1 -0
  35. package/dist/effect-errors.test.js +163 -0
  36. package/dist/effects.d.ts +8 -0
  37. package/dist/effects.js +13 -0
  38. package/dist/error-overlay.js +7 -7
  39. package/dist/handler-html.d.ts +63 -0
  40. package/dist/handler-html.js +285 -0
  41. package/dist/handler-html.test.d.ts +1 -0
  42. package/dist/handler-html.test.js +256 -0
  43. package/dist/handler-routing.d.ts +83 -0
  44. package/dist/handler-routing.js +579 -0
  45. package/dist/handler-routing.test.d.ts +1 -0
  46. package/dist/handler-routing.test.js +99 -0
  47. package/dist/handler-segments.d.ts +43 -0
  48. package/dist/handler-segments.js +115 -0
  49. package/dist/handler-segments.test.d.ts +1 -0
  50. package/dist/handler-segments.test.js +217 -0
  51. package/dist/head-tags.d.ts +51 -0
  52. package/dist/head-tags.js +329 -0
  53. package/dist/head-tags.test.d.ts +1 -0
  54. package/dist/head-tags.test.js +131 -0
  55. package/dist/highlight-bind.d.ts +42 -0
  56. package/dist/highlight-bind.js +176 -0
  57. package/dist/highlight-bind.test.d.ts +1 -0
  58. package/dist/highlight-bind.test.js +124 -0
  59. package/dist/highlight.d.ts +93 -0
  60. package/dist/highlight.js +426 -0
  61. package/dist/highlight.test.d.ts +1 -0
  62. package/dist/highlight.test.js +56 -0
  63. package/dist/hints.d.ts +19 -0
  64. package/dist/hints.js +97 -0
  65. package/dist/hook-args.d.ts +7 -0
  66. package/dist/hook-args.js +10 -0
  67. package/dist/htmlspec-attributes.d.ts +1 -0
  68. package/dist/htmlspec-attributes.js +159 -0
  69. package/dist/index.d.ts +4 -0
  70. package/dist/index.js +3 -0
  71. package/dist/jsx-types.d.ts +11 -0
  72. package/dist/krate-core.js +2 -0
  73. package/dist/krate-dev.js +75 -12
  74. package/dist/krate-f-actions.js +2 -0
  75. package/dist/krate-f-classes.js +8 -0
  76. package/dist/krate-f-helpers.js +2 -0
  77. package/dist/krate-f-highlight.js +2 -0
  78. package/dist/krate-f-list.js +2 -0
  79. package/dist/krate-f-navigation.js +2 -0
  80. package/dist/krate-f-router-lite.js +2 -0
  81. package/dist/krate-f-router.js +2 -0
  82. package/dist/krate-features.json +493 -0
  83. package/dist/krate-hydrate-lite.js +5 -5
  84. package/dist/krate-hydrate.js +5 -5
  85. package/dist/krate-runtime.js +5 -5
  86. package/dist/list.js +4 -2
  87. package/dist/metadata-routes.d.ts +75 -0
  88. package/dist/metadata-routes.js +76 -0
  89. package/dist/metadata.d.ts +222 -0
  90. package/dist/metadata.js +452 -0
  91. package/dist/metadata.test.d.ts +1 -0
  92. package/dist/metadata.test.js +167 -0
  93. package/dist/navigation-server.d.ts +27 -0
  94. package/dist/navigation-server.js +90 -0
  95. package/dist/navigation.d.ts +37 -0
  96. package/dist/navigation.js +195 -0
  97. package/dist/navigation.test.d.ts +1 -0
  98. package/dist/navigation.test.js +130 -0
  99. package/dist/node-server.d.ts +22 -0
  100. package/dist/node-server.js +436 -0
  101. package/dist/node-server.test.d.ts +1 -0
  102. package/dist/node-server.test.js +492 -0
  103. package/dist/og-files.d.ts +2 -0
  104. package/dist/og-files.js +19 -0
  105. package/dist/og.d.ts +56 -0
  106. package/dist/og.js +156 -0
  107. package/dist/patterns.test.d.ts +1 -0
  108. package/dist/patterns.test.js +98 -0
  109. package/dist/react.d.ts +47 -0
  110. package/dist/react.js +59 -1
  111. package/dist/react19.test.d.ts +1 -0
  112. package/dist/react19.test.js +176 -0
  113. package/dist/reactivity-core.test.d.ts +1 -0
  114. package/dist/reactivity-core.test.js +152 -0
  115. package/dist/reconcile.js +4 -2
  116. package/dist/request-context.d.ts +23 -0
  117. package/dist/request-context.js +45 -0
  118. package/dist/resp.d.ts +55 -0
  119. package/dist/resp.js +239 -0
  120. package/dist/router-layout.test.js +70 -0
  121. package/dist/router-nav.test.js +65 -0
  122. package/dist/router-speculation.test.d.ts +1 -0
  123. package/dist/router-speculation.test.js +25 -0
  124. package/dist/router-styles.test.d.ts +1 -0
  125. package/dist/router-styles.test.js +98 -0
  126. package/dist/router.js +175 -36
  127. package/dist/segmented-lru.d.ts +19 -0
  128. package/dist/segmented-lru.js +87 -0
  129. package/dist/server-async.test.js +43 -1
  130. package/dist/server-handler.d.ts +165 -0
  131. package/dist/server-handler.js +1826 -0
  132. package/dist/server-handler.test.d.ts +1 -0
  133. package/dist/server-handler.test.js +522 -0
  134. package/dist/server-highlight.test.d.ts +1 -0
  135. package/dist/server-highlight.test.js +32 -0
  136. package/dist/server-renderer.js +165 -720
  137. package/dist/server-renderer.test.d.ts +1 -0
  138. package/dist/server-renderer.test.js +266 -0
  139. package/dist/server.d.ts +13 -1
  140. package/dist/server.js +131 -16
  141. package/dist/server.test.js +20 -0
  142. package/dist/sha256.d.ts +1 -0
  143. package/dist/sha256.js +66 -0
  144. package/dist/sha256.test.d.ts +1 -0
  145. package/dist/sha256.test.js +13 -0
  146. package/dist/shared-isr.d.ts +31 -0
  147. package/dist/shared-isr.js +142 -0
  148. package/dist/signal.d.ts +3 -2
  149. package/dist/signal.js +163 -23
  150. package/dist/slots.js +12 -1
  151. package/dist/ssr-core-behavior.test.d.ts +1 -0
  152. package/dist/ssr-core-behavior.test.js +620 -0
  153. package/dist/ssr-core.d.ts +175 -0
  154. package/dist/ssr-core.js +940 -0
  155. package/dist/ssr-core.test.d.ts +1 -0
  156. package/dist/ssr-core.test.js +324 -0
  157. package/dist/static-memory.d.ts +3 -0
  158. package/dist/static-memory.js +47 -0
  159. package/dist/static-memory.test.d.ts +1 -0
  160. package/dist/static-memory.test.js +26 -0
  161. package/dist/test-redis.d.ts +12 -0
  162. package/dist/test-redis.js +131 -0
  163. package/dist/use-id.d.ts +8 -0
  164. package/dist/use-id.js +40 -0
  165. package/package.json +30 -2
@@ -108,6 +108,9 @@ export function cacheRuntime() {
108
108
  const tags = Array.isArray(payload.tags) ? payload.tags.filter((t) => typeof t === 'string') : [];
109
109
  return { dataEntries: tags.length ? created.dataCache.invalidateTags(tags) : 0 };
110
110
  },
111
+ async invalidateShared(tags) {
112
+ return created.shared && tags.length ? created.shared.deleteTags(tags) : 0;
113
+ },
111
114
  };
112
115
  rt = created;
113
116
  g[STATE_KEY] = rt;
@@ -184,6 +187,33 @@ function goBridge() {
184
187
  ? g
185
188
  : null;
186
189
  }
190
+ /**
191
+ * Reads a JSON value from the data cache; undefined on a miss. With a shared
192
+ * cache the instances' common store answers; when it cannot, this process's own
193
+ * cache does.
194
+ */
195
+ export async function dataCacheGetJSONAsync(key) {
196
+ const shared = cacheRuntime().shared;
197
+ if (shared && !goBridge()) {
198
+ const r = await shared.get(key);
199
+ if (r.ok)
200
+ return r.value;
201
+ }
202
+ return dataCacheGetJSON(key);
203
+ }
204
+ /** Stores a JSON value in the shared cache when there is one, else in this process's cache. */
205
+ export async function dataCacheSetJSONAsync(key, json, ttlSeconds, tags, epoch) {
206
+ const shared = cacheRuntime().shared;
207
+ if (shared && !goBridge()) {
208
+ const scope = currentRenderScope();
209
+ const all = scope ? [...tags, routeDataTag(scope.route)] : tags;
210
+ if (cacheRuntime().epoch !== epoch)
211
+ return;
212
+ if (await shared.set(key, json, ttlSeconds, all))
213
+ return;
214
+ }
215
+ dataCacheSetJSON(key, json, ttlSeconds, tags, epoch);
216
+ }
187
217
  /** Reads a JSON value from the data cache; undefined on a miss. */
188
218
  export function dataCacheGetJSON(key) {
189
219
  const go = goBridge();
@@ -257,6 +287,13 @@ function fetchCacheKey(method, url, init) {
257
287
  * `next.revalidate: 0` bypass the cache and make the render uncacheable.
258
288
  * Requests without these options are passed through untouched.
259
289
  */
290
+ function responseOf(c, method) {
291
+ return new Response(method === 'HEAD' ? null : fromBase64(c.body), {
292
+ status: c.status,
293
+ statusText: c.statusText,
294
+ headers: c.headers,
295
+ });
296
+ }
260
297
  export function patchFetch() {
261
298
  const rt = cacheRuntime();
262
299
  const g = globalThis;
@@ -264,6 +301,7 @@ export function patchFetch() {
264
301
  return;
265
302
  const original = g.fetch.bind(globalThis);
266
303
  rt.fetchPatched = true;
304
+ const inflight = new Map();
267
305
  const wrapped = async (input, init) => {
268
306
  const next = init && init.next;
269
307
  const mode = init && init.cache;
@@ -287,25 +325,38 @@ export function patchFetch() {
287
325
  if (ttl === 0 || (method !== 'GET' && method !== 'HEAD'))
288
326
  return original(input, plainInit);
289
327
  const key = fetchCacheKey(method, requestURL(input), plainInit);
290
- const hit = dataCacheGetJSON(key);
291
- if (hit !== undefined) {
292
- const c = JSON.parse(hit);
293
- return new Response(method === 'HEAD' ? null : fromBase64(c.body), {
294
- status: c.status,
295
- statusText: c.statusText,
296
- headers: c.headers,
297
- });
328
+ const hit = await dataCacheGetJSONAsync(key);
329
+ if (hit !== undefined)
330
+ return responseOf(JSON.parse(hit), method);
331
+ // Concurrent misses for one request share a single upstream call, so a
332
+ // page and its generateMetadata that read the same URL ask it once.
333
+ const pending = inflight.get(key);
334
+ if (pending) {
335
+ const shared = await pending;
336
+ return shared.entry ? responseOf(shared.entry, method) : original(input, plainInit);
298
337
  }
299
338
  const epoch = rt.epoch;
300
- const res = await original(input, plainInit);
301
- if (res.ok) {
339
+ const fetching = (async () => {
340
+ const res = await original(input, plainInit);
341
+ if (!res.ok)
342
+ return { res, entry: null };
302
343
  const bytes = new Uint8Array(await res.clone().arrayBuffer());
303
344
  const headers = [];
304
- res.headers.forEach((v, k) => headers.push([k, v]));
345
+ res.headers.forEach((v, k) => {
346
+ if (k.toLowerCase() !== 'set-cookie')
347
+ headers.push([k, v]);
348
+ });
305
349
  const entry = { status: res.status, statusText: res.statusText, headers, body: toBase64(bytes) };
306
- dataCacheSetJSON(key, JSON.stringify(entry), ttl, tags, epoch);
350
+ await dataCacheSetJSONAsync(key, JSON.stringify(entry), ttl, tags, epoch);
351
+ return { res, entry };
352
+ })();
353
+ inflight.set(key, fetching);
354
+ try {
355
+ return (await fetching).res;
356
+ }
357
+ finally {
358
+ inflight.delete(key);
307
359
  }
308
- return res;
309
360
  };
310
361
  g.fetch = wrapped;
311
362
  }
package/dist/cache.d.ts CHANGED
@@ -33,6 +33,7 @@ export declare function sendRevalidation(payload: RevalidatePayload): Promise<Re
33
33
  export declare function revalidatePath(path: string, type?: RevalidatePathType): void;
34
34
  /** Invalidates every cached page render, region and data entry that read `tag`. */
35
35
  export declare function revalidateTag(tag: string): void;
36
+ export type { CacheAdapter, CacheSetOptions, CacheSpec } from './cache-adapter.js';
36
37
  /** Options for `unstable_cache`. */
37
38
  export interface UnstableCacheOptions {
38
39
  /** Tags that `revalidateTag` can invalidate this entry by. */
package/dist/cache.js CHANGED
@@ -12,7 +12,7 @@
12
12
  * function's JSON-serializable result.
13
13
  * - `unstable_noStore()` marks the current render uncacheable.
14
14
  */
15
- import { cacheRuntime, currentRenderScope, currentRevalidateScope, dataCacheGetJSON, dataCacheSetJSON, markNoStore, recordCacheRead, } from './cache-scope.js';
15
+ import { cacheRuntime, currentRenderScope, currentRevalidateScope, dataCacheGetJSONAsync, dataCacheSetJSONAsync, markNoStore, recordCacheRead, } from './cache-scope.js';
16
16
  function env(name) {
17
17
  const proc = globalThis.process;
18
18
  return (proc && proc.env && proc.env[name]) || '';
@@ -121,7 +121,7 @@ export function unstable_cache(fn, keyParts, options = {}) {
121
121
  if (ttl === 0)
122
122
  return fn(...args);
123
123
  const key = 'uc:' + base + '\u0000' + JSON.stringify(args);
124
- const hit = dataCacheGetJSON(key);
124
+ const hit = await dataCacheGetJSONAsync(key);
125
125
  if (hit !== undefined)
126
126
  return JSON.parse(hit);
127
127
  const running = pending.get(key);
@@ -134,7 +134,7 @@ export function unstable_cache(fn, keyParts, options = {}) {
134
134
  if (json === undefined) {
135
135
  throw new TypeError('unstable_cache() results must be JSON-serializable (got undefined or a function)');
136
136
  }
137
- dataCacheSetJSON(key, json, ttl, tags, epoch);
137
+ await dataCacheSetJSONAsync(key, json, ttl, tags, epoch);
138
138
  return value;
139
139
  })();
140
140
  pending.set(key, p);
@@ -189,6 +189,22 @@ describe('revalidatePath / revalidateTag', () => {
189
189
  });
190
190
  });
191
191
  describe('patchFetch', () => {
192
+ it('never replays Set-Cookie from a cached response', async () => {
193
+ const base = vi.fn(async () => new Response('body', {
194
+ status: 200,
195
+ headers: { 'set-cookie': 'sid=secret', 'x-test': 'yes' },
196
+ }));
197
+ vi.stubGlobal('fetch', base);
198
+ cacheRuntime().fetchPatched = false;
199
+ patchFetch();
200
+ const read = () => fetch('http://data/session', { next: { tags: ['session'], revalidate: 60 } });
201
+ const first = await withCacheScope('/p', async () => read());
202
+ expect(first.result.headers.get('x-test')).toBe('yes');
203
+ const second = await withCacheScope('/p', async () => read());
204
+ expect(second.result.headers.get('set-cookie')).toBeNull();
205
+ expect(second.result.headers.get('x-test')).toBe('yes');
206
+ expect(base).toHaveBeenCalledTimes(1);
207
+ });
192
208
  it('caches tagged GET responses, records tags, and bypasses no-store', async () => {
193
209
  let n = 0;
194
210
  const base = vi.fn(async () => new Response(`body-${++n}`, { status: 200, headers: { 'x-n': String(n) } }));
@@ -382,6 +382,12 @@ class Controller {
382
382
  return false;
383
383
  if (this.catching)
384
384
  return true;
385
+ // The boundary already shows its fallback: an error from there is the
386
+ // fallback's own, which React hands to the next boundary up (a boundary
387
+ // never catches what its own render output throws). A reset clears inError
388
+ // before the children mount again, so their errors are caught as usual.
389
+ if (owner.inError)
390
+ return false;
385
391
  this.catching = true;
386
392
  try {
387
393
  // React logs every error a boundary catches.
@@ -1,6 +1,6 @@
1
1
  import { afterEach, describe, expect, it, vi } from 'vitest';
2
- import { createEffect, createSignal, disposeAll } from './signal.js';
3
- import { __krateOwn, __krateOwner, __krateCondPre, __krateCondPost, __krateOnError } from './boundary.js';
2
+ import { createEffect, createSignal, disposeAll, krateDisposeExcept, krateEnterScope, krateLeaveScope } from './signal.js';
3
+ import { __krateOwn, __krateOwner, __krateCondPre, __krateCondPost, __krateOnError, handleError } from './boundary.js';
4
4
  import { __krateClass } from './class-component.js';
5
5
  // Lets the effect flush, the render phase and the commit phase run.
6
6
  const settle = () => new Promise((r) => setTimeout(r, 0));
@@ -385,6 +385,31 @@ describe('error boundaries', () => {
385
385
  await settle();
386
386
  expect(log2.filter((l) => l.includes('gDSFE'))).toEqual(['O gDSFE fallback broke']);
387
387
  });
388
+ it('does not catch an error raised while the boundary already shows its fallback', async () => {
389
+ const log = [];
390
+ boundary('Outer', {}, log, 'Outer');
391
+ boundary('Inner', { p: 'Outer' }, log, 'Inner');
392
+ const [fail, setFail] = createSignal(false);
393
+ __krateOwn('Page', { p: 'Inner', n: 'Page' }, () => {
394
+ createEffect(() => {
395
+ if (fail())
396
+ throw new Error('page failed');
397
+ });
398
+ });
399
+ await settle();
400
+ setFail(true);
401
+ await settle();
402
+ // (An update-phase error runs getDerivedStateFromError twice, as in React 18.)
403
+ expect(new Set(log.filter((l) => l.includes('gDSFE')))).toEqual(new Set(['Inner gDSFE page failed']));
404
+ expect(__krateOwner('Inner').inError).toBe(true);
405
+ // The fallback is the boundary's own render output: what it throws is not
406
+ // the boundary's to catch.
407
+ handleError(new Error('fallback failed'), __krateOwner('Page'));
408
+ await settle();
409
+ const caught = log.filter((l) => l.includes('gDSFE'));
410
+ expect(caught).toContain('Outer gDSFE fallback failed');
411
+ expect(caught).not.toContain('Inner gDSFE fallback failed');
412
+ });
388
413
  it('reports uncaught errors and unmounts only the failing component', async () => {
389
414
  const spy = vi.spyOn(console, 'error').mockImplementation(() => { });
390
415
  let siblingRan = false;
@@ -409,3 +434,29 @@ describe('error boundaries', () => {
409
434
  expect(routed).toBe(false);
410
435
  });
411
436
  });
437
+ describe('owner teardown by route scope', () => {
438
+ it('keeps the owners of a kept layout and drops the page owners', async () => {
439
+ const log = [];
440
+ krateEnterScope('_lroot_');
441
+ __krateOwn('Layout', { n: 'Layout' }, () => {
442
+ classScope({}, {}, { componentWillUnmount: () => log.push('layout unmount') });
443
+ });
444
+ krateLeaveScope();
445
+ __krateOwn('Page', { p: 'Layout', n: 'Page' }, () => {
446
+ classScope({}, {}, { componentWillUnmount: () => log.push('page unmount') });
447
+ });
448
+ await settle();
449
+ expect(__krateOwner('Page').state).toBe('mounted');
450
+ // A soft navigation keeps the layout: only page-scope owners go.
451
+ krateDisposeExcept(['_lroot_']);
452
+ expect(log).toEqual(['page unmount']);
453
+ expect(__krateOwner('Page')).toBeNull();
454
+ const layout = __krateOwner('Layout');
455
+ expect(layout.state).toBe('mounted');
456
+ expect(layout.children).toHaveLength(0);
457
+ // A full teardown drops everything.
458
+ disposeAll();
459
+ expect(log).toEqual(['page unmount', 'layout unmount']);
460
+ expect(__krateOwner('Layout')).toBeNull();
461
+ });
462
+ });
@@ -2,10 +2,10 @@ export type ClassValue = string | number | boolean | null | undefined | ClassVal
2
2
  /** `clsx` - conditional class names from strings, arrays, and objects. */
3
3
  export declare function clsx(...inputs: ClassValue[]): string;
4
4
  /**
5
- * Merge conflicting Tailwind utilities. This is a deliberately small subset:
6
- * later classes win over earlier ones for the same property prefix. Full
7
- * `tailwind-merge` semantics (variant/modifier aware) are out of scope; the
8
- * compiler folds literal calls and this covers dynamic joins.
5
+ * Merge conflicting Tailwind utilities: later classes win over earlier ones in
6
+ * the same utility group and variant chain (`hover:p-2` never conflicts with
7
+ * `p-4`). Classes the helper does not recognise only dedupe on an exact match.
8
+ * The compiler folds literal calls; this covers dynamic joins.
9
9
  */
10
10
  export declare function twMerge(...inputs: ClassValue[]): string;
11
11
  /** `cn` - `twMerge` over `clsx`, the shadcn/ui convention. */