@krate/runtime 0.5.0-beta.1 → 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 (134) hide show
  1. package/dist/actions.js +2 -1
  2. package/dist/assets-static.d.ts +5 -0
  3. package/dist/assets-static.js +31 -0
  4. package/dist/boundary.d.ts +12 -0
  5. package/dist/boundary.js +53 -13
  6. package/dist/cache-adapter.d.ts +113 -0
  7. package/dist/cache-adapter.js +217 -0
  8. package/dist/cache-adapter.test.d.ts +1 -0
  9. package/dist/cache-adapter.test.js +244 -0
  10. package/dist/cache-redis.d.ts +27 -0
  11. package/dist/cache-redis.js +110 -0
  12. package/dist/cache-scope.d.ts +25 -9
  13. package/dist/cache-scope.js +60 -12
  14. package/dist/cache.d.ts +1 -0
  15. package/dist/cache.js +3 -3
  16. package/dist/class-component.js +6 -0
  17. package/dist/class-component.test.js +53 -2
  18. package/dist/dev-overlay.js +10 -10
  19. package/dist/dom.d.ts +8 -0
  20. package/dist/dom.js +28 -0
  21. package/dist/effect-errors.test.d.ts +1 -0
  22. package/dist/effect-errors.test.js +163 -0
  23. package/dist/effects.d.ts +8 -0
  24. package/dist/effects.js +13 -0
  25. package/dist/error-overlay.js +4 -4
  26. package/dist/handler-html.d.ts +63 -0
  27. package/dist/handler-html.js +285 -0
  28. package/dist/handler-html.test.d.ts +1 -0
  29. package/dist/handler-html.test.js +256 -0
  30. package/dist/handler-routing.d.ts +83 -0
  31. package/dist/handler-routing.js +579 -0
  32. package/dist/handler-routing.test.d.ts +1 -0
  33. package/dist/handler-routing.test.js +99 -0
  34. package/dist/handler-segments.d.ts +43 -0
  35. package/dist/handler-segments.js +115 -0
  36. package/dist/handler-segments.test.d.ts +1 -0
  37. package/dist/handler-segments.test.js +217 -0
  38. package/dist/head-tags.d.ts +51 -0
  39. package/dist/head-tags.js +329 -0
  40. package/dist/head-tags.test.d.ts +1 -0
  41. package/dist/head-tags.test.js +131 -0
  42. package/dist/highlight-bind.d.ts +42 -0
  43. package/dist/highlight-bind.js +176 -0
  44. package/dist/highlight-bind.test.d.ts +1 -0
  45. package/dist/highlight-bind.test.js +124 -0
  46. package/dist/highlight.d.ts +93 -0
  47. package/dist/highlight.js +426 -0
  48. package/dist/highlight.test.d.ts +1 -0
  49. package/dist/highlight.test.js +56 -0
  50. package/dist/hints.d.ts +19 -0
  51. package/dist/hints.js +97 -0
  52. package/dist/index.d.ts +3 -0
  53. package/dist/index.js +2 -0
  54. package/dist/jsx-types.d.ts +11 -0
  55. package/dist/krate-core.js +1 -1
  56. package/dist/krate-dev.js +10 -10
  57. package/dist/krate-f-actions.js +1 -1
  58. package/dist/krate-f-classes.js +5 -5
  59. package/dist/krate-f-highlight.js +2 -0
  60. package/dist/krate-f-list.js +1 -1
  61. package/dist/krate-f-navigation.js +2 -0
  62. package/dist/krate-f-router.js +1 -1
  63. package/dist/krate-features.json +254 -0
  64. package/dist/krate-hydrate-lite.js +5 -5
  65. package/dist/krate-hydrate.js +5 -5
  66. package/dist/krate-runtime.js +5 -5
  67. package/dist/list.js +4 -2
  68. package/dist/metadata-routes.d.ts +75 -0
  69. package/dist/metadata-routes.js +76 -0
  70. package/dist/metadata.d.ts +222 -0
  71. package/dist/metadata.js +452 -0
  72. package/dist/metadata.test.d.ts +1 -0
  73. package/dist/metadata.test.js +167 -0
  74. package/dist/navigation-server.d.ts +27 -0
  75. package/dist/navigation-server.js +90 -0
  76. package/dist/navigation.d.ts +37 -0
  77. package/dist/navigation.js +195 -0
  78. package/dist/navigation.test.d.ts +1 -0
  79. package/dist/navigation.test.js +130 -0
  80. package/dist/node-server.d.ts +22 -0
  81. package/dist/node-server.js +436 -0
  82. package/dist/node-server.test.d.ts +1 -0
  83. package/dist/node-server.test.js +492 -0
  84. package/dist/og-files.d.ts +2 -0
  85. package/dist/og-files.js +19 -0
  86. package/dist/og.d.ts +56 -0
  87. package/dist/og.js +156 -0
  88. package/dist/react.d.ts +47 -0
  89. package/dist/react.js +59 -1
  90. package/dist/react19.test.d.ts +1 -0
  91. package/dist/react19.test.js +176 -0
  92. package/dist/request-context.d.ts +23 -0
  93. package/dist/request-context.js +45 -0
  94. package/dist/resp.d.ts +55 -0
  95. package/dist/resp.js +239 -0
  96. package/dist/router-layout.test.js +70 -0
  97. package/dist/router-nav.test.js +27 -0
  98. package/dist/router.js +59 -4
  99. package/dist/segmented-lru.d.ts +19 -0
  100. package/dist/segmented-lru.js +87 -0
  101. package/dist/server-async.test.js +23 -1
  102. package/dist/server-handler.d.ts +165 -0
  103. package/dist/server-handler.js +1826 -0
  104. package/dist/server-handler.test.d.ts +1 -0
  105. package/dist/server-handler.test.js +522 -0
  106. package/dist/server-highlight.test.d.ts +1 -0
  107. package/dist/server-highlight.test.js +32 -0
  108. package/dist/server-renderer.js +146 -788
  109. package/dist/server-renderer.test.d.ts +1 -0
  110. package/dist/server-renderer.test.js +266 -0
  111. package/dist/server.d.ts +12 -1
  112. package/dist/server.js +42 -6
  113. package/dist/sha256.d.ts +1 -0
  114. package/dist/sha256.js +66 -0
  115. package/dist/sha256.test.d.ts +1 -0
  116. package/dist/sha256.test.js +13 -0
  117. package/dist/shared-isr.d.ts +31 -0
  118. package/dist/shared-isr.js +142 -0
  119. package/dist/signal.js +63 -8
  120. package/dist/ssr-core-behavior.test.d.ts +1 -0
  121. package/dist/ssr-core-behavior.test.js +620 -0
  122. package/dist/ssr-core.d.ts +175 -0
  123. package/dist/ssr-core.js +940 -0
  124. package/dist/ssr-core.test.d.ts +1 -0
  125. package/dist/ssr-core.test.js +324 -0
  126. package/dist/static-memory.d.ts +3 -0
  127. package/dist/static-memory.js +47 -0
  128. package/dist/static-memory.test.d.ts +1 -0
  129. package/dist/static-memory.test.js +26 -0
  130. package/dist/test-redis.d.ts +12 -0
  131. package/dist/test-redis.js +131 -0
  132. package/dist/use-id.d.ts +8 -0
  133. package/dist/use-id.js +40 -0
  134. package/package.json +29 -1
@@ -0,0 +1,244 @@
1
+ // @vitest-environment node
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
4
+ import { CacheGuard, MemoryAdapter, SharedDataCache, cacheSpecFromConfig, cacheSpecFromEnv, installCacheAdapter, loadCacheAdapter } from './cache-adapter';
5
+ import { RedisAdapter } from './cache-redis';
6
+ import { SharedIsrStore, isrStoreFor } from './shared-isr';
7
+ import { createSSRCore, MemoryIsrStore } from './ssr-core';
8
+ import { cacheRuntime, installRenderStore, markNoStore, patchFetch } from './cache-scope';
9
+ import { parseRedisURL } from './resp';
10
+ import { startFakeRedis } from './test-redis';
11
+ import { jsx } from './server';
12
+ installRenderStore(new AsyncLocalStorage());
13
+ let redis;
14
+ beforeEach(async () => {
15
+ redis = await startFakeRedis();
16
+ vi.spyOn(console, 'warn').mockImplementation(() => { });
17
+ vi.spyOn(console, 'error').mockImplementation(() => { });
18
+ });
19
+ afterEach(async () => {
20
+ vi.restoreAllMocks();
21
+ await redis.kill();
22
+ cacheRuntime().shared = undefined;
23
+ });
24
+ const url = () => `redis://127.0.0.1:${redis.port}/0`;
25
+ const adapter = () => new RedisAdapter({ url: url(), timeoutMs: 200 });
26
+ describe('parseRedisURL', () => {
27
+ it('reads host, port, credentials, db and TLS', () => {
28
+ expect(parseRedisURL('redis://u:p%40ss@cache.example:6380/2')).toMatchObject({ host: 'cache.example', port: 6380, username: 'u', password: 'p@ss', db: 2, tls: false });
29
+ expect(parseRedisURL('rediss://cache.example')).toMatchObject({ port: 6379, tls: true });
30
+ expect(() => parseRedisURL('http://x')).toThrow(/protocol/);
31
+ });
32
+ });
33
+ describe('RedisAdapter', () => {
34
+ it('stores values with a ttl and tags, and deletes by tag', async () => {
35
+ const a = adapter();
36
+ await a.set('one', '1', { ttlSeconds: 30, tags: ['t:a', 't:b'] });
37
+ await a.set('two', '2', { tags: ['t:a'] });
38
+ expect(await a.get('one')).toBe('1');
39
+ expect(await a.get('missing')).toBeNull();
40
+ expect((await a.keysByTag('t:a')).sort()).toEqual(['one', 'two']);
41
+ expect(await a.deleteByTags(['t:a'])).toBe(2);
42
+ expect(await a.get('one')).toBeNull();
43
+ expect(await a.get('two')).toBeNull();
44
+ expect(redis.commands.some((c) => c[0] === 'SET' && c[3] === 'EX' && c[4] === '30')).toBe(true);
45
+ await a.close();
46
+ });
47
+ it('keeps apps apart with a prefix', async () => {
48
+ const a = new RedisAdapter({ url: url(), prefix: 'one:' });
49
+ const b = new RedisAdapter({ url: url(), prefix: 'two:' });
50
+ await a.set('k', 'A');
51
+ expect(await b.get('k')).toBeNull();
52
+ expect(redis.keys()).toEqual(['one:k:k']);
53
+ await a.close();
54
+ await b.close();
55
+ });
56
+ it('authenticates', async () => {
57
+ const guarded = await startFakeRedis({ password: 's3cret' });
58
+ try {
59
+ const ok = new RedisAdapter({ url: `redis://:s3cret@127.0.0.1:${guarded.port}` });
60
+ await ok.set('k', 'v');
61
+ expect(await ok.get('k')).toBe('v');
62
+ const bad = new RedisAdapter({ url: `redis://:nope@127.0.0.1:${guarded.port}` });
63
+ await expect(bad.get('k')).rejects.toThrow(/WRONGPASS/);
64
+ await ok.close();
65
+ await bad.close();
66
+ }
67
+ finally {
68
+ await guarded.kill();
69
+ }
70
+ });
71
+ it('delivers published messages to subscribers on other connections', async () => {
72
+ const a = adapter();
73
+ const b = adapter();
74
+ const got = [];
75
+ const stop = await b.subscribe('invalidate', (m) => got.push(m));
76
+ await a.publish('invalidate', '{"tags":["x"]}');
77
+ await vi.waitFor(() => expect(got).toEqual(['{"tags":["x"]}']));
78
+ stop();
79
+ await a.close();
80
+ await b.close();
81
+ });
82
+ it('tells a subscriber to flush everything after its connection was lost', async () => {
83
+ const a = adapter();
84
+ const got = [];
85
+ await a.subscribe('invalidate', (m) => got.push(m));
86
+ await redis.kill();
87
+ await redis.revive();
88
+ await vi.waitFor(() => expect(got).toContain('*'), { timeout: 4000 });
89
+ await a.close();
90
+ });
91
+ });
92
+ describe('SharedIsrStore across instances', () => {
93
+ const entry = (html, tags) => ({ html, timestamp: Date.now(), tags });
94
+ it('serves what another instance stored and invalidates for both', async () => {
95
+ const a = new SharedIsrStore(new CacheGuard(adapter()));
96
+ const b = new SharedIsrStore(new CacheGuard(adapter()));
97
+ await a.set('/p/[id]?id=1', entry('<p>1</p>', ['posts']));
98
+ await a.set('/p/[id]?id=2', entry('<p>2</p>', ['users']));
99
+ expect((await b.get('/p/[id]?id=1'))?.html).toBe('<p>1</p>');
100
+ expect(await b.deleteTags(['posts'])).toBeGreaterThan(0);
101
+ expect(await a.get('/p/[id]?id=1')).toBeUndefined();
102
+ expect((await a.get('/p/[id]?id=2'))?.html).toBe('<p>2</p>');
103
+ expect(await b.deleteRoute('/p/[id]')).toBeGreaterThan(0);
104
+ expect(await a.get('/p/[id]?id=2')).toBeUndefined();
105
+ });
106
+ it('lists the variants of a route and deletes one params variant', async () => {
107
+ const s = new SharedIsrStore(new CacheGuard(adapter()));
108
+ await s.set('/p/[id]?id=1', entry('1'));
109
+ await s.set('/p/[id]?id=1#q=a', entry('1a'));
110
+ await s.set('/p/[id]?id=2', entry('2'));
111
+ expect((await s.entriesForRoute('/p/[id]')).map(([k]) => k).sort()).toEqual(['/p/[id]?id=1', '/p/[id]?id=1#q=a', '/p/[id]?id=2']);
112
+ await s.deleteVariant('/p/[id]', { id: '1' });
113
+ expect((await s.entriesForRoute('/p/[id]')).map(([k]) => k)).toEqual(['/p/[id]?id=2']);
114
+ });
115
+ });
116
+ describe('a cache that fails never fails a request', () => {
117
+ const page = (route, extra = {}) => ({ route, source: route + '.tsx', mode: 'isr', bundlePath: route, revalidate: 60, ...extra });
118
+ const core = (store, render) => createSSRCore({
119
+ manifest: { pages: [page('/p')], regions: {} },
120
+ isrStore: store,
121
+ loadPageModule: async () => ({ default: () => jsx('p', { children: render() }) }),
122
+ loadRuntimeRenderer: () => () => '',
123
+ });
124
+ it('renders when Redis is down, falls back to process memory, and recovers', async () => {
125
+ let n = 0;
126
+ const guard = new CacheGuard(adapter(), 100, 2, 300);
127
+ const c = core(new SharedIsrStore(guard), () => `render ${++n}`);
128
+ const req = { route: '/p', url: '/p', method: 'GET', headers: {} };
129
+ expect((await c.renderPage(req)).cacheStatus).toBe('miss');
130
+ expect((await c.renderPage(req)).cacheStatus).toBe('hit');
131
+ await redis.kill();
132
+ // Down: the page still renders (and is cached in memory for this instance).
133
+ const down = await c.renderPage(req);
134
+ expect(down.status).toBe(200);
135
+ expect(down.html).toContain('<p>');
136
+ for (let i = 0; i < 5; i++)
137
+ expect((await c.renderPage(req)).status).toBe(200);
138
+ expect(guard.healthy).toBe(false);
139
+ await redis.revive();
140
+ await vi.waitFor(async () => expect((await c.renderPage(req)).status).toBe(200));
141
+ await new Promise((r) => setTimeout(r, 350));
142
+ expect((await c.renderPage(req)).status).toBe(200);
143
+ expect(guard.healthy).toBe(true);
144
+ });
145
+ it('gives up on a cache that hangs after the timeout instead of waiting', async () => {
146
+ const never = () => new Promise(() => { });
147
+ const hang = {
148
+ name: 'hang',
149
+ get: () => never(),
150
+ set: () => never(),
151
+ delete: () => never(),
152
+ keysByTag: () => never(),
153
+ deleteByTags: () => never(),
154
+ publish: () => never(),
155
+ subscribe: () => never(),
156
+ close: async () => { },
157
+ };
158
+ const c = core(new SharedIsrStore(new CacheGuard(hang, 50)), () => 'x');
159
+ const started = Date.now();
160
+ const r = await c.renderPage({ route: '/p', url: '/p', method: 'GET', headers: {} });
161
+ expect(r.status).toBe(200);
162
+ expect(Date.now() - started).toBeLessThan(1500);
163
+ });
164
+ it('never stores a render that read per-user state', async () => {
165
+ const store = new SharedIsrStore(new CacheGuard(adapter()));
166
+ const c = createSSRCore({
167
+ manifest: { pages: [page('/me')], regions: {} },
168
+ isrStore: store,
169
+ loadPageModule: async () => ({
170
+ default: () => {
171
+ markNoStore(); // cookies(), headers() and no-store fetches do this
172
+ return jsx('p', { children: 'Hello Ada' });
173
+ },
174
+ }),
175
+ loadRuntimeRenderer: () => () => '',
176
+ });
177
+ const r = await c.renderPage({ route: '/me', url: '/me', method: 'GET', headers: { cookie: 'sid=ada' } });
178
+ expect(r.noStore).toBe(true);
179
+ expect(redis.keys().filter((k) => k.includes('isr:'))).toEqual([]);
180
+ expect(await store.get('/me')).toBeUndefined();
181
+ });
182
+ });
183
+ describe('the shared data cache', () => {
184
+ it('shares fetch responses between instances and invalidates them by tag', async () => {
185
+ const shared = new SharedDataCache(new CacheGuard(adapter()));
186
+ cacheRuntime().shared = shared;
187
+ let upstream = 0;
188
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(`body-${++upstream}`)));
189
+ cacheRuntime().fetchPatched = false;
190
+ patchFetch();
191
+ const read = async () => (await fetch('http://data/x', { next: { tags: ['x'], revalidate: 60 } })).text();
192
+ expect(await read()).toBe('body-1');
193
+ // Another instance (a fresh data store on the same Redis) sees the entry.
194
+ const other = new SharedDataCache(new CacheGuard(adapter()));
195
+ const hit = await other.get('fetch:' + JSON.stringify(['GET', 'http://data/x', []]));
196
+ expect(hit.ok && hit.value).toBeTruthy();
197
+ expect(await read()).toBe('body-1');
198
+ expect(await other.deleteTags(['x'])).toBeGreaterThan(0);
199
+ expect(await read()).toBe('body-2');
200
+ vi.unstubAllGlobals();
201
+ cacheRuntime().fetchPatched = false;
202
+ });
203
+ });
204
+ describe('configuration', () => {
205
+ it('loads the default (no adapter), redis, and a custom module', async () => {
206
+ expect(await loadCacheAdapter(undefined)).toBeNull();
207
+ expect(await loadCacheAdapter({ adapter: 'memory' })).toBeNull();
208
+ const r = await loadCacheAdapter({ adapter: 'redis', url: url() });
209
+ expect(r?.name).toBe('redis');
210
+ await r?.close();
211
+ await expect(loadCacheAdapter({ adapter: 'redis' })).rejects.toThrow(/cache\.url/);
212
+ });
213
+ it('reads the spec from KRATE_CACHE and from the bundled config', () => {
214
+ expect(cacheSpecFromEnv({ KRATE_CACHE: '{"adapter":"redis","url":"redis://h"}' })).toEqual({ adapter: 'redis', url: 'redis://h' });
215
+ expect(cacheSpecFromEnv({ KRATE_CACHE: 'not json' })).toBeUndefined();
216
+ expect(cacheSpecFromEnv({})).toBeUndefined();
217
+ const saved = process.env.MY_REDIS;
218
+ process.env.MY_REDIS = 'redis://from-env';
219
+ expect(cacheSpecFromConfig({ adapter: 'redis', urlEnv: 'MY_REDIS' })?.url).toBe('redis://from-env');
220
+ expect(cacheSpecFromConfig({ adapter: 'memory' })).toBeUndefined();
221
+ if (saved === undefined)
222
+ delete process.env.MY_REDIS;
223
+ else
224
+ process.env.MY_REDIS = saved;
225
+ });
226
+ it('keeps the fallback store for a spec that fails to start', async () => {
227
+ const fallback = new MemoryIsrStore(4);
228
+ const setup = isrStoreFor({ adapter: 'redis' }, fallback);
229
+ expect(await setup.ready).toBeNull();
230
+ await setup.store.set('/a', { html: 'a', timestamp: 1 });
231
+ expect((await setup.store.get('/a'))?.html).toBe('a');
232
+ });
233
+ it('accepts an adapter instance (serverless targets plug in their own)', async () => {
234
+ const mem = new MemoryAdapter();
235
+ const setup = isrStoreFor(mem, new MemoryIsrStore(4));
236
+ expect(await setup.ready).toBe(mem);
237
+ await setup.store.set('/a', { html: 'a', timestamp: 1, tags: ['t'] });
238
+ expect(await mem.get('isr:/a')).toContain('"html":"a"');
239
+ expect(await setup.store.deleteTags(['t'])).toBeGreaterThan(0);
240
+ expect(await mem.get('isr:/a')).toBeNull();
241
+ installCacheAdapter(mem);
242
+ expect(cacheRuntime().shared).toBeTruthy();
243
+ });
244
+ });
@@ -0,0 +1,27 @@
1
+ import type { CacheAdapter, CacheSetOptions } from './cache-adapter.js';
2
+ export interface RedisAdapterOptions {
3
+ url: string;
4
+ prefix?: string;
5
+ /** Milliseconds one command may take (default 250). */
6
+ timeoutMs?: number;
7
+ }
8
+ export declare class RedisAdapter implements CacheAdapter {
9
+ readonly name = "redis";
10
+ private readonly conn;
11
+ private readonly prefix;
12
+ private readonly connOpts;
13
+ private subscribers;
14
+ constructor(options: RedisAdapterOptions);
15
+ private k;
16
+ private t;
17
+ get(key: string): Promise<string | null>;
18
+ set(key: string, value: string, options?: CacheSetOptions): Promise<void>;
19
+ delete(key: string): Promise<void>;
20
+ keysByTag(tag: string): Promise<string[]>;
21
+ deleteByTags(tags: string[]): Promise<number>;
22
+ publish(channel: string, message: string): Promise<void>;
23
+ subscribe(channel: string, handler: (message: string) => void): Promise<() => void>;
24
+ close(): Promise<void>;
25
+ }
26
+ /** createRedisAdapter({ url }) is `new RedisAdapter({ url })`, for passing to createKrateHandler({ cache }). */
27
+ export declare function createRedisAdapter(options: RedisAdapterOptions): RedisAdapter;
@@ -0,0 +1,110 @@
1
+ // The Redis cache adapter: a RESP client over node:net (resp.ts), no dependency.
2
+ //
3
+ // Layout (prefix defaults to "krate:"):
4
+ // <prefix>k:<key> the value, with EX when it expires
5
+ // <prefix>t:<tag> a set of the keys stored with tag
6
+ // <prefix>c:<channel> pub/sub channel
7
+ import { RespConnection, parseRedisURL } from './resp.js';
8
+ export class RedisAdapter {
9
+ constructor(options) {
10
+ this.name = 'redis';
11
+ this.subscribers = [];
12
+ this.connOpts = { ...parseRedisURL(options.url), commandTimeoutMs: options.timeoutMs ?? 250, connectTimeoutMs: Math.max(options.timeoutMs ?? 250, 500) };
13
+ this.conn = new RespConnection(this.connOpts);
14
+ this.prefix = options.prefix ?? 'krate:';
15
+ }
16
+ k(key) {
17
+ return this.prefix + 'k:' + key;
18
+ }
19
+ t(tag) {
20
+ return this.prefix + 't:' + tag;
21
+ }
22
+ async get(key) {
23
+ const v = await this.conn.command('GET', this.k(key));
24
+ return typeof v === 'string' ? v : null;
25
+ }
26
+ async set(key, value, options = {}) {
27
+ const ttl = options.ttlSeconds && options.ttlSeconds !== Infinity && options.ttlSeconds > 0 ? Math.ceil(options.ttlSeconds) : 0;
28
+ const writes = [ttl ? this.conn.command('SET', this.k(key), value, 'EX', ttl) : this.conn.command('SET', this.k(key), value)];
29
+ for (const tag of options.tags || []) {
30
+ writes.push(this.conn.command('SADD', this.t(tag), this.k(key)));
31
+ // A tag set outlives its newest member a little, so it never grows forever.
32
+ if (ttl)
33
+ writes.push(this.conn.command('EXPIRE', this.t(tag), ttl + 60));
34
+ }
35
+ await Promise.all(writes);
36
+ }
37
+ async delete(key) {
38
+ await this.conn.command('DEL', this.k(key));
39
+ }
40
+ async keysByTag(tag) {
41
+ const members = await this.conn.command('SMEMBERS', this.t(tag));
42
+ const prefix = this.prefix + 'k:';
43
+ return Array.isArray(members) ? members.filter((m) => typeof m === 'string' && m.startsWith(prefix)).map((m) => m.slice(prefix.length)) : [];
44
+ }
45
+ async deleteByTags(tags) {
46
+ let n = 0;
47
+ for (const tag of tags) {
48
+ const members = await this.conn.command('SMEMBERS', this.t(tag));
49
+ const keys = Array.isArray(members) ? members.filter((m) => typeof m === 'string') : [];
50
+ if (keys.length > 0) {
51
+ const removed = await this.conn.command('DEL', ...keys);
52
+ if (typeof removed === 'number')
53
+ n += removed;
54
+ }
55
+ await this.conn.command('DEL', this.t(tag));
56
+ }
57
+ return n;
58
+ }
59
+ async publish(channel, message) {
60
+ await this.conn.command('PUBLISH', this.prefix + 'c:' + channel, message);
61
+ }
62
+ async subscribe(channel, handler) {
63
+ const full = this.prefix + 'c:' + channel;
64
+ const sub = new RespConnection({ ...this.connOpts, commandTimeoutMs: 5000 });
65
+ let stopped = false;
66
+ let delay = 200;
67
+ const open = async () => {
68
+ await sub.ensure();
69
+ await sub.send('SUBSCRIBE', full);
70
+ };
71
+ sub.onPush = (kind, ch, payload) => {
72
+ if (kind === 'message' && ch === full)
73
+ handler(payload);
74
+ };
75
+ sub.onDisconnect = () => {
76
+ if (stopped)
77
+ return;
78
+ const retry = () => {
79
+ if (stopped)
80
+ return;
81
+ open().then(() => {
82
+ delay = 200;
83
+ // Messages published while disconnected are gone: tell the caller.
84
+ handler('*');
85
+ }, () => {
86
+ delay = Math.min(delay * 2, 5000);
87
+ setTimeout(retry, delay).unref?.();
88
+ });
89
+ };
90
+ setTimeout(retry, delay).unref?.();
91
+ };
92
+ await open();
93
+ const stop = () => {
94
+ stopped = true;
95
+ sub.close();
96
+ };
97
+ this.subscribers.push(stop);
98
+ return stop;
99
+ }
100
+ async close() {
101
+ for (const stop of this.subscribers)
102
+ stop();
103
+ this.subscribers = [];
104
+ this.conn.close();
105
+ }
106
+ }
107
+ /** createRedisAdapter({ url }) is `new RedisAdapter({ url })`, for passing to createKrateHandler({ cache }). */
108
+ export function createRedisAdapter(options) {
109
+ return new RedisAdapter(options);
110
+ }
@@ -57,8 +57,23 @@ export declare class DataCache {
57
57
  invalidateTags(tags: string[]): number;
58
58
  clear(): void;
59
59
  }
60
+ /** A data cache shared by several processes (see cache-adapter.ts). */
61
+ export interface SharedDataStore {
62
+ /** { ok: false } when the shared store could not be reached. */
63
+ get(key: string): Promise<{
64
+ ok: true;
65
+ value: string | undefined;
66
+ } | {
67
+ ok: false;
68
+ }>;
69
+ /** Resolves false when the entry could not be stored. */
70
+ set(key: string, json: string, ttlSeconds: number, tags: string[]): Promise<boolean>;
71
+ deleteTags(tags: string[]): Promise<number>;
72
+ }
60
73
  /** Process-wide cache runtime shared by every bundled copy of this module. */
61
74
  export interface CacheRuntime {
75
+ /** The data cache shared with other instances, when a cache adapter is configured. */
76
+ shared?: SharedDataStore;
62
77
  dataCache: DataCache;
63
78
  /** Render scope storage; installed by the SSR renderer. */
64
79
  renderStore?: AsyncStore<CacheScope>;
@@ -70,6 +85,8 @@ export interface CacheRuntime {
70
85
  }): {
71
86
  dataEntries: number;
72
87
  };
88
+ /** Deletes the entries stored with tags in the shared cache (0 when there is none). */
89
+ invalidateShared(tags: string[]): Promise<number>;
73
90
  fetchPatched?: boolean;
74
91
  }
75
92
  /** The shared cache runtime, created on first use. */
@@ -99,6 +116,14 @@ export declare function routeDataTag(route: string): string;
99
116
  export declare function recordCacheRead(tags: readonly string[] | undefined, revalidate: number | false | undefined): void;
100
117
  /** Marks the current render as uncacheable. Outside a render it has no effect. */
101
118
  export declare function markNoStore(): void;
119
+ /**
120
+ * Reads a JSON value from the data cache; undefined on a miss. With a shared
121
+ * cache the instances' common store answers; when it cannot, this process's own
122
+ * cache does.
123
+ */
124
+ export declare function dataCacheGetJSONAsync(key: string): Promise<string | undefined>;
125
+ /** Stores a JSON value in the shared cache when there is one, else in this process's cache. */
126
+ export declare function dataCacheSetJSONAsync(key: string, json: string, ttlSeconds: number, tags: string[], epoch: number): Promise<void>;
102
127
  /** Reads a JSON value from the data cache; undefined on a miss. */
103
128
  export declare function dataCacheGetJSON(key: string): string | undefined;
104
129
  /**
@@ -106,13 +131,4 @@ export declare function dataCacheGetJSON(key: string): string | undefined;
106
131
  * render the entry also gets the route's implicit tag (see routeDataTag).
107
132
  */
108
133
  export declare function dataCacheSetJSON(key: string, json: string, ttlSeconds: number, tags: string[], epoch: number): void;
109
- /**
110
- * Wraps globalThis.fetch once so Next-style cache options work in server
111
- * code: `next.tags` are recorded on the current render, `next.revalidate: N`
112
- * or `cache: "force-cache"` cache successful GET/HEAD responses (by method,
113
- * URL and headers) for N seconds (indefinitely for force-cache or
114
- * `revalidate: false`) under the given tags, and `cache: "no-store"` /
115
- * `next.revalidate: 0` bypass the cache and make the render uncacheable.
116
- * Requests without these options are passed through untouched.
117
- */
118
134
  export declare function patchFetch(): void;
@@ -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,18 +325,21 @@ 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
345
  res.headers.forEach((v, k) => {
@@ -306,9 +347,16 @@ export function patchFetch() {
306
347
  headers.push([k, v]);
307
348
  });
308
349
  const entry = { status: res.status, statusText: res.statusText, headers, body: toBase64(bytes) };
309
- 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);
310
359
  }
311
- return res;
312
360
  };
313
361
  g.fetch = wrapped;
314
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);
@@ -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.