@krate/runtime 0.5.0-beta.1 → 0.5.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions.js +2 -1
- package/dist/assets-static.d.ts +5 -0
- package/dist/assets-static.js +31 -0
- package/dist/boundary.d.ts +12 -0
- package/dist/boundary.js +53 -13
- package/dist/cache-adapter.d.ts +113 -0
- package/dist/cache-adapter.js +217 -0
- package/dist/cache-adapter.test.d.ts +1 -0
- package/dist/cache-adapter.test.js +244 -0
- package/dist/cache-redis.d.ts +27 -0
- package/dist/cache-redis.js +110 -0
- package/dist/cache-scope.d.ts +25 -9
- package/dist/cache-scope.js +60 -12
- package/dist/cache.d.ts +1 -0
- package/dist/cache.js +3 -3
- package/dist/class-component.js +6 -0
- package/dist/class-component.test.js +53 -2
- package/dist/dev-overlay.js +10 -10
- package/dist/dom.d.ts +8 -0
- package/dist/dom.js +28 -0
- package/dist/effect-errors.test.d.ts +1 -0
- package/dist/effect-errors.test.js +163 -0
- package/dist/effects.d.ts +8 -0
- package/dist/effects.js +13 -0
- package/dist/error-overlay.js +4 -4
- package/dist/handler-html.d.ts +63 -0
- package/dist/handler-html.js +285 -0
- package/dist/handler-html.test.d.ts +1 -0
- package/dist/handler-html.test.js +256 -0
- package/dist/handler-routing.d.ts +83 -0
- package/dist/handler-routing.js +579 -0
- package/dist/handler-routing.test.d.ts +1 -0
- package/dist/handler-routing.test.js +99 -0
- package/dist/handler-segments.d.ts +43 -0
- package/dist/handler-segments.js +115 -0
- package/dist/handler-segments.test.d.ts +1 -0
- package/dist/handler-segments.test.js +217 -0
- package/dist/head-tags.d.ts +51 -0
- package/dist/head-tags.js +329 -0
- package/dist/head-tags.test.d.ts +1 -0
- package/dist/head-tags.test.js +131 -0
- package/dist/highlight-bind.d.ts +42 -0
- package/dist/highlight-bind.js +176 -0
- package/dist/highlight-bind.test.d.ts +1 -0
- package/dist/highlight-bind.test.js +124 -0
- package/dist/highlight.d.ts +93 -0
- package/dist/highlight.js +426 -0
- package/dist/highlight.test.d.ts +1 -0
- package/dist/highlight.test.js +56 -0
- package/dist/hints.d.ts +19 -0
- package/dist/hints.js +97 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/jsx-types.d.ts +11 -0
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +10 -10
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-classes.js +5 -5
- package/dist/krate-f-highlight.js +2 -0
- package/dist/krate-f-list.js +1 -1
- package/dist/krate-f-navigation.js +2 -0
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-features.json +254 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-runtime.js +5 -5
- package/dist/list.js +4 -2
- package/dist/metadata-routes.d.ts +75 -0
- package/dist/metadata-routes.js +76 -0
- package/dist/metadata.d.ts +222 -0
- package/dist/metadata.js +452 -0
- package/dist/metadata.test.d.ts +1 -0
- package/dist/metadata.test.js +167 -0
- package/dist/navigation-server.d.ts +27 -0
- package/dist/navigation-server.js +90 -0
- package/dist/navigation.d.ts +37 -0
- package/dist/navigation.js +195 -0
- package/dist/navigation.test.d.ts +1 -0
- package/dist/navigation.test.js +130 -0
- package/dist/node-server.d.ts +22 -0
- package/dist/node-server.js +436 -0
- package/dist/node-server.test.d.ts +1 -0
- package/dist/node-server.test.js +492 -0
- package/dist/og-files.d.ts +2 -0
- package/dist/og-files.js +19 -0
- package/dist/og.d.ts +56 -0
- package/dist/og.js +156 -0
- package/dist/react.d.ts +47 -0
- package/dist/react.js +59 -1
- package/dist/react19.test.d.ts +1 -0
- package/dist/react19.test.js +176 -0
- package/dist/request-context.d.ts +23 -0
- package/dist/request-context.js +45 -0
- package/dist/resp.d.ts +55 -0
- package/dist/resp.js +239 -0
- package/dist/router-layout.test.js +70 -0
- package/dist/router-nav.test.js +27 -0
- package/dist/router.js +59 -4
- package/dist/segmented-lru.d.ts +19 -0
- package/dist/segmented-lru.js +87 -0
- package/dist/server-async.test.js +23 -1
- package/dist/server-handler.d.ts +165 -0
- package/dist/server-handler.js +1832 -0
- package/dist/server-handler.test.d.ts +1 -0
- package/dist/server-handler.test.js +535 -0
- package/dist/server-highlight.test.d.ts +1 -0
- package/dist/server-highlight.test.js +32 -0
- package/dist/server-renderer.js +146 -788
- package/dist/server-renderer.test.d.ts +1 -0
- package/dist/server-renderer.test.js +266 -0
- package/dist/server.d.ts +12 -1
- package/dist/server.js +42 -6
- package/dist/sha256.d.ts +1 -0
- package/dist/sha256.js +66 -0
- package/dist/sha256.test.d.ts +1 -0
- package/dist/sha256.test.js +13 -0
- package/dist/shared-isr.d.ts +31 -0
- package/dist/shared-isr.js +142 -0
- package/dist/signal.js +63 -8
- package/dist/ssr-core-behavior.test.d.ts +1 -0
- package/dist/ssr-core-behavior.test.js +620 -0
- package/dist/ssr-core.d.ts +175 -0
- package/dist/ssr-core.js +940 -0
- package/dist/ssr-core.test.d.ts +1 -0
- package/dist/ssr-core.test.js +324 -0
- package/dist/static-memory.d.ts +3 -0
- package/dist/static-memory.js +47 -0
- package/dist/static-memory.test.d.ts +1 -0
- package/dist/static-memory.test.js +26 -0
- package/dist/test-redis.d.ts +12 -0
- package/dist/test-redis.js +131 -0
- package/dist/use-id.d.ts +8 -0
- package/dist/use-id.js +40 -0
- package/package.json +29 -1
package/dist/resp.js
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// A small RESP2 client over node:net / node:tls, enough for the Redis cache
|
|
2
|
+
// adapter: pipelined commands with a timeout each, automatic reconnects, and a
|
|
3
|
+
// subscriber connection for pub/sub. No dependency.
|
|
4
|
+
import net from 'node:net';
|
|
5
|
+
import tls from 'node:tls';
|
|
6
|
+
export class RespError extends Error {
|
|
7
|
+
constructor(message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = 'RespError';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Parses redis://[user:password@]host[:port][/db] and rediss:// (TLS) URLs. */
|
|
13
|
+
export function parseRedisURL(url) {
|
|
14
|
+
const u = new URL(url);
|
|
15
|
+
if (u.protocol !== 'redis:' && u.protocol !== 'rediss:')
|
|
16
|
+
throw new Error(`unsupported cache URL protocol ${u.protocol}`);
|
|
17
|
+
const db = u.pathname.length > 1 ? parseInt(u.pathname.slice(1), 10) : undefined;
|
|
18
|
+
return {
|
|
19
|
+
host: u.hostname || '127.0.0.1',
|
|
20
|
+
port: u.port ? parseInt(u.port, 10) : 6379,
|
|
21
|
+
tls: u.protocol === 'rediss:',
|
|
22
|
+
username: u.username ? decodeURIComponent(u.username) : undefined,
|
|
23
|
+
password: u.password ? decodeURIComponent(u.password) : undefined,
|
|
24
|
+
db: db !== undefined && Number.isFinite(db) ? db : undefined,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** Encodes a command as a RESP array of bulk strings. */
|
|
28
|
+
export function encodeCommand(args) {
|
|
29
|
+
const parts = [Buffer.from(`*${args.length}\r\n`)];
|
|
30
|
+
for (const a of args) {
|
|
31
|
+
const b = Buffer.isBuffer(a) ? a : Buffer.from(String(a));
|
|
32
|
+
parts.push(Buffer.from(`$${b.length}\r\n`), b, Buffer.from('\r\n'));
|
|
33
|
+
}
|
|
34
|
+
return Buffer.concat(parts);
|
|
35
|
+
}
|
|
36
|
+
/** Incremental reply parser: push chunks, take complete replies. */
|
|
37
|
+
export class RespParser {
|
|
38
|
+
constructor() {
|
|
39
|
+
this.buf = Buffer.alloc(0);
|
|
40
|
+
}
|
|
41
|
+
push(chunk) {
|
|
42
|
+
this.buf = this.buf.length === 0 ? chunk : Buffer.concat([this.buf, chunk]);
|
|
43
|
+
}
|
|
44
|
+
/** The next complete reply, or undefined when more bytes are needed. */
|
|
45
|
+
next() {
|
|
46
|
+
const r = this.parse(0);
|
|
47
|
+
if (!r)
|
|
48
|
+
return undefined;
|
|
49
|
+
this.buf = this.buf.subarray(r.end);
|
|
50
|
+
return r.value;
|
|
51
|
+
}
|
|
52
|
+
line(at) {
|
|
53
|
+
const i = this.buf.indexOf('\r\n', at);
|
|
54
|
+
if (i < 0)
|
|
55
|
+
return null;
|
|
56
|
+
return { text: this.buf.toString('utf8', at, i), end: i + 2 };
|
|
57
|
+
}
|
|
58
|
+
parse(at) {
|
|
59
|
+
if (at >= this.buf.length)
|
|
60
|
+
return null;
|
|
61
|
+
const type = String.fromCharCode(this.buf[at]);
|
|
62
|
+
const l = this.line(at + 1);
|
|
63
|
+
if (!l)
|
|
64
|
+
return null;
|
|
65
|
+
switch (type) {
|
|
66
|
+
case '+':
|
|
67
|
+
return { value: l.text, end: l.end };
|
|
68
|
+
case '-':
|
|
69
|
+
return { value: new RespError(l.text), end: l.end };
|
|
70
|
+
case ':':
|
|
71
|
+
return { value: parseInt(l.text, 10), end: l.end };
|
|
72
|
+
case '$': {
|
|
73
|
+
const n = parseInt(l.text, 10);
|
|
74
|
+
if (n < 0)
|
|
75
|
+
return { value: null, end: l.end };
|
|
76
|
+
if (this.buf.length < l.end + n + 2)
|
|
77
|
+
return null;
|
|
78
|
+
return { value: this.buf.toString('utf8', l.end, l.end + n), end: l.end + n + 2 };
|
|
79
|
+
}
|
|
80
|
+
case '*': {
|
|
81
|
+
const n = parseInt(l.text, 10);
|
|
82
|
+
if (n < 0)
|
|
83
|
+
return { value: null, end: l.end };
|
|
84
|
+
const items = [];
|
|
85
|
+
let pos = l.end;
|
|
86
|
+
for (let i = 0; i < n; i++) {
|
|
87
|
+
const r = this.parse(pos);
|
|
88
|
+
if (!r)
|
|
89
|
+
return null;
|
|
90
|
+
items.push(r.value instanceof RespError ? r.value.message : r.value);
|
|
91
|
+
pos = r.end;
|
|
92
|
+
}
|
|
93
|
+
return { value: items, end: pos };
|
|
94
|
+
}
|
|
95
|
+
default:
|
|
96
|
+
throw new RespError(`unexpected reply type ${JSON.stringify(type)}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** One connection: commands are written in order and answered in order. */
|
|
101
|
+
export class RespConnection {
|
|
102
|
+
constructor(opts) {
|
|
103
|
+
this.opts = opts;
|
|
104
|
+
this.socket = null;
|
|
105
|
+
this.connecting = null;
|
|
106
|
+
this.pending = [];
|
|
107
|
+
this.parser = new RespParser();
|
|
108
|
+
this.closed = false;
|
|
109
|
+
}
|
|
110
|
+
connect() {
|
|
111
|
+
if (this.socket)
|
|
112
|
+
return Promise.resolve(this.socket);
|
|
113
|
+
if (this.connecting)
|
|
114
|
+
return this.connecting;
|
|
115
|
+
const timeout = this.opts.connectTimeoutMs ?? 1000;
|
|
116
|
+
this.connecting = new Promise((resolve, reject) => {
|
|
117
|
+
const done = (err, s) => {
|
|
118
|
+
clearTimeout(timer);
|
|
119
|
+
this.connecting = null;
|
|
120
|
+
if (err)
|
|
121
|
+
reject(err);
|
|
122
|
+
else
|
|
123
|
+
resolve(s);
|
|
124
|
+
};
|
|
125
|
+
const s = this.opts.tls
|
|
126
|
+
? tls.connect({ host: this.opts.host, port: this.opts.port, servername: this.opts.host })
|
|
127
|
+
: net.connect({ host: this.opts.host, port: this.opts.port });
|
|
128
|
+
const timer = setTimeout(() => {
|
|
129
|
+
s.destroy();
|
|
130
|
+
done(new Error(`cache connection to ${this.opts.host}:${this.opts.port} timed out`));
|
|
131
|
+
}, timeout);
|
|
132
|
+
s.setNoDelay(true);
|
|
133
|
+
s.once('error', (e) => done(e));
|
|
134
|
+
s.once(this.opts.tls ? 'secureConnect' : 'connect', () => {
|
|
135
|
+
s.removeAllListeners('error');
|
|
136
|
+
this.attach(s);
|
|
137
|
+
this.handshake(s).then(() => done(null, s), (e) => {
|
|
138
|
+
s.destroy();
|
|
139
|
+
done(e instanceof Error ? e : new Error(String(e)));
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
return this.connecting;
|
|
144
|
+
}
|
|
145
|
+
attach(s) {
|
|
146
|
+
this.socket = s;
|
|
147
|
+
this.parser = new RespParser();
|
|
148
|
+
s.on('data', (chunk) => {
|
|
149
|
+
this.parser.push(chunk);
|
|
150
|
+
for (;;) {
|
|
151
|
+
let reply;
|
|
152
|
+
try {
|
|
153
|
+
reply = this.parser.next();
|
|
154
|
+
}
|
|
155
|
+
catch (e) {
|
|
156
|
+
s.destroy(e instanceof Error ? e : new Error(String(e)));
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (reply === undefined)
|
|
160
|
+
return;
|
|
161
|
+
// A subscriber connection (onPush set) only receives pushes.
|
|
162
|
+
if (this.onPush && Array.isArray(reply)) {
|
|
163
|
+
this.onPush(String(reply[0]), String(reply[1]), String(reply[2] ?? ''));
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
this.settle(reply);
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
const drop = (err) => {
|
|
170
|
+
if (this.socket !== s)
|
|
171
|
+
return;
|
|
172
|
+
this.socket = null;
|
|
173
|
+
const pending = this.pending;
|
|
174
|
+
this.pending = [];
|
|
175
|
+
for (const p of pending) {
|
|
176
|
+
clearTimeout(p.timer);
|
|
177
|
+
p.reject(err || new Error('cache connection closed'));
|
|
178
|
+
}
|
|
179
|
+
if (!this.closed && this.onDisconnect)
|
|
180
|
+
this.onDisconnect(err);
|
|
181
|
+
};
|
|
182
|
+
s.on('error', (e) => drop(e));
|
|
183
|
+
s.on('close', () => drop());
|
|
184
|
+
}
|
|
185
|
+
settle(reply) {
|
|
186
|
+
const p = this.pending.shift();
|
|
187
|
+
if (!p)
|
|
188
|
+
return;
|
|
189
|
+
clearTimeout(p.timer);
|
|
190
|
+
if (reply instanceof RespError)
|
|
191
|
+
p.reject(reply);
|
|
192
|
+
else
|
|
193
|
+
p.resolve(reply);
|
|
194
|
+
}
|
|
195
|
+
async handshake(s) {
|
|
196
|
+
const send = (args) => this.write(s, args);
|
|
197
|
+
if (this.opts.password !== undefined) {
|
|
198
|
+
await send(this.opts.username ? ['AUTH', this.opts.username, this.opts.password] : ['AUTH', this.opts.password]);
|
|
199
|
+
}
|
|
200
|
+
if (this.opts.db)
|
|
201
|
+
await send(['SELECT', String(this.opts.db)]);
|
|
202
|
+
}
|
|
203
|
+
write(s, args) {
|
|
204
|
+
const timeout = this.opts.commandTimeoutMs ?? 1000;
|
|
205
|
+
return new Promise((resolve, reject) => {
|
|
206
|
+
const timer = setTimeout(() => {
|
|
207
|
+
// The reply order is unknown after a timeout: drop the connection.
|
|
208
|
+
s.destroy(new Error(`cache command ${String(args[0])} timed out after ${timeout}ms`));
|
|
209
|
+
}, timeout);
|
|
210
|
+
this.pending.push({ resolve, reject, timer });
|
|
211
|
+
s.write(encodeCommand(args), (err) => {
|
|
212
|
+
if (err)
|
|
213
|
+
s.destroy(err);
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
/** Sends a command and resolves with its reply. */
|
|
218
|
+
async command(...args) {
|
|
219
|
+
if (this.closed)
|
|
220
|
+
throw new Error('cache connection is closed');
|
|
221
|
+
const s = await this.connect();
|
|
222
|
+
return this.write(s, args);
|
|
223
|
+
}
|
|
224
|
+
/** Writes a command without waiting for a reply (pub/sub subscribe uses pushes). */
|
|
225
|
+
async send(...args) {
|
|
226
|
+
const s = await this.connect();
|
|
227
|
+
s.write(encodeCommand(args));
|
|
228
|
+
}
|
|
229
|
+
/** Opens the connection now (used by the subscriber to reconnect). */
|
|
230
|
+
async ensure() {
|
|
231
|
+
await this.connect();
|
|
232
|
+
}
|
|
233
|
+
close() {
|
|
234
|
+
this.closed = true;
|
|
235
|
+
if (this.socket)
|
|
236
|
+
this.socket.destroy();
|
|
237
|
+
this.socket = null;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
@@ -89,6 +89,76 @@ describe('layout persistence', () => {
|
|
|
89
89
|
// The layout effect is still live.
|
|
90
90
|
expect(log).toEqual(['layout-cleanup', 'layout:1']);
|
|
91
91
|
});
|
|
92
|
+
it('shows a segment 404/500 page in place, keeps the layout, and hands over the server error data', async () => {
|
|
93
|
+
setup(shell('<main>Page A</main>'), [LAYOUT]);
|
|
94
|
+
const nav = document.getElementById('nav');
|
|
95
|
+
const errorBlock = '<script type="application/json" id="__krate_error">{"message":"Internal Server Error","digest":"abc1234567"}</script>';
|
|
96
|
+
const errDoc = doc('500', shell('<main id="err">Oops</main>'), [LAYOUT]).replace('</head>', errorBlock + '</head>');
|
|
97
|
+
fetch.mockImplementation(async (input) => {
|
|
98
|
+
const u = new URL(input, location.href);
|
|
99
|
+
const bodies = {
|
|
100
|
+
'/boom': [500, errDoc],
|
|
101
|
+
'/missing': [404, doc('404', shell('<main id="nf">Nothing here</main>'), [LAYOUT])],
|
|
102
|
+
'/fine': [200, doc('Fine', shell('<main>Fine</main>'), [LAYOUT])],
|
|
103
|
+
};
|
|
104
|
+
const hit = bodies[u.pathname];
|
|
105
|
+
return {
|
|
106
|
+
ok: !!hit && hit[0] < 400,
|
|
107
|
+
status: hit ? hit[0] : 404,
|
|
108
|
+
url: u.href,
|
|
109
|
+
headers: new Headers({ 'content-type': 'text/html' }),
|
|
110
|
+
text: async () => (hit ? hit[1] : ''),
|
|
111
|
+
};
|
|
112
|
+
});
|
|
113
|
+
await krateRouter.push('/boom');
|
|
114
|
+
expect(document.getElementById('err')).not.toBeNull();
|
|
115
|
+
expect(document.getElementById('nav')).toBe(nav);
|
|
116
|
+
expect(location.pathname).toBe('/boom');
|
|
117
|
+
const block = document.getElementById('__krate_error');
|
|
118
|
+
expect(JSON.parse(block.textContent).digest).toBe('abc1234567');
|
|
119
|
+
expect(document.querySelectorAll('#__krate_error')).toHaveLength(1);
|
|
120
|
+
// A 404 page swaps in the same way and the previous error data is dropped.
|
|
121
|
+
await krateRouter.push('/missing');
|
|
122
|
+
expect(document.getElementById('nf')).not.toBeNull();
|
|
123
|
+
expect(document.getElementById('nav')).toBe(nav);
|
|
124
|
+
expect(location.pathname).toBe('/missing');
|
|
125
|
+
expect(document.getElementById('__krate_error')).toBeNull();
|
|
126
|
+
// And an ordinary page after an error page leaves no stale data either.
|
|
127
|
+
await krateRouter.push('/boom');
|
|
128
|
+
expect(document.getElementById('__krate_error')).not.toBeNull();
|
|
129
|
+
await krateRouter.push('/fine');
|
|
130
|
+
expect(document.getElementById('__krate_error')).toBeNull();
|
|
131
|
+
expect(document.getElementById('nav')).toBe(nav);
|
|
132
|
+
});
|
|
133
|
+
describe('segment error boundaries', () => {
|
|
134
|
+
const ERR = { id: '_lerr_', k: 'error', d: 0, p: true };
|
|
135
|
+
const INNER = { id: '_linner_', k: 'layout', d: 0, p: true };
|
|
136
|
+
const nested = (page) => shell(`<!--kl:_lerr_--><section id="inner">Inner<!--kl:_linner_-->${page}<!--/kl:_linner_--></section><!--/kl:_lerr_-->`);
|
|
137
|
+
afterEach(() => {
|
|
138
|
+
delete globalThis.krateScopeFailed;
|
|
139
|
+
});
|
|
140
|
+
it('keeps the layouts below a healthy error boundary', async () => {
|
|
141
|
+
const chain = [LAYOUT, ERR, INNER];
|
|
142
|
+
setup(nested('<main>Page A</main>'), chain);
|
|
143
|
+
const inner = document.getElementById('inner');
|
|
144
|
+
routes['/b'] = doc('B', nested('<main>Page B</main>'), chain);
|
|
145
|
+
await krateRouter.push('/b');
|
|
146
|
+
expect(document.querySelector('main').textContent).toBe('Page B');
|
|
147
|
+
expect(document.getElementById('inner')).toBe(inner);
|
|
148
|
+
});
|
|
149
|
+
it('replaces a boundary that caught an error, and what is below it', async () => {
|
|
150
|
+
const chain = [LAYOUT, ERR, INNER];
|
|
151
|
+
setup(nested('<main>Page A</main>'), chain);
|
|
152
|
+
const inner = document.getElementById('inner');
|
|
153
|
+
const nav = document.getElementById('nav');
|
|
154
|
+
globalThis.krateScopeFailed = (scope) => scope === '_lerr_';
|
|
155
|
+
routes['/b'] = doc('B', nested('<main>Page B</main>'), chain);
|
|
156
|
+
await krateRouter.push('/b');
|
|
157
|
+
expect(document.querySelector('main').textContent).toBe('Page B');
|
|
158
|
+
expect(document.getElementById('inner')).not.toBe(inner);
|
|
159
|
+
expect(document.getElementById('nav')).toBe(nav);
|
|
160
|
+
});
|
|
161
|
+
});
|
|
92
162
|
it('remounts layouts the compiler marked as not persistable', async () => {
|
|
93
163
|
globalThis.__KRATE_CFG__ = { viewTransitions: false, dev: true };
|
|
94
164
|
const warn = vi.spyOn(console, 'warn').mockImplementation(() => { });
|
package/dist/router-nav.test.js
CHANGED
|
@@ -183,6 +183,17 @@ describe('view transitions', () => {
|
|
|
183
183
|
expect(order).toEqual(['mutate', 'push:About']);
|
|
184
184
|
});
|
|
185
185
|
});
|
|
186
|
+
describe('view transition names', () => {
|
|
187
|
+
it('names elements and applies their transition class after a swap', async () => {
|
|
188
|
+
routes['/vt'] = {
|
|
189
|
+
body: page('VT', '<h1 id="hero" data-view-transition="hero" data-view-transition-class="slow-fade">x</h1>'),
|
|
190
|
+
};
|
|
191
|
+
await krateRouter.push('/vt');
|
|
192
|
+
const hero = document.getElementById('hero');
|
|
193
|
+
expect(hero.style.viewTransitionName).toBe('hero');
|
|
194
|
+
expect(hero.style.getPropertyValue('view-transition-class')).toBe('slow-fade');
|
|
195
|
+
});
|
|
196
|
+
});
|
|
186
197
|
describe('hash navigation', () => {
|
|
187
198
|
it('handles hash-only links in place without fetching', async () => {
|
|
188
199
|
document.getElementById('root').innerHTML = `${link('#sec', 'Sec')}<div id="sec">x</div>`;
|
|
@@ -312,6 +323,22 @@ describe('prefetch cache', () => {
|
|
|
312
323
|
// The cache hit was consumed: revisiting fetches fresh HTML.
|
|
313
324
|
expect(fetchMock.mock.calls.filter((c) => String(c[0]).endsWith('/about')).length).toBe(2);
|
|
314
325
|
});
|
|
326
|
+
it('keeps the fragment of the link when the document was prefetched', async () => {
|
|
327
|
+
routes['/about'] = { body: page('About', '<h1>About</h1><h2 id="team">Team</h2>') };
|
|
328
|
+
const original = Element.prototype.scrollIntoView;
|
|
329
|
+
const scrolled = vi.fn();
|
|
330
|
+
Element.prototype.scrollIntoView = scrolled;
|
|
331
|
+
try {
|
|
332
|
+
await krateRouter.prefetch('/about#team');
|
|
333
|
+
await krateRouter.push('/about#team');
|
|
334
|
+
await settle();
|
|
335
|
+
expect(location.pathname + location.hash).toBe('/about#team');
|
|
336
|
+
expect(scrolled).toHaveBeenCalled();
|
|
337
|
+
}
|
|
338
|
+
finally {
|
|
339
|
+
Element.prototype.scrollIntoView = original;
|
|
340
|
+
}
|
|
341
|
+
});
|
|
315
342
|
it('expires entries after the TTL', async () => {
|
|
316
343
|
globalThis.__KRATE_CFG__ = { viewTransitions: false, prefetchTTL: 0 };
|
|
317
344
|
await krateRouter.prefetch('/about');
|
package/dist/router.js
CHANGED
|
@@ -509,7 +509,8 @@ function endTransition() {
|
|
|
509
509
|
el.style.opacity = '';
|
|
510
510
|
}
|
|
511
511
|
/**
|
|
512
|
-
* Apply `data-view-transition="name"` to `view-transition-name
|
|
512
|
+
* Apply `data-view-transition="name"` to `view-transition-name` (and
|
|
513
|
+
* `data-view-transition-class` to `view-transition-class`). Persistent
|
|
513
514
|
* chrome (navbar/sidebar) keeps its name across mutations so it morphs
|
|
514
515
|
* instead of cross-fading.
|
|
515
516
|
*/
|
|
@@ -518,6 +519,10 @@ function applyViewTransitionNames(root) {
|
|
|
518
519
|
const name = el.getAttribute('data-view-transition');
|
|
519
520
|
if (name)
|
|
520
521
|
el.style.viewTransitionName = name;
|
|
522
|
+
// `<ViewTransition default="slow-fade">` selects ::view-transition-*(*.slow-fade).
|
|
523
|
+
const cls = el.getAttribute('data-view-transition-class');
|
|
524
|
+
if (cls)
|
|
525
|
+
el.style.setProperty('view-transition-class', cls);
|
|
521
526
|
});
|
|
522
527
|
}
|
|
523
528
|
// Document reconciliation
|
|
@@ -787,8 +792,13 @@ async function loadDocument(req, signal) {
|
|
|
787
792
|
if (signal.aborted)
|
|
788
793
|
return { ok: false, aborted: true };
|
|
789
794
|
const hit = cacheTake(key);
|
|
790
|
-
if (hit)
|
|
791
|
-
|
|
795
|
+
if (hit) {
|
|
796
|
+
// The prefetch fetched the URL without its fragment: keep the one the
|
|
797
|
+
// link asked for, so `/docs/page#section` still scrolls to the section.
|
|
798
|
+
const hash = new URL(req.url, location.href).hash;
|
|
799
|
+
const target = hash && !new URL(hit.url, location.href).hash ? hit.url + hash : hit.url;
|
|
800
|
+
return { ok: true, doc: { html: hit.html, url: target, status: hit.status } };
|
|
801
|
+
}
|
|
792
802
|
}
|
|
793
803
|
let res;
|
|
794
804
|
try {
|
|
@@ -969,6 +979,7 @@ async function commitDocument(loaded, req, seq) {
|
|
|
969
979
|
renderedPath = pathOf(location.href);
|
|
970
980
|
docPath = renderedPath;
|
|
971
981
|
syncParams(doc);
|
|
982
|
+
syncErrorData(doc);
|
|
972
983
|
applyScroll(url, req);
|
|
973
984
|
if (req.kind !== 'pop' && req.kind !== 'refresh')
|
|
974
985
|
focusContent();
|
|
@@ -1099,16 +1110,24 @@ function keepScopes(ids) {
|
|
|
1099
1110
|
* route has a matching slot page and otherwise keep their content (a soft
|
|
1100
1111
|
* navigation never resets a slot to its default).
|
|
1101
1112
|
*/
|
|
1113
|
+
function boundaryFailed(scope) {
|
|
1114
|
+
const fn = globalThis.krateScopeFailed;
|
|
1115
|
+
return typeof fn === 'function' && !!fn(scope);
|
|
1116
|
+
}
|
|
1102
1117
|
function planSwap(oldChain, newChain, fromUrl, toUrl, doc) {
|
|
1103
1118
|
const full = { keep: [], skip: [], region: null, slots: [], chain: newChain };
|
|
1104
1119
|
let k = 0;
|
|
1105
1120
|
while (k < oldChain.length && k < newChain.length) {
|
|
1106
1121
|
const a = oldChain[k];
|
|
1107
1122
|
const b = newChain[k];
|
|
1108
|
-
if (a.id !== b.id || a.k !== 'layout'
|
|
1123
|
+
if (a.id !== b.id || a.k !== b.k || (a.k !== 'layout' && a.k !== 'error'))
|
|
1109
1124
|
break;
|
|
1110
1125
|
if (segmentKey(fromUrl, a.d) !== segmentKey(toUrl, b.d))
|
|
1111
1126
|
break;
|
|
1127
|
+
// A segment's error boundary stays mounted while it shows the page, so the
|
|
1128
|
+
// layouts below it keep their state; one that caught an error is replaced.
|
|
1129
|
+
if (a.k === 'error' && boundaryFailed(a.id))
|
|
1130
|
+
break;
|
|
1112
1131
|
if (!a.p || !b.p) {
|
|
1113
1132
|
devWarn(`layout ${b.f || b.id} is remounted on this navigation: ${b.why || a.why || 'not persistable'}`);
|
|
1114
1133
|
break;
|
|
@@ -1251,6 +1270,22 @@ function setSlotInfo(key, next) {
|
|
|
1251
1270
|
currentChain = currentChain.map((e) => e.s && e.s.some((x) => x.key === key) ? { ...e, s: e.s.map((x) => (x.key === key ? next : x)) } : e);
|
|
1252
1271
|
}
|
|
1253
1272
|
function syncParams(doc) {
|
|
1273
|
+
// The route pattern of a dynamic page, for useParams(). A static page has
|
|
1274
|
+
// none; the empty string says so (the first page's block is not in the DOM
|
|
1275
|
+
// any more once the router swapped it out).
|
|
1276
|
+
let route = '';
|
|
1277
|
+
const routeEl = doc.getElementById('__krate_page');
|
|
1278
|
+
if (routeEl) {
|
|
1279
|
+
try {
|
|
1280
|
+
const data = JSON.parse(routeEl.textContent || '{}');
|
|
1281
|
+
if (typeof data.r === 'string')
|
|
1282
|
+
route = data.r;
|
|
1283
|
+
}
|
|
1284
|
+
catch {
|
|
1285
|
+
/* ignore */
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
globalThis.__KRATE_ROUTE__ = route;
|
|
1254
1289
|
for (const script of Array.from(doc.querySelectorAll('script:not([src])'))) {
|
|
1255
1290
|
const m = /window\.__KRATE_PARAMS__\s*=\s*(\{[\s\S]*?\})\s*;?\s*$/.exec(script.textContent || '');
|
|
1256
1291
|
if (!m)
|
|
@@ -1265,6 +1300,26 @@ function syncParams(doc) {
|
|
|
1265
1300
|
}
|
|
1266
1301
|
delete globalThis.__KRATE_PARAMS__;
|
|
1267
1302
|
}
|
|
1303
|
+
/**
|
|
1304
|
+
* Moves the server-rendered error (a JSON data block the Go server injects into
|
|
1305
|
+
* a 500 page, read by error components while they hydrate) from the incoming
|
|
1306
|
+
* document to the live one, so an error page shown by soft navigation sees the
|
|
1307
|
+
* error of its own response. The block is removed when the new page has none.
|
|
1308
|
+
*/
|
|
1309
|
+
function syncErrorData(doc) {
|
|
1310
|
+
const next = doc.getElementById('__krate_error');
|
|
1311
|
+
const live = document.getElementById('__krate_error');
|
|
1312
|
+
if (!next) {
|
|
1313
|
+
if (live)
|
|
1314
|
+
live.remove();
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1317
|
+
const copy = document.importNode(next, true);
|
|
1318
|
+
if (live)
|
|
1319
|
+
live.replaceWith(copy);
|
|
1320
|
+
else
|
|
1321
|
+
document.head.appendChild(copy);
|
|
1322
|
+
}
|
|
1268
1323
|
function disposeScopes(ids) {
|
|
1269
1324
|
const fn = globalThis.krateDisposeScopes;
|
|
1270
1325
|
if (typeof fn === 'function')
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare class SegmentedLRU<V> {
|
|
2
|
+
private probation;
|
|
3
|
+
private protectedSeg;
|
|
4
|
+
private readonly max;
|
|
5
|
+
private readonly protectedMax;
|
|
6
|
+
constructor(maxSize: number);
|
|
7
|
+
get size(): number;
|
|
8
|
+
has(key: string): boolean;
|
|
9
|
+
/** Reads an entry without counting as a use. */
|
|
10
|
+
peek(key: string): V | undefined;
|
|
11
|
+
/** Reads an entry and counts the use: probation entries are promoted. */
|
|
12
|
+
get(key: string): V | undefined;
|
|
13
|
+
/** Stores an entry. An existing key keeps its segment. Returns the evicted entries. */
|
|
14
|
+
set(key: string, value: V): Array<[string, V]>;
|
|
15
|
+
delete(key: string): boolean;
|
|
16
|
+
clear(): void;
|
|
17
|
+
keys(): string[];
|
|
18
|
+
entries(): Array<[string, V]>;
|
|
19
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// A bounded cache that one client cannot flush. A plain LRU drops the hot
|
|
2
|
+
// entries as soon as enough new keys arrive between two hits, and on an open
|
|
3
|
+
// dynamic route ("/blog/[slug]") any slug renders, so a client can mint new
|
|
4
|
+
// keys at will. This is a segmented LRU: a new entry starts in a small
|
|
5
|
+
// probation segment and moves to the protected segment on its first hit, so a
|
|
6
|
+
// flood of one-off keys only churns probation and never reaches the entries
|
|
7
|
+
// that were requested twice.
|
|
8
|
+
export class SegmentedLRU {
|
|
9
|
+
constructor(maxSize) {
|
|
10
|
+
this.probation = new Map();
|
|
11
|
+
this.protectedSeg = new Map();
|
|
12
|
+
this.max = Math.max(1, Math.floor(maxSize));
|
|
13
|
+
// At least one probation slot, so a new entry can always be admitted.
|
|
14
|
+
this.protectedMax = Math.min(this.max - 1, Math.max(1, Math.floor(this.max * 0.8)));
|
|
15
|
+
}
|
|
16
|
+
get size() {
|
|
17
|
+
return this.probation.size + this.protectedSeg.size;
|
|
18
|
+
}
|
|
19
|
+
has(key) {
|
|
20
|
+
return this.protectedSeg.has(key) || this.probation.has(key);
|
|
21
|
+
}
|
|
22
|
+
/** Reads an entry without counting as a use. */
|
|
23
|
+
peek(key) {
|
|
24
|
+
return this.protectedSeg.get(key) ?? this.probation.get(key);
|
|
25
|
+
}
|
|
26
|
+
/** Reads an entry and counts the use: probation entries are promoted. */
|
|
27
|
+
get(key) {
|
|
28
|
+
const hot = this.protectedSeg.get(key);
|
|
29
|
+
if (hot !== undefined) {
|
|
30
|
+
this.protectedSeg.delete(key);
|
|
31
|
+
this.protectedSeg.set(key, hot);
|
|
32
|
+
return hot;
|
|
33
|
+
}
|
|
34
|
+
const cold = this.probation.get(key);
|
|
35
|
+
if (cold === undefined)
|
|
36
|
+
return undefined;
|
|
37
|
+
this.probation.delete(key);
|
|
38
|
+
if (this.protectedMax <= 0) {
|
|
39
|
+
this.probation.set(key, cold);
|
|
40
|
+
return cold;
|
|
41
|
+
}
|
|
42
|
+
this.protectedSeg.set(key, cold);
|
|
43
|
+
if (this.protectedSeg.size > this.protectedMax) {
|
|
44
|
+
// The coldest protected entry goes back to probation's newest slot.
|
|
45
|
+
const demoted = this.protectedSeg.keys().next().value;
|
|
46
|
+
const v = this.protectedSeg.get(demoted);
|
|
47
|
+
this.protectedSeg.delete(demoted);
|
|
48
|
+
this.probation.set(demoted, v);
|
|
49
|
+
}
|
|
50
|
+
return cold;
|
|
51
|
+
}
|
|
52
|
+
/** Stores an entry. An existing key keeps its segment. Returns the evicted entries. */
|
|
53
|
+
set(key, value) {
|
|
54
|
+
if (this.protectedSeg.has(key)) {
|
|
55
|
+
this.protectedSeg.delete(key);
|
|
56
|
+
this.protectedSeg.set(key, value);
|
|
57
|
+
return [];
|
|
58
|
+
}
|
|
59
|
+
if (this.probation.has(key)) {
|
|
60
|
+
this.probation.delete(key);
|
|
61
|
+
this.probation.set(key, value);
|
|
62
|
+
return [];
|
|
63
|
+
}
|
|
64
|
+
const evicted = [];
|
|
65
|
+
while (this.size >= this.max) {
|
|
66
|
+
const seg = this.probation.size > 0 ? this.probation : this.protectedSeg;
|
|
67
|
+
const oldest = seg.keys().next().value;
|
|
68
|
+
evicted.push([oldest, seg.get(oldest)]);
|
|
69
|
+
seg.delete(oldest);
|
|
70
|
+
}
|
|
71
|
+
this.probation.set(key, value);
|
|
72
|
+
return evicted;
|
|
73
|
+
}
|
|
74
|
+
delete(key) {
|
|
75
|
+
return this.protectedSeg.delete(key) || this.probation.delete(key);
|
|
76
|
+
}
|
|
77
|
+
clear() {
|
|
78
|
+
this.probation.clear();
|
|
79
|
+
this.protectedSeg.clear();
|
|
80
|
+
}
|
|
81
|
+
keys() {
|
|
82
|
+
return [...this.probation.keys(), ...this.protectedSeg.keys()];
|
|
83
|
+
}
|
|
84
|
+
entries() {
|
|
85
|
+
return [...this.probation.entries(), ...this.protectedSeg.entries()];
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { afterEach, describe, expect, it } from 'vitest';
|
|
2
2
|
import { cookies, headers } from './action-context.js';
|
|
3
|
-
import { getRequestContext, isNotFoundSignal, notFound, parseCookieHeader, redirectTarget, thenableRecord, } from './request-context.js';
|
|
3
|
+
import { getRequestContext, isNotFoundSignal, notFound, forbidden, unauthorized, accessDeniedStatus, httpFallbackStatus, parseCookieHeader, redirectTarget, thenableRecord, } from './request-context.js';
|
|
4
4
|
import { Link, Suspense, clientBoundary, jsx, renderToString, renderToStringAsync } from './server.js';
|
|
5
5
|
const REQUEST_KEY = Symbol.for('krate.request.store');
|
|
6
6
|
function withRequestStore(ctx) {
|
|
@@ -152,6 +152,28 @@ describe('render signals', () => {
|
|
|
152
152
|
expect(isNotFoundSignal(caught)).toBe(true);
|
|
153
153
|
expect(isNotFoundSignal(new Error('other'))).toBe(false);
|
|
154
154
|
});
|
|
155
|
+
it('forbidden() and unauthorized() throw signals with the Next.js digest', () => {
|
|
156
|
+
const catchOf = (fn) => {
|
|
157
|
+
try {
|
|
158
|
+
fn();
|
|
159
|
+
}
|
|
160
|
+
catch (e) {
|
|
161
|
+
return e;
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
const f = catchOf(forbidden);
|
|
165
|
+
const u = catchOf(unauthorized);
|
|
166
|
+
expect(accessDeniedStatus(f)).toBe(403);
|
|
167
|
+
expect(accessDeniedStatus(u)).toBe(401);
|
|
168
|
+
expect(f.digest).toBe('NEXT_HTTP_ERROR_FALLBACK;403');
|
|
169
|
+
expect(u.digest).toBe('NEXT_HTTP_ERROR_FALLBACK;401');
|
|
170
|
+
expect(accessDeniedStatus(Object.assign(new Error('x'), { digest: 'NEXT_HTTP_ERROR_FALLBACK;403' }))).toBe(403);
|
|
171
|
+
expect(accessDeniedStatus(new Error('other'))).toBe(0);
|
|
172
|
+
expect(isNotFoundSignal(f)).toBe(false);
|
|
173
|
+
expect(httpFallbackStatus(catchOf(notFound))).toBe(404);
|
|
174
|
+
expect(httpFallbackStatus(f)).toBe(403);
|
|
175
|
+
expect(httpFallbackStatus(undefined)).toBe(0);
|
|
176
|
+
});
|
|
155
177
|
it('redirectTarget understands Krate and Next.js redirect errors', () => {
|
|
156
178
|
expect(redirectTarget(Object.assign(new Error('x'), { __krateRedirect: '/a' }))).toBe('/a');
|
|
157
179
|
expect(redirectTarget(new Error('NEXT_REDIRECT:/b'))).toBe('/b');
|