@krate/runtime 0.5.0-rc.2 → 0.5.0-rc.4

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 (155) hide show
  1. package/dist/actions.d.ts +7 -0
  2. package/dist/actions.js +21 -3
  3. package/dist/actions.test.js +8 -410
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/after.test.js +58 -0
  7. package/dist/assets-static.d.ts +10 -1
  8. package/dist/assets-static.js +10 -2
  9. package/dist/base-path.js +4 -3
  10. package/dist/builtin-tags.d.ts +12 -0
  11. package/dist/builtin-tags.js +42 -0
  12. package/dist/builtin-tags.test.js +12 -0
  13. package/dist/cache-adapter.test.js +4 -203
  14. package/dist/cache-scope.d.ts +2 -0
  15. package/dist/cache.test.js +1 -197
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/dev-overlay.d.ts +54 -3
  19. package/dist/dev-overlay.js +469 -76
  20. package/dist/dom.js +3 -1
  21. package/dist/events.test.js +2 -407
  22. package/dist/handler-html.test.js +1 -202
  23. package/dist/handler-routing.js +3 -0
  24. package/dist/handler-segments.d.ts +6 -0
  25. package/dist/handler-segments.js +16 -2
  26. package/dist/handler-segments.test.js +8 -200
  27. package/dist/head-tags.d.ts +9 -0
  28. package/dist/head-tags.js +85 -1
  29. package/dist/head-tags.test.js +18 -125
  30. package/dist/index.d.ts +1 -5
  31. package/dist/index.js +3 -0
  32. package/dist/inline-action-token.test.js +31 -0
  33. package/dist/jsx-svg-types.test.js +58 -0
  34. package/dist/jsx-types.d.ts +92 -1
  35. package/dist/krate-core.js +1 -1
  36. package/dist/krate-dev.js +384 -65
  37. package/dist/krate-f-actions.js +1 -1
  38. package/dist/krate-f-navigation.js +1 -1
  39. package/dist/krate-f-router-lite.js +1 -1
  40. package/dist/krate-f-router.js +1 -1
  41. package/dist/krate-features.json +2 -0
  42. package/dist/krate-hydrate-lite.js +5 -5
  43. package/dist/krate-hydrate.js +5 -5
  44. package/dist/krate-runtime.js +5 -5
  45. package/dist/link-base-path.test.js +28 -0
  46. package/dist/node-server.test.js +1 -355
  47. package/dist/platform.d.ts +52 -0
  48. package/dist/platform.js +57 -0
  49. package/dist/platform.test.js +44 -0
  50. package/dist/router-nav.test.js +15 -444
  51. package/dist/router.js +39 -1
  52. package/dist/server-handler.d.ts +48 -0
  53. package/dist/server-handler.js +279 -17
  54. package/dist/server-handler.test.js +54 -388
  55. package/dist/server-renderer.test.js +0 -104
  56. package/dist/server.d.ts +15 -5
  57. package/dist/server.js +149 -22
  58. package/dist/server.test.js +52 -60
  59. package/dist/site-config.d.ts +13 -0
  60. package/dist/site-config.js +28 -0
  61. package/dist/site-config.test.js +30 -0
  62. package/dist/slot.d.ts +12 -0
  63. package/dist/slot.js +23 -0
  64. package/dist/slot.test.js +25 -0
  65. package/dist/ssr-core-behavior.test.js +3 -515
  66. package/dist/testing.d.ts +59 -0
  67. package/dist/testing.js +88 -0
  68. package/dist/testing.test.js +73 -0
  69. package/package.json +9 -1
  70. package/dist/action-context.test.js +0 -72
  71. package/dist/base-path.test.js +0 -88
  72. package/dist/class-component.test.js +0 -462
  73. package/dist/class-helpers.test.js +0 -169
  74. package/dist/context.test.js +0 -57
  75. package/dist/derived.test.js +0 -140
  76. package/dist/dev-overlay.test.js +0 -165
  77. package/dist/discrete.test.js +0 -100
  78. package/dist/dom.test.js +0 -39
  79. package/dist/effect-errors.test.d.ts +0 -1
  80. package/dist/effect-errors.test.js +0 -199
  81. package/dist/effects.test.d.ts +0 -1
  82. package/dist/effects.test.js +0 -485
  83. package/dist/handler-routing.test.d.ts +0 -1
  84. package/dist/handler-routing.test.js +0 -99
  85. package/dist/highlight-bind.test.d.ts +0 -1
  86. package/dist/highlight-bind.test.js +0 -124
  87. package/dist/highlight.test.d.ts +0 -1
  88. package/dist/highlight.test.js +0 -56
  89. package/dist/lanes.test.d.ts +0 -1
  90. package/dist/lanes.test.js +0 -59
  91. package/dist/list.test.d.ts +0 -1
  92. package/dist/list.test.js +0 -435
  93. package/dist/metadata.test.d.ts +0 -1
  94. package/dist/metadata.test.js +0 -167
  95. package/dist/navigation.test.d.ts +0 -1
  96. package/dist/navigation.test.js +0 -130
  97. package/dist/optimistic-lanes.test.d.ts +0 -1
  98. package/dist/optimistic-lanes.test.js +0 -45
  99. package/dist/patterns.test.d.ts +0 -1
  100. package/dist/patterns.test.js +0 -125
  101. package/dist/portal.test.d.ts +0 -1
  102. package/dist/portal.test.js +0 -99
  103. package/dist/react-effects.test.d.ts +0 -1
  104. package/dist/react-effects.test.js +0 -133
  105. package/dist/react-suspense.test.d.ts +0 -1
  106. package/dist/react-suspense.test.js +0 -194
  107. package/dist/react.test.d.ts +0 -1
  108. package/dist/react.test.js +0 -60
  109. package/dist/react19.test.d.ts +0 -1
  110. package/dist/react19.test.js +0 -176
  111. package/dist/reactivity-core.test.d.ts +0 -1
  112. package/dist/reactivity-core.test.js +0 -152
  113. package/dist/reconcile.test.d.ts +0 -1
  114. package/dist/reconcile.test.js +0 -110
  115. package/dist/refs.test.d.ts +0 -1
  116. package/dist/refs.test.js +0 -257
  117. package/dist/router-layout.test.d.ts +0 -1
  118. package/dist/router-layout.test.js +0 -249
  119. package/dist/router-slots.test.d.ts +0 -1
  120. package/dist/router-slots.test.js +0 -144
  121. package/dist/router-speculation.test.d.ts +0 -1
  122. package/dist/router-speculation.test.js +0 -25
  123. package/dist/router-styles.test.d.ts +0 -1
  124. package/dist/router-styles.test.js +0 -98
  125. package/dist/router.test.d.ts +0 -1
  126. package/dist/router.test.js +0 -36
  127. package/dist/server-async.test.d.ts +0 -1
  128. package/dist/server-async.test.js +0 -216
  129. package/dist/server-highlight.test.d.ts +0 -1
  130. package/dist/server-highlight.test.js +0 -32
  131. package/dist/signal-lanes.test.d.ts +0 -1
  132. package/dist/signal-lanes.test.js +0 -32
  133. package/dist/slots.test.d.ts +0 -1
  134. package/dist/slots.test.js +0 -187
  135. package/dist/snapshots.test.d.ts +0 -1
  136. package/dist/snapshots.test.js +0 -208
  137. package/dist/ssr-core.test.d.ts +0 -1
  138. package/dist/ssr-core.test.js +0 -324
  139. package/dist/static-memory.test.d.ts +0 -1
  140. package/dist/static-memory.test.js +0 -26
  141. package/dist/storage.test.d.ts +0 -1
  142. package/dist/storage.test.js +0 -46
  143. package/dist/suspense-actions.test.d.ts +0 -1
  144. package/dist/suspense-actions.test.js +0 -72
  145. package/dist/suspense.test.d.ts +0 -1
  146. package/dist/suspense.test.js +0 -556
  147. /package/dist/{action-context.test.d.ts → after.test.d.ts} +0 -0
  148. /package/dist/{base-path.test.d.ts → builtin-tags.test.d.ts} +0 -0
  149. /package/dist/{class-component.test.d.ts → inline-action-token.test.d.ts} +0 -0
  150. /package/dist/{class-helpers.test.d.ts → jsx-svg-types.test.d.ts} +0 -0
  151. /package/dist/{context.test.d.ts → link-base-path.test.d.ts} +0 -0
  152. /package/dist/{derived.test.d.ts → platform.test.d.ts} +0 -0
  153. /package/dist/{dev-overlay.test.d.ts → site-config.test.d.ts} +0 -0
  154. /package/dist/{discrete.test.d.ts → slot.test.d.ts} +0 -0
  155. /package/dist/{dom.test.d.ts → testing.test.d.ts} +0 -0
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
2
- import { initRouter, destroyRouter, krateRouter, navigate, getHistoryState, subscribeNavigation, invalidatePrefetchCache, } from './router';
2
+ import { initRouter, destroyRouter, krateRouter, } from './router';
3
3
  function page(title, body, head = '') {
4
4
  return `<!doctype html><html><head><title>${title}</title>${head}</head><body><div id="root">${body}</div></body></html>`;
5
5
  }
@@ -91,211 +91,28 @@ describe('SPA navigation', () => {
91
91
  expect(document.getElementById('__krate-route-announcer').textContent).toBe('About');
92
92
  expect(fetchMock).toHaveBeenCalledTimes(1);
93
93
  });
94
- it('ignores modified clicks and target=_blank links', async () => {
95
- // Keep happy-dom from performing the default (real) navigation.
96
- const stop = (e) => e.preventDefault();
97
- window.addEventListener('click', stop);
98
- document.getElementById('root').innerHTML = link('/about', 'x', 'target="_blank"');
99
- click(document.querySelector('a'));
100
- const a = document.createElement('a');
101
- a.setAttribute('data-krate-link', '');
102
- a.href = '/about';
103
- document.body.appendChild(a);
104
- a.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, button: 0, metaKey: true }));
94
+ it('follows html and body attribute changes and keeps runtime-set ones', async () => {
95
+ routes['/themed'] = {
96
+ body: '<!doctype html><html class="dark" lang="fr"><head><title>T</title></head><body data-x="1"><div id="root"><h1>T</h1></div></body></html>',
97
+ };
98
+ document.documentElement.setAttribute('data-runtime', '1');
99
+ await krateRouter.push('/themed');
105
100
  await settle();
106
- window.removeEventListener('click', stop);
107
- expect(fetchMock).not.toHaveBeenCalled();
108
- });
109
- it('stores NavigateOptions.state on the history entry', async () => {
110
- await krateRouter.push('/about', { state: { from: 'test' } });
111
- expect(getHistoryState()).toEqual({ from: 'test' });
112
- expect(location.pathname).toBe('/about');
113
- });
114
- it('replace() does not add a history entry', async () => {
115
- const before = history.length;
116
- await krateRouter.replace('/about');
117
- expect(history.length).toBe(before);
118
- expect(location.pathname).toBe('/about');
119
- });
120
- it('navigate() drives the SPA router and returns false', async () => {
121
- expect(navigate('/about')).toBe(false);
101
+ expect(document.documentElement.getAttribute('class')).toBe('dark');
102
+ expect(document.documentElement.getAttribute('lang')).toBe('fr');
103
+ expect(document.body.getAttribute('data-x')).toBe('1');
104
+ expect(document.documentElement.getAttribute('data-runtime')).toBe('1');
105
+ await krateRouter.push('/about');
122
106
  await settle();
123
- expect(document.title).toBe('About');
124
- });
125
- it('follows the final URL after a redirect', async () => {
126
- routes['/old'] = { body: page('About', '<h1>About</h1>'), redirect: '/about?moved=1' };
127
- await krateRouter.push('/old');
128
- expect(location.pathname + location.search).toBe('/about?moved=1');
129
- });
130
- it('hard-navigates for non-HTML responses', async () => {
131
- routes['/file.json'] = { body: '{}', type: 'application/json' };
132
- await krateRouter.push('/file.json');
133
- expect(hardNavs).toEqual([['http://localhost:3000/file.json', false]]);
134
- expect(location.pathname).toBe('/');
107
+ expect(document.documentElement.hasAttribute('class')).toBe(false);
108
+ expect(document.body.hasAttribute('data-x')).toBe(false);
109
+ expect(document.documentElement.getAttribute('data-runtime')).toBe('1');
135
110
  });
136
111
  it('hard-navigates when a redirect leaves the origin', async () => {
137
112
  routes['/out'] = { body: page('x', ''), redirect: 'https://example.com/elsewhere' };
138
113
  await krateRouter.push('/out');
139
114
  expect(hardNavs[0][0]).toBe('https://example.com/elsewhere');
140
115
  });
141
- it('cancels a navigation when krate:navigate-start is prevented', async () => {
142
- const stop = (e) => e.preventDefault();
143
- window.addEventListener('krate:navigate-start', stop);
144
- await krateRouter.push('/about');
145
- window.removeEventListener('krate:navigate-start', stop);
146
- expect(fetchMock).not.toHaveBeenCalled();
147
- expect(location.pathname).toBe('/');
148
- });
149
- it('notifies subscribers with pathname, search and status', async () => {
150
- const seen = [];
151
- const off = subscribeNavigation((s) => seen.push(`${s.status}:${s.pathname}${s.search}`));
152
- await krateRouter.push('/docs?x=1');
153
- off();
154
- expect(seen).toContain('loading:/');
155
- expect(seen[seen.length - 1]).toBe('idle:/docs?x=1');
156
- });
157
- });
158
- describe('view transitions', () => {
159
- it('updates history and focus only after the transition callback ran', async () => {
160
- globalThis.__KRATE_CFG__ = { viewTransitions: 'auto' };
161
- const order = [];
162
- let release;
163
- const gate = new Promise((r) => (release = r));
164
- document.startViewTransition = (cb) => {
165
- // The browser runs the update callback asynchronously.
166
- const updateCallbackDone = gate.then(() => {
167
- order.push('mutate');
168
- cb();
169
- });
170
- return { updateCallbackDone, finished: updateCallbackDone };
171
- };
172
- const origPush = history.pushState.bind(history);
173
- const spy = vi.spyOn(history, 'pushState').mockImplementation((...args) => {
174
- order.push('push:' + document.title);
175
- origPush(...args);
176
- });
177
- const p = krateRouter.push('/about');
178
- await settle();
179
- expect(order).toEqual([]);
180
- release();
181
- await p;
182
- spy.mockRestore();
183
- expect(order).toEqual(['mutate', 'push:About']);
184
- });
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
- });
197
- describe('hash navigation', () => {
198
- it('handles hash-only links in place without fetching', async () => {
199
- document.getElementById('root').innerHTML = `${link('#sec', 'Sec')}<div id="sec">x</div>`;
200
- const scrolled = vi.fn();
201
- document.getElementById('sec').scrollIntoView = scrolled;
202
- click(document.querySelector('a'));
203
- await settle();
204
- expect(fetchMock).not.toHaveBeenCalled();
205
- expect(location.hash).toBe('#sec');
206
- expect(scrolled).toHaveBeenCalled();
207
- });
208
- it('does not refetch on a hash-only popstate', async () => {
209
- history.pushState(history.state, '', '/#a');
210
- window.dispatchEvent(new PopStateEvent('popstate', { state: history.state }));
211
- await settle();
212
- expect(fetchMock).not.toHaveBeenCalled();
213
- });
214
- it('a same-page link with a hash scrolls instead of fetching', async () => {
215
- await krateRouter.push('/docs');
216
- fetchMock.mockClear();
217
- await krateRouter.push('/docs#part');
218
- expect(fetchMock).not.toHaveBeenCalled();
219
- expect(location.href).toBe('http://localhost:3000/docs#part');
220
- });
221
- });
222
- describe('scroll restoration', () => {
223
- it('restores the scroll position of the entry being returned to', async () => {
224
- routes['/'] = { body: page('Home', '<h1>Home</h1>') };
225
- const homeState = history.state;
226
- window.scrollTo(0, 420);
227
- await krateRouter.push('/about');
228
- expect(window.scrollY).toBe(0);
229
- const aboutState = history.state;
230
- window.scrollTo(0, 77);
231
- // Simulate the browser's history step back to "/": the URL and state
232
- // change first, then popstate fires.
233
- history.replaceState(homeState, '', '/');
234
- window.dispatchEvent(new PopStateEvent('popstate', { state: homeState }));
235
- await settle();
236
- expect(document.title).toBe('Home');
237
- expect(window.scrollY).toBe(420);
238
- history.replaceState(aboutState, '', '/about');
239
- window.dispatchEvent(new PopStateEvent('popstate', { state: aboutState }));
240
- await settle();
241
- expect(document.title).toBe('About');
242
- expect(window.scrollY).toBe(77);
243
- });
244
- });
245
- describe('error handling', () => {
246
- it('shows a server-rendered 404 document in place and reports the status', async () => {
247
- const errs = events('krate:navigate-error');
248
- routes['/missing'] = { status: 404, body: page('Not found', '<h1>Not found</h1>') };
249
- await krateRouter.push('/missing');
250
- expect(document.title).toBe('Not found');
251
- expect(location.pathname).toBe('/missing');
252
- expect(errs).toEqual([{ url: 'http://localhost:3000/missing', status: 404 }]);
253
- expect(hardNavs).toEqual([]);
254
- });
255
- it('falls back to <basePath>/404.html when the 404 response is not HTML', async () => {
256
- globalThis.__KRATE_CFG__ = { viewTransitions: false, basePath: '/app' };
257
- routes['/app/gone'] = { status: 404, body: 'nope', type: 'text/plain' };
258
- routes['/app/404.html'] = { body: page('404', '<h1>Lost</h1>') };
259
- await krateRouter.push('/app/gone');
260
- expect(document.querySelector('#root h1').textContent).toBe('Lost');
261
- expect(fetchMock.mock.calls.map((c) => new URL(c[0], location.href).pathname)).toContain('/app/404.html');
262
- });
263
- it('uses /500.html for server errors without an HTML body', async () => {
264
- routes['/boom'] = { status: 503, body: '', type: 'text/plain' };
265
- routes['/500.html'] = { body: page('Error', '<h1>Broken</h1>') };
266
- await krateRouter.push('/boom');
267
- expect(document.querySelector('#root h1').textContent).toBe('Broken');
268
- });
269
- it('does not show the 404 page for 403 responses', async () => {
270
- routes['/secret'] = { status: 403, body: 'forbidden', type: 'text/plain' };
271
- routes['/404.html'] = { body: page('404', '<h1>Lost</h1>') };
272
- await krateRouter.push('/secret');
273
- expect(hardNavs).toEqual([['http://localhost:3000/secret', false]]);
274
- expect(document.querySelector('#root h1').textContent).toBe('Home');
275
- });
276
- it('emits krate:navigate-error on network failure, then hard-navigates', async () => {
277
- const errs = events('krate:navigate-error');
278
- routes['/net'] = { fail: new TypeError('Failed to fetch') };
279
- await krateRouter.push('/net');
280
- expect(errs.length).toBe(1);
281
- expect(errs[0].status).toBe(0);
282
- expect(hardNavs).toEqual([['http://localhost:3000/net', false]]);
283
- });
284
- it('lets the app cancel the hard-reload fallback', async () => {
285
- const stop = (e) => e.preventDefault();
286
- window.addEventListener('krate:navigate-error', stop);
287
- routes['/net'] = { fail: new TypeError('Failed to fetch') };
288
- await krateRouter.push('/net');
289
- window.removeEventListener('krate:navigate-error', stop);
290
- expect(hardNavs).toEqual([]);
291
- expect(location.pathname).toBe('/');
292
- });
293
- it('never uses document.write', async () => {
294
- const spy = vi.spyOn(document, 'write');
295
- routes['/missing'] = { status: 404, body: page('Not found', '<h1>Not found</h1>') };
296
- await krateRouter.push('/missing');
297
- expect(spy).not.toHaveBeenCalled();
298
- });
299
116
  });
300
117
  describe('races', () => {
301
118
  it('a slower superseded navigation never overwrites a newer one', async () => {
@@ -311,249 +128,3 @@ describe('races', () => {
311
128
  expect(location.pathname).toBe('/about');
312
129
  });
313
130
  });
314
- describe('in-document steps while a page loads', () => {
315
- it('a hash link cancels the navigation still loading', async () => {
316
- let open;
317
- routes['/slow'] = { body: page('Slow', '<h1>Slow</h1>'), gate: new Promise((r) => (open = r)) };
318
- const loading = krateRouter.push('/slow');
319
- await settle();
320
- await krateRouter.push('/#top');
321
- open();
322
- await loading;
323
- await settle();
324
- expect(location.pathname + location.hash).toBe('/#top');
325
- expect(document.querySelector('#root h1').textContent).toBe('Home');
326
- expect(krateRouter.getState().status).toBe('idle');
327
- });
328
- it('going back over a hash entry cancels the navigation still loading', async () => {
329
- await krateRouter.push('/#a');
330
- await krateRouter.push('/#b');
331
- let open;
332
- routes['/slow'] = { body: page('Slow', '<h1>Slow</h1>'), gate: new Promise((r) => (open = r)) };
333
- const loading = krateRouter.push('/slow');
334
- await settle();
335
- history.back();
336
- await settle();
337
- open();
338
- await loading;
339
- await settle();
340
- expect(location.pathname + location.hash).toBe('/#a');
341
- expect(document.querySelector('#root h1').textContent).toBe('Home');
342
- });
343
- });
344
- describe('prefetch cache', () => {
345
- it('serves a prefetched document once, then refetches', async () => {
346
- await krateRouter.prefetch('/about');
347
- expect(fetchMock).toHaveBeenCalledTimes(1);
348
- await krateRouter.push('/about');
349
- expect(fetchMock).toHaveBeenCalledTimes(1);
350
- routes['/'] = { body: page('Home', '<h1>Home</h1>') };
351
- await krateRouter.push('/');
352
- await krateRouter.push('/about');
353
- // The cache hit was consumed: revisiting fetches fresh HTML.
354
- expect(fetchMock.mock.calls.filter((c) => String(c[0]).endsWith('/about')).length).toBe(2);
355
- });
356
- it('keeps the fragment of the link when the document was prefetched', async () => {
357
- routes['/about'] = { body: page('About', '<h1>About</h1><h2 id="team">Team</h2>') };
358
- const original = Element.prototype.scrollIntoView;
359
- const scrolled = vi.fn();
360
- Element.prototype.scrollIntoView = scrolled;
361
- try {
362
- await krateRouter.prefetch('/about#team');
363
- await krateRouter.push('/about#team');
364
- await settle();
365
- expect(location.pathname + location.hash).toBe('/about#team');
366
- expect(scrolled).toHaveBeenCalled();
367
- }
368
- finally {
369
- Element.prototype.scrollIntoView = original;
370
- }
371
- });
372
- it('expires entries after the TTL', async () => {
373
- globalThis.__KRATE_CFG__ = { viewTransitions: false, prefetchTTL: 0 };
374
- await krateRouter.prefetch('/about');
375
- await new Promise((r) => setTimeout(r, 5));
376
- await krateRouter.push('/about');
377
- expect(fetchMock).toHaveBeenCalledTimes(2);
378
- });
379
- it('invalidatePrefetchCache drops entries', async () => {
380
- await krateRouter.prefetch('/about');
381
- invalidatePrefetchCache('/about');
382
- await krateRouter.push('/about');
383
- expect(fetchMock).toHaveBeenCalledTimes(2);
384
- });
385
- it('a prefetch in flight when the cache is invalidated does not repopulate it', async () => {
386
- let release;
387
- routes['/about'].gate = new Promise((r) => (release = r));
388
- const inflight = krateRouter.prefetch('/about');
389
- await settle();
390
- invalidatePrefetchCache();
391
- release();
392
- await inflight;
393
- await krateRouter.push('/about');
394
- // The stale response was dropped, so navigating fetched again.
395
- expect(fetchMock).toHaveBeenCalledTimes(2);
396
- });
397
- it('invalidating one URL also drops its prefetch in flight', async () => {
398
- let release;
399
- routes['/about'].gate = new Promise((r) => (release = r));
400
- const inflight = krateRouter.prefetch('/about');
401
- await settle();
402
- invalidatePrefetchCache('/about');
403
- release();
404
- await inflight;
405
- await krateRouter.push('/about');
406
- expect(fetchMock).toHaveBeenCalledTimes(2);
407
- });
408
- it('does not cache error responses', async () => {
409
- routes['/missing'] = { status: 404, body: page('Not found', '') };
410
- await krateRouter.prefetch('/missing');
411
- await krateRouter.push('/missing');
412
- expect(fetchMock).toHaveBeenCalledTimes(2);
413
- });
414
- });
415
- describe('refresh and revalidation', () => {
416
- it('refresh() refetches the current route bypassing the cache and keeps history', async () => {
417
- await krateRouter.push('/about');
418
- routes['/about'] = { body: page('About v2', '<h1>About v2</h1>') };
419
- await krateRouter.prefetch('/about');
420
- const len = history.length;
421
- window.scrollTo(0, 33);
422
- await krateRouter.refresh();
423
- expect(document.title).toBe('About v2');
424
- expect(history.length).toBe(len);
425
- expect(window.scrollY).toBe(33);
426
- const last = fetchMock.mock.calls[fetchMock.mock.calls.length - 1];
427
- expect(last[1].cache).toBe('no-cache');
428
- });
429
- it('krate:revalidate refreshes the current route', async () => {
430
- await krateRouter.push('/about');
431
- routes['/about'] = { body: page('Fresh', '<h1>Fresh</h1>') };
432
- window.dispatchEvent(new CustomEvent('krate:revalidate', { detail: { paths: ['/about'] } }));
433
- await settle();
434
- expect(document.title).toBe('Fresh');
435
- });
436
- });
437
- describe('active links', () => {
438
- it('marks exact matches with aria-current and segments separately', async () => {
439
- await krateRouter.push('/docs/intro');
440
- const docs = document.querySelector('a[href="/docs"]');
441
- const old = document.querySelector('a[href="/docs-old"]');
442
- expect(docs.getAttribute('aria-current')).toBeNull();
443
- expect(docs.getAttribute('data-krate-active')).toBe('segment');
444
- expect(old.hasAttribute('data-krate-active')).toBe(false);
445
- await krateRouter.push('/docs');
446
- expect(document.querySelector('a[href="/docs"]').getAttribute('aria-current')).toBe('page');
447
- });
448
- });
449
- describe('forms', () => {
450
- it('intercepts GET form submissions', async () => {
451
- routes['/search'] = { body: page('Search', '<h1>Results</h1>') };
452
- document.getElementById('root').innerHTML =
453
- '<form action="/search"><input name="q" value="krate"><button name="go" value="1">Go</button></form>';
454
- const form = document.querySelector('form');
455
- const ev = new Event('submit', { bubbles: true, cancelable: true });
456
- ev.submitter = form.querySelector('button');
457
- form.dispatchEvent(ev);
458
- expect(ev.defaultPrevented).toBe(true);
459
- await settle();
460
- expect(location.pathname + location.search).toBe('/search?q=krate&go=1');
461
- expect(document.title).toBe('Search');
462
- });
463
- it('leaves POST forms alone', async () => {
464
- document.getElementById('root').innerHTML = '<form method="post" action="/search"><input name="q"></form>';
465
- const ev = new Event('submit', { bubbles: true, cancelable: true });
466
- document.querySelector('form').dispatchEvent(ev);
467
- expect(ev.defaultPrevented).toBe(false);
468
- });
469
- });
470
- describe('focus', () => {
471
- it('focuses the root temporarily and removes tabindex on blur', async () => {
472
- await krateRouter.push('/about');
473
- const root = document.getElementById('root');
474
- expect(document.activeElement).toBe(root);
475
- expect(root.getAttribute('tabindex')).toBe('-1');
476
- root.blur();
477
- expect(root.hasAttribute('tabindex')).toBe(false);
478
- });
479
- });
480
- describe('fallback fade and reduced motion', () => {
481
- function stubReducedMotion(reduce) {
482
- vi.stubGlobal('matchMedia', (q) => ({
483
- matches: reduce && q.includes('prefers-reduced-motion'),
484
- media: q,
485
- addEventListener() { },
486
- removeEventListener() { },
487
- addListener() { },
488
- removeListener() { },
489
- }));
490
- window.matchMedia = globalThis.matchMedia;
491
- }
492
- async function rootStyleDuringFetch() {
493
- let release;
494
- routes['/about'].gate = new Promise((r) => (release = r));
495
- const p = krateRouter.push('/about');
496
- await settle();
497
- const el = document.getElementById('root');
498
- const seen = { transition: el.style.transition, opacity: el.style.opacity };
499
- release();
500
- await p;
501
- await settle();
502
- return seen;
503
- }
504
- it('applies the opacity fade without View Transitions', async () => {
505
- stubReducedMotion(false);
506
- const seen = await rootStyleDuringFetch();
507
- expect(seen.opacity).toBe('0');
508
- expect(seen.transition).toContain('opacity');
509
- });
510
- it('applies no fade under prefers-reduced-motion', async () => {
511
- stubReducedMotion(true);
512
- const seen = await rootStyleDuringFetch();
513
- expect(seen.opacity).toBe('');
514
- expect(seen.transition).toBe('');
515
- expect(document.querySelector('#root h1').textContent).toBe('About');
516
- });
517
- });
518
- describe('inline boot scripts', () => {
519
- const bootPage = (title) => page(title, `<h1>${title}</h1>${link('/', 'Home')}<script data-krate-boot>window.__boots=1;</script>`);
520
- // happy-dom does not execute inline scripts: count the ones handed to the document.
521
- let ran;
522
- beforeEach(() => {
523
- ran = [];
524
- const append = document.head.appendChild.bind(document.head);
525
- vi.spyOn(document.head, 'appendChild').mockImplementation(((node) => {
526
- if (node instanceof HTMLScriptElement && !node.src)
527
- ran.push(node.text);
528
- return append(node);
529
- }));
530
- });
531
- afterEach(() => vi.restoreAllMocks());
532
- it('runs a boot script of the new page once, not on every visit', async () => {
533
- routes['/aria'] = { body: bootPage('Aria') };
534
- routes['/aria2'] = { body: bootPage('Aria2') };
535
- await krateRouter.push('/aria');
536
- await settle();
537
- expect(ran).toEqual(['window.__boots=1;']);
538
- await krateRouter.push('/aria2');
539
- await krateRouter.push('/about');
540
- await krateRouter.push('/aria');
541
- await settle();
542
- expect(ran).toEqual(['window.__boots=1;']);
543
- });
544
- it('does not rerun the boot script the first document already ran', async () => {
545
- destroyRouter();
546
- document.body.innerHTML += '<script data-krate-boot>window.__boots=1;</script>';
547
- initRouter();
548
- routes['/aria'] = { body: bootPage('Aria') };
549
- await krateRouter.push('/aria');
550
- await settle();
551
- expect(ran).toEqual([]);
552
- });
553
- it('leaves ordinary inline scripts alone', async () => {
554
- routes['/plain'] = { body: page('Plain', '<h1>Plain</h1><script>window.__boots=99;</script>') };
555
- await krateRouter.push('/plain');
556
- await settle();
557
- expect(ran).toEqual([]);
558
- });
559
- });
package/dist/router.js CHANGED
@@ -6,6 +6,7 @@
6
6
  // by every page's hydration script) only refreshes per-page bindings and never
7
7
  // loses the prefetch cache, saved scroll positions or the in-flight navigation.
8
8
  import { basePath, withBase } from './base-path.js';
9
+ import { siteConfig } from './site-config.js';
9
10
  /**
10
11
  * The shared runtime chunk is loaded once and must persist across SPA
11
12
  * navigations. Page-specific hydration scripts, in contrast, must be
@@ -14,7 +15,7 @@ import { basePath, withBase } from './base-path.js';
14
15
  */
15
16
  const RUNTIME_CHUNK_RE = /\/chunks\/runtime\.[^/]+\.js$/;
16
17
  function runtimeConfig() {
17
- return globalThis.__KRATE_CFG__ || {};
18
+ return siteConfig();
18
19
  }
19
20
  /** Strips the base path from a pathname so route comparisons are consistent. */
20
21
  function stripBase(pathname) {
@@ -627,6 +628,36 @@ function reconcileHeadMeta(doc) {
627
628
  document.head.appendChild(document.importNode(el, true));
628
629
  });
629
630
  }
631
+ let docAttrSnap = null;
632
+ function attrsOf(el) {
633
+ const out = {};
634
+ if (el)
635
+ for (const a of Array.from(el.attributes))
636
+ out[a.name] = a.value;
637
+ return out;
638
+ }
639
+ function docAttrsOf(d) {
640
+ return { html: attrsOf(d.documentElement), body: attrsOf(d.body) };
641
+ }
642
+ function reconcileDocAttrs(doc) {
643
+ const prev = docAttrSnap ?? docAttrsOf(document);
644
+ const next = docAttrsOf(doc);
645
+ const apply = (target, before, after) => {
646
+ if (!target)
647
+ return;
648
+ for (const name of new Set([...Object.keys(before), ...Object.keys(after)])) {
649
+ if (before[name] === after[name])
650
+ continue;
651
+ if (after[name] === undefined)
652
+ target.removeAttribute(name);
653
+ else
654
+ target.setAttribute(name, after[name]);
655
+ }
656
+ };
657
+ apply(document.documentElement, prev.html, next.html);
658
+ apply(document.body, prev.body, next.body);
659
+ docAttrSnap = next;
660
+ }
630
661
  function scriptsToLoad(doc, baseUrl) {
631
662
  const keep = new Set();
632
663
  document.querySelectorAll('script[src]:not([data-krate-spa])').forEach((s) => keep.add(s.src));
@@ -972,6 +1003,7 @@ async function commitDocument(loaded, req, seq) {
972
1003
  interceptSnapshots.clear();
973
1004
  sheets.commit();
974
1005
  reconcileHeadMeta(doc);
1006
+ reconcileDocAttrs(doc);
975
1007
  applyViewTransitionNames(document);
976
1008
  };
977
1009
  await runMutation(mutate);
@@ -1050,6 +1082,11 @@ function runMutation(mutate) {
1050
1082
  const vt = document.startViewTransition(once);
1051
1083
  if (vt && vt.finished && typeof vt.finished.catch === 'function')
1052
1084
  vt.finished.catch(() => { });
1085
+ // A newer navigation skips this transition; ready then rejects with
1086
+ // "Transition was skipped", which would otherwise surface as an unhandled
1087
+ // rejection on the page.
1088
+ if (vt && vt.ready && typeof vt.ready.catch === 'function')
1089
+ vt.ready.catch(() => { });
1053
1090
  const done = vt && vt.updateCallbackDone;
1054
1091
  if (done && typeof done.then === 'function') {
1055
1092
  return done.then(() => once(), () => once());
@@ -1790,6 +1827,7 @@ export function initRouter() {
1790
1827
  document.querySelectorAll('script[data-krate-boot]').forEach((s) => bootRan.add(s.textContent || ''));
1791
1828
  renderedPath = pathOf(location.href);
1792
1829
  currentChain = readRouteChain(document);
1830
+ docAttrSnap = docAttrsOf(document);
1793
1831
  docPath = renderedPath;
1794
1832
  currentKey = entryKey(history.state) || newKey();
1795
1833
  if (entryKey(history.state) === undefined) {
@@ -57,6 +57,8 @@ export interface HandlerConfig {
57
57
  ppr: boolean;
58
58
  pprRevalidate: number;
59
59
  };
60
+ /** Page URL form: "always" (default) redirects /x to /x/, "never" redirects /x/ to /x, "ignore" serves both. */
61
+ trailingSlash?: "always" | "never" | "ignore";
60
62
  }
61
63
  export interface HandlerPage {
62
64
  route: string;
@@ -67,12 +69,29 @@ export interface HandlerPage {
67
69
  serverComponents?: boolean;
68
70
  /** Source directory relative to the pages root, route groups kept (segment page lookup). */
69
71
  segDir?: string;
72
+ /** A segment page that renders per request: reached through its synthetic route, never a URL. */
73
+ segment?: boolean;
70
74
  }
75
+ /**
76
+ * A per-request metadata route. `path` is an exact URL; `prefix` and `suffix`
77
+ * match /sitemap/<id>.xml, where `key` ends in "/[id]".
78
+ */
79
+ export interface MetaRoute {
80
+ path?: string;
81
+ prefix?: string;
82
+ suffix?: string;
83
+ key: string;
84
+ }
85
+ /** The API route key serving URL path p, or "" when no metadata route does. */
86
+ export declare function matchMetaRoute(routes: MetaRoute[] | undefined, p: string): string;
71
87
  export interface ActionEntry {
72
88
  id: string;
73
89
  export: string;
74
90
  file: string;
75
91
  source?: string;
92
+ /** A hoisted inline server action; `captures` names the sealed values it receives first. */
93
+ inline?: boolean;
94
+ captures?: string[];
76
95
  }
77
96
  /** Build data the compiler inlines into the server bundle. */
78
97
  export interface KrateServerData {
@@ -106,6 +125,17 @@ export interface KrateServerData {
106
125
  staticPages?: Record<string, string>;
107
126
  /** API route keys: file path under the API dir without extension ("items/[id]"). */
108
127
  apiRoutes: string[];
128
+ /**
129
+ * Per-route request budgets in seconds (`export const maxDuration`), keyed
130
+ * like apiRoutes. A handler still running at the deadline is aborted
131
+ * (request.signal) and the request answered 504.
132
+ */
133
+ apiMaxDuration?: Record<string, number>;
134
+ /**
135
+ * Metadata routes (robots.ts, sitemap.ts, manifest.ts) that run per request:
136
+ * a public URL served by the API route `key`.
137
+ */
138
+ metaRoutes?: MetaRoute[];
109
139
  actions: ActionEntry[];
110
140
  hasMiddleware: boolean;
111
141
  }
@@ -133,6 +163,12 @@ export interface StaticLayer {
133
163
  export interface HandlerContext {
134
164
  /** Keeps the instance alive for work that outlives the response. */
135
165
  waitUntil?(work: Promise<unknown>): void;
166
+ /** Cloudflare only: let the request fall through to the origin when the Worker throws. */
167
+ passThroughOnException?(): void;
168
+ /** The platform's bindings (the Worker `env` on cloudflare), reachable from page code through getPlatform(). */
169
+ env?: unknown;
170
+ /** Cloudflare's `request.cf` properties. */
171
+ cf?: Record<string, unknown>;
136
172
  }
137
173
  export interface HandlerOptions {
138
174
  target: DeployTarget;
@@ -162,5 +198,17 @@ export interface HandlerOptions {
162
198
  flashSecret?: string;
163
199
  }
164
200
  export type KrateHandler = (request: Request, ctx?: HandlerContext) => Promise<Response>;
201
+ /**
202
+ * Runs fn with the platform of a request (or of a Worker event such as a cron
203
+ * trigger) published to getPlatform() / getCloudflareContext(). The generated
204
+ * Cloudflare Worker wraps the exports of src/cloudflare.ts with it.
205
+ */
206
+ export declare function runWithPlatform<R>(target: DeployTarget, ctx: HandlerContext, fn: () => R): R;
207
+ /**
208
+ * Opens the closure token of an inline server action: AES-256-GCM over the
209
+ * JSON of the captured values, authenticated against the action id, with the
210
+ * key derived from the action secret (the format the server renderer seals).
211
+ */
212
+ export declare function openInlineToken(token: unknown, entry: ActionEntry, secret: string): Promise<unknown[]>;
165
213
  export declare function createKrateHandler(options: HandlerOptions): KrateHandler;
166
214
  export { isDynamicPattern };