@krate/runtime 0.5.0-rc.13 → 0.5.0-rc.15
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/action-context.d.ts +2 -0
- package/dist/action-context.js +12 -1
- package/dist/action-seal.d.ts +5 -0
- package/dist/action-seal.js +105 -0
- package/dist/actions.js +7 -1
- package/dist/cache-scope.d.ts +2 -0
- package/dist/dev/api.d.ts +93 -0
- package/dist/dev/api.js +2 -0
- package/dist/dev/app.d.ts +165 -0
- package/dist/dev/app.js +1204 -0
- package/dist/dev/commands.d.ts +49 -0
- package/dist/dev/commands.js +114 -0
- package/dist/dev/highlight.d.ts +4 -0
- package/dist/dev/highlight.js +126 -0
- package/dist/dev/icons.d.ts +4 -0
- package/dist/dev/icons.js +57 -0
- package/dist/dev/inspect.d.ts +55 -0
- package/dist/dev/inspect.js +256 -0
- package/dist/dev/inspector.d.ts +39 -0
- package/dist/dev/inspector.js +348 -0
- package/dist/dev/issues.d.ts +83 -0
- package/dist/dev/issues.js +166 -0
- package/dist/dev/modal.d.ts +16 -0
- package/dist/dev/modal.js +836 -0
- package/dist/dev/native.d.ts +53 -0
- package/dist/dev/native.js +95 -0
- package/dist/dev/palette.d.ts +9 -0
- package/dist/dev/palette.js +250 -0
- package/dist/dev/panel.d.ts +31 -0
- package/dist/dev/panel.js +848 -0
- package/dist/dev/requests.d.ts +36 -0
- package/dist/dev/requests.js +150 -0
- package/dist/dev/settings.d.ts +32 -0
- package/dist/dev/settings.js +78 -0
- package/dist/dev/sourcemap.d.ts +22 -0
- package/dist/dev/sourcemap.js +148 -0
- package/dist/dev/stack.d.ts +38 -0
- package/dist/dev/stack.js +115 -0
- package/dist/dev/styles.d.ts +1 -0
- package/dist/dev/styles.js +424 -0
- package/dist/dev/util.d.ts +63 -0
- package/dist/dev/util.js +190 -0
- package/dist/dev-overlay.d.ts +9 -83
- package/dist/dev-overlay.js +17 -1038
- package/dist/flight-props.d.ts +2 -0
- package/dist/flight-props.js +12 -1
- package/dist/handler-routing.js +7 -1
- package/dist/island-swap.js +10 -1
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +441 -871
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-list.js +1 -1
- package/dist/krate-f-navigation.js +1 -1
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-island-swap.js +1 -1
- package/dist/krate-runtime.js +5 -5
- package/dist/list.js +23 -1
- package/dist/metadata.js +23 -12
- package/dist/navigation-server.d.ts +1 -2
- package/dist/navigation-server.js +1 -2
- package/dist/navigation.d.ts +1 -1
- package/dist/navigation.js +7 -2
- package/dist/process-guard.d.ts +23 -0
- package/dist/process-guard.js +45 -0
- package/dist/react-types.d.ts +29 -0
- package/dist/react-types.js +1 -0
- package/dist/react.d.ts +2 -0
- package/dist/react.js +3 -0
- package/dist/request-context.d.ts +15 -0
- package/dist/request-context.js +41 -0
- package/dist/router.js +17 -0
- package/dist/server-handler.d.ts +4 -0
- package/dist/server-handler.js +43 -8
- package/dist/server-renderer.js +94 -2
- package/dist/server.d.ts +1 -1
- package/dist/server.js +57 -11
- package/dist/signal.d.ts +8 -0
- package/dist/signal.js +4 -0
- package/dist/ssr-core.d.ts +5 -0
- package/dist/ssr-core.js +49 -7
- package/package.json +5 -1
package/dist/list.js
CHANGED
|
@@ -32,7 +32,29 @@ function keyOf(keyFn, item, i) {
|
|
|
32
32
|
if (!keyFn)
|
|
33
33
|
return String(i);
|
|
34
34
|
const k = keyFn(item, i);
|
|
35
|
-
|
|
35
|
+
if (k == null)
|
|
36
|
+
return String(i);
|
|
37
|
+
if (typeof k === 'object' || typeof k === 'function')
|
|
38
|
+
return objectKey(k);
|
|
39
|
+
return '$' + String(k);
|
|
40
|
+
}
|
|
41
|
+
// Object keys (a DOM node, say) have no useful string form, so they are keyed
|
|
42
|
+
// by identity: a stable id per object.
|
|
43
|
+
let objectIds;
|
|
44
|
+
let nextObjectId = 0;
|
|
45
|
+
let warnedObjectKey = false;
|
|
46
|
+
function objectKey(k) {
|
|
47
|
+
const ids = objectIds || (objectIds = new WeakMap());
|
|
48
|
+
let id = ids.get(k);
|
|
49
|
+
if (id === undefined) {
|
|
50
|
+
id = ++nextObjectId;
|
|
51
|
+
ids.set(k, id);
|
|
52
|
+
}
|
|
53
|
+
if (!warnedObjectKey) {
|
|
54
|
+
warnedObjectKey = true;
|
|
55
|
+
console.error('A list key is a DOM node or object. Use a string or number as the key; Krate keys the row by object identity instead.');
|
|
56
|
+
}
|
|
57
|
+
return '@o' + id;
|
|
36
58
|
}
|
|
37
59
|
function decodeKey(s) {
|
|
38
60
|
try {
|
package/dist/metadata.js
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
// viewport (string), verification, appleWebApp, formatDetection, category,
|
|
15
15
|
// itunes, appLinks, archives, assets, bookmarks and other. metadataBase resolves
|
|
16
16
|
// relative URLs. Anything else is ignored.
|
|
17
|
-
import { httpFallbackStatus, redirectTarget, thenableRecord } from './request-context.js';
|
|
17
|
+
import { httpFallbackStatus, isDynamicUsageError, redirectTarget, thenableRecord } from './request-context.js';
|
|
18
18
|
function isThenable(v) {
|
|
19
19
|
return !!v && typeof v.then === 'function';
|
|
20
20
|
}
|
|
@@ -93,7 +93,7 @@ export async function resolveMetadata(segments, rawProps) {
|
|
|
93
93
|
// notFound(), forbidden(), unauthorized() and redirect() in
|
|
94
94
|
// generateMetadata answer the request; any other error costs only the
|
|
95
95
|
// segment's metadata.
|
|
96
|
-
if (httpFallbackStatus(error) || redirectTarget(error))
|
|
96
|
+
if (httpFallbackStatus(error) || redirectTarget(error) || isDynamicUsageError(error))
|
|
97
97
|
throw error;
|
|
98
98
|
errors.push({ file: seg.file || '', error });
|
|
99
99
|
own = undefined;
|
|
@@ -341,10 +341,21 @@ export function renderMetadataTags(md, templates = {}) {
|
|
|
341
341
|
if (parts.length)
|
|
342
342
|
push(meta('name', 'format-detection', parts.join(', ')));
|
|
343
343
|
}
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
344
|
+
// Like Next.js, an openGraph or twitter object without its own title takes
|
|
345
|
+
// the resolved top-level title (already templated); twitter takes the
|
|
346
|
+
// openGraph title and description first. Descriptions are not copied from
|
|
347
|
+
// the top level, so a <Head> description override leaves no stale copy.
|
|
348
|
+
const topTitle = typeof md.title === 'string' ? md.title : '';
|
|
349
|
+
let ogTitle = '';
|
|
350
|
+
if (md.openGraph) {
|
|
351
|
+
ogTitle = titleOf(md.openGraph.title, templates.openGraph) || topTitle;
|
|
352
|
+
renderOpenGraph(md.openGraph, base, ogTitle, md.openGraph.description, push);
|
|
353
|
+
}
|
|
354
|
+
if (md.twitter) {
|
|
355
|
+
const twTitle = titleOf(md.twitter.title, templates.twitter) || ogTitle || topTitle;
|
|
356
|
+
const twDescription = md.twitter.description || md.openGraph?.description;
|
|
357
|
+
renderTwitter(md.twitter, base, twTitle, twDescription, push);
|
|
358
|
+
}
|
|
348
359
|
if (md.appLinks) {
|
|
349
360
|
for (const [platform, entries] of Object.entries(md.appLinks))
|
|
350
361
|
for (const entry of toArray(entries))
|
|
@@ -378,9 +389,9 @@ function renderIcons(icons, base, push) {
|
|
|
378
389
|
emit(o.apple, 'apple-touch-icon');
|
|
379
390
|
emit(o.other, 'icon');
|
|
380
391
|
}
|
|
381
|
-
function renderOpenGraph(og, base,
|
|
382
|
-
push(meta('property', 'og:title',
|
|
383
|
-
push(meta('property', 'og:description',
|
|
392
|
+
function renderOpenGraph(og, base, title, description, push) {
|
|
393
|
+
push(meta('property', 'og:title', title));
|
|
394
|
+
push(meta('property', 'og:description', description));
|
|
384
395
|
push(meta('property', 'og:url', resolveBaseJoin(og.url, base)));
|
|
385
396
|
push(meta('property', 'og:site_name', og.siteName));
|
|
386
397
|
push(meta('property', 'og:locale', og.locale));
|
|
@@ -423,7 +434,7 @@ function renderOpenGraph(og, base, template, push) {
|
|
|
423
434
|
push(meta('property', 'profile:gender', og.gender));
|
|
424
435
|
}
|
|
425
436
|
}
|
|
426
|
-
function renderTwitter(tw, base,
|
|
437
|
+
function renderTwitter(tw, base, title, description, push) {
|
|
427
438
|
const images = imageList(tw.images, base);
|
|
428
439
|
const card = tw.card || (images.length > 0 ? 'summary_large_image' : 'summary');
|
|
429
440
|
push(meta('name', 'twitter:card', card));
|
|
@@ -431,8 +442,8 @@ function renderTwitter(tw, base, template, push) {
|
|
|
431
442
|
push(meta('name', 'twitter:site:id', tw.siteId));
|
|
432
443
|
push(meta('name', 'twitter:creator', tw.creator));
|
|
433
444
|
push(meta('name', 'twitter:creator:id', tw.creatorId));
|
|
434
|
-
push(meta('name', 'twitter:title',
|
|
435
|
-
push(meta('name', 'twitter:description',
|
|
445
|
+
push(meta('name', 'twitter:title', title));
|
|
446
|
+
push(meta('name', 'twitter:description', description));
|
|
436
447
|
for (const img of images) {
|
|
437
448
|
push(meta('name', 'twitter:image', img.url));
|
|
438
449
|
push(meta('name', 'twitter:image:alt', img.alt));
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
export { redirect as permanentRedirect };
|
|
1
|
+
export { permanentRedirect } from './action-context.js';
|
|
3
2
|
type ParamValue = string | string[];
|
|
4
3
|
/** The current URL path without the query ("/blog/hello"). */
|
|
5
4
|
export declare function usePathname(): string;
|
|
@@ -2,8 +2,7 @@
|
|
|
2
2
|
// the portable handler). They read the request being rendered, so a page
|
|
3
3
|
// rendered per request sees its own URL. See navigation.ts for the browser side.
|
|
4
4
|
import { getRequestContext } from './request-context.js';
|
|
5
|
-
|
|
6
|
-
export { redirect as permanentRedirect };
|
|
5
|
+
export { permanentRedirect } from './action-context.js';
|
|
7
6
|
/** The URL path of the request: the route pattern with its params filled in. */
|
|
8
7
|
function requestPath() {
|
|
9
8
|
const ctx = getRequestContext();
|
package/dist/navigation.d.ts
CHANGED
|
@@ -51,6 +51,6 @@ export declare function useSelectedLayoutSegments(parallelRouteKey?: string, dep
|
|
|
51
51
|
export declare function useSelectedLayoutSegment(parallelRouteKey?: string, depth?: number): string | null;
|
|
52
52
|
/** Throws the signal the host answers with a redirect while rendering; navigates in the browser. */
|
|
53
53
|
export declare function redirect(url: string): never;
|
|
54
|
-
/** redirect()
|
|
54
|
+
/** redirect() that a page or API route answers with 308 instead of 307. */
|
|
55
55
|
export declare function permanentRedirect(url: string): never;
|
|
56
56
|
export { notFound, forbidden, unauthorized } from './request-context.js';
|
package/dist/navigation.js
CHANGED
|
@@ -223,8 +223,13 @@ export function redirect(url) {
|
|
|
223
223
|
err.__krateRedirect = url;
|
|
224
224
|
throw err;
|
|
225
225
|
}
|
|
226
|
-
/** redirect()
|
|
226
|
+
/** redirect() that a page or API route answers with 308 instead of 307. */
|
|
227
227
|
export function permanentRedirect(url) {
|
|
228
|
-
|
|
228
|
+
if (typeof location !== 'undefined')
|
|
229
|
+
void krateRouter.push(url);
|
|
230
|
+
const err = new Error('Server action redirect to ' + url);
|
|
231
|
+
err.__krateRedirect = url;
|
|
232
|
+
err.__krateRedirectStatus = 308;
|
|
233
|
+
throw err;
|
|
229
234
|
}
|
|
230
235
|
export { notFound, forbidden, unauthorized } from './request-context.js';
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process-level error policy of the SSR renderer.
|
|
3
|
+
*
|
|
4
|
+
* A render error is that request's error: it ends as a 500 or the error page.
|
|
5
|
+
* Node's defaults are harsher for the errors a render leaves behind outside its
|
|
6
|
+
* own promise chain, a rejected promise nobody awaited or a throw from a timer
|
|
7
|
+
* or event callback: they end the process, and every other page then answers
|
|
8
|
+
* 503 until the supervisor has restarted the renderer. Those are logged and the
|
|
9
|
+
* renderer keeps serving. What stays fatal is an uncaught exception that does
|
|
10
|
+
* not belong to any request (the renderer's own code, a failed listener), since
|
|
11
|
+
* the process state can no longer be trusted.
|
|
12
|
+
*/
|
|
13
|
+
/** The part of `process` the guards use. */
|
|
14
|
+
export interface GuardedProcess {
|
|
15
|
+
on(event: 'unhandledRejection' | 'uncaughtException', listener: (...args: any[]) => void): unknown;
|
|
16
|
+
exit(code?: number): unknown;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Installs the policy. An unhandled rejection never ends the renderer. An
|
|
20
|
+
* uncaught exception raised inside a request's async scope is logged; one
|
|
21
|
+
* outside any request exits with status 1, as Node does by default.
|
|
22
|
+
*/
|
|
23
|
+
export declare function installProcessGuards(proc?: GuardedProcess, log?: (...args: unknown[]) => void): void;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process-level error policy of the SSR renderer.
|
|
3
|
+
*
|
|
4
|
+
* A render error is that request's error: it ends as a 500 or the error page.
|
|
5
|
+
* Node's defaults are harsher for the errors a render leaves behind outside its
|
|
6
|
+
* own promise chain, a rejected promise nobody awaited or a throw from a timer
|
|
7
|
+
* or event callback: they end the process, and every other page then answers
|
|
8
|
+
* 503 until the supervisor has restarted the renderer. Those are logged and the
|
|
9
|
+
* renderer keeps serving. What stays fatal is an uncaught exception that does
|
|
10
|
+
* not belong to any request (the renderer's own code, a failed listener), since
|
|
11
|
+
* the process state can no longer be trusted.
|
|
12
|
+
*/
|
|
13
|
+
import { getRequestContext } from './request-context.js';
|
|
14
|
+
function describe(err) {
|
|
15
|
+
if (err instanceof Error)
|
|
16
|
+
return err.stack || `${err.name}: ${err.message}`;
|
|
17
|
+
try {
|
|
18
|
+
return typeof err === 'string' ? err : JSON.stringify(err);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return String(err);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function where() {
|
|
25
|
+
const req = getRequestContext();
|
|
26
|
+
return req ? ` while rendering ${req.method} ${req.url}` : '';
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Installs the policy. An unhandled rejection never ends the renderer. An
|
|
30
|
+
* uncaught exception raised inside a request's async scope is logged; one
|
|
31
|
+
* outside any request exits with status 1, as Node does by default.
|
|
32
|
+
*/
|
|
33
|
+
export function installProcessGuards(proc = process, log = console.error) {
|
|
34
|
+
proc.on('unhandledRejection', (reason) => {
|
|
35
|
+
log(`[krate-ssr] unhandled promise rejection${where()} (the renderer keeps running): ${describe(reason)}`);
|
|
36
|
+
});
|
|
37
|
+
proc.on('uncaughtException', (err) => {
|
|
38
|
+
if (getRequestContext()) {
|
|
39
|
+
log(`[krate-ssr] uncaught exception${where()} (the renderer keeps running): ${describe(err)}`);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
log(`[krate-ssr] uncaught exception outside any request, exiting: ${describe(err)}`);
|
|
43
|
+
proc.exit(1);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/// <reference types="react" />
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Opt-in typing bridge for apps that keep React-typed code (@types/react).
|
|
5
|
+
*
|
|
6
|
+
* Krate's global `JSX.Element` extends the DOM `Node`, which React's
|
|
7
|
+
* `ReactNode` rejects. That breaks two setups:
|
|
8
|
+
*
|
|
9
|
+
* - `jsx: "react-jsx"`: the globals `<Link>`, `<Head>`, ... fail with TS2786.
|
|
10
|
+
* - `jsx: "preserve"` + `jsxImportSource: "@krate/runtime"` (what
|
|
11
|
+
* `krate migrate nextjs` writes): every intrinsic element is a Krate
|
|
12
|
+
* `Element`, which React-typed props (`children: ReactNode`) reject.
|
|
13
|
+
*
|
|
14
|
+
* Importing this file makes `JSX.Element` also a `React.ReactElement`, so it is
|
|
15
|
+
* assignable to `ReactNode` in both setups. Include it once, for example:
|
|
16
|
+
*
|
|
17
|
+
* // src/krate-react.d.ts
|
|
18
|
+
* import "@krate/runtime/react-types";
|
|
19
|
+
*
|
|
20
|
+
* It needs @types/react; plain Krate apps should not import it.
|
|
21
|
+
*/
|
|
22
|
+
declare global {
|
|
23
|
+
namespace JSX {
|
|
24
|
+
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
|
25
|
+
interface Element extends React.ReactElement<any, any> {}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/react.d.ts
CHANGED
|
@@ -142,6 +142,8 @@ export declare function SuspenseList(props: {
|
|
|
142
142
|
export declare const unstable_SuspenseList: typeof SuspenseList;
|
|
143
143
|
/** React 19.2's useEffectEvent: a function that always runs the latest closure. */
|
|
144
144
|
export declare const useEffectEvent: <T extends (...args: never[]) => unknown>(fn: T) => T;
|
|
145
|
+
/** React's `useId()`; the compiler lowers it, this serves modules that reach it through the compat module. */
|
|
146
|
+
export declare const useId: () => string;
|
|
145
147
|
export declare function useRef<T = unknown>(initial?: T): RefObject<T>;
|
|
146
148
|
type EffectCallback = () => void | (() => void);
|
|
147
149
|
/** Passive effect: runs after paint, re-runs when a live dependency changes. */
|
package/dist/react.js
CHANGED
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
import { h, krateTrackNode } from './dom.js';
|
|
21
21
|
import { getOwner, handleError } from './boundary.js';
|
|
22
22
|
import { createSignal, createReducer, isSignalGetter } from './signal.js';
|
|
23
|
+
import { __krate_useId } from './use-id.js';
|
|
23
24
|
import { createEffectDeps, createEffectEvent } from './effects.js';
|
|
24
25
|
import { krateSetRef } from './refs.js';
|
|
25
26
|
import { krateEventRoot } from './events.js';
|
|
@@ -363,6 +364,8 @@ export function SuspenseList(props) {
|
|
|
363
364
|
export const unstable_SuspenseList = SuspenseList;
|
|
364
365
|
/** React 19.2's useEffectEvent: a function that always runs the latest closure. */
|
|
365
366
|
export const useEffectEvent = createEffectEvent;
|
|
367
|
+
/** React's `useId()`; the compiler lowers it, this serves modules that reach it through the compat module. */
|
|
368
|
+
export const useId = __krate_useId;
|
|
366
369
|
export function useRef(initial) {
|
|
367
370
|
return { current: initial ?? null };
|
|
368
371
|
}
|
|
@@ -16,6 +16,8 @@ export interface RequestContext {
|
|
|
16
16
|
cookies: Map<string, string>;
|
|
17
17
|
params: Record<string, string>;
|
|
18
18
|
searchParams: Record<string, string>;
|
|
19
|
+
/** True during build-time prerendering, where request-only APIs bail out. */
|
|
20
|
+
prerender?: boolean;
|
|
19
21
|
}
|
|
20
22
|
/** The current render request, or undefined outside a server render. */
|
|
21
23
|
export declare function getRequestContext(): RequestContext | undefined;
|
|
@@ -81,5 +83,18 @@ export declare function unauthorized(): never;
|
|
|
81
83
|
export declare function accessDeniedStatus(err: unknown): 401 | 403 | 0;
|
|
82
84
|
/** httpFallbackStatus is 404, 403 or 401 for notFound(), forbidden() and unauthorized() signals, else 0. */
|
|
83
85
|
export declare function httpFallbackStatus(err: unknown): 401 | 403 | 404 | 0;
|
|
86
|
+
/**
|
|
87
|
+
* redirectStatus is the HTTP status of a redirect() signal: 307, or 308 for
|
|
88
|
+
* permanentRedirect() (Next.js's NEXT_REDIRECT digest carries it as well).
|
|
89
|
+
*/
|
|
90
|
+
export declare function redirectStatus(err: unknown): 307 | 308;
|
|
84
91
|
/** redirectTarget returns the URL of a redirect() signal, or "" for other errors. */
|
|
85
92
|
export declare function redirectTarget(err: unknown): string;
|
|
93
|
+
/** Thrown when a request-only API is read during build-time prerendering. */
|
|
94
|
+
export interface DynamicUsageError extends Error {
|
|
95
|
+
__krateDynamicUsage: string;
|
|
96
|
+
digest: string;
|
|
97
|
+
}
|
|
98
|
+
export declare function dynamicUsageError(api: string): DynamicUsageError;
|
|
99
|
+
export declare function isDynamicUsageError(err: unknown): err is DynamicUsageError;
|
|
100
|
+
export declare function dynamicUsageReason(err: unknown): string;
|
package/dist/request-context.js
CHANGED
|
@@ -134,6 +134,23 @@ export function httpFallbackStatus(err) {
|
|
|
134
134
|
return 404;
|
|
135
135
|
return accessDeniedStatus(err);
|
|
136
136
|
}
|
|
137
|
+
/**
|
|
138
|
+
* redirectStatus is the HTTP status of a redirect() signal: 307, or 308 for
|
|
139
|
+
* permanentRedirect() (Next.js's NEXT_REDIRECT digest carries it as well).
|
|
140
|
+
*/
|
|
141
|
+
export function redirectStatus(err) {
|
|
142
|
+
if (!err || typeof err !== 'object')
|
|
143
|
+
return 307;
|
|
144
|
+
const e = err;
|
|
145
|
+
if (e.__krateRedirectStatus === 308)
|
|
146
|
+
return 308;
|
|
147
|
+
if (typeof e.digest === 'string' && e.digest.startsWith('NEXT_REDIRECT;')) {
|
|
148
|
+
const parts = e.digest.split(';');
|
|
149
|
+
if (parts[3] === '308' || parts[3] === '301')
|
|
150
|
+
return 308;
|
|
151
|
+
}
|
|
152
|
+
return 307;
|
|
153
|
+
}
|
|
137
154
|
/** redirectTarget returns the URL of a redirect() signal, or "" for other errors. */
|
|
138
155
|
export function redirectTarget(err) {
|
|
139
156
|
if (!err || typeof err !== 'object')
|
|
@@ -150,3 +167,27 @@ export function redirectTarget(err) {
|
|
|
150
167
|
}
|
|
151
168
|
return '';
|
|
152
169
|
}
|
|
170
|
+
export function dynamicUsageError(api) {
|
|
171
|
+
const err = new Error(`Dynamic server usage: ${api} cannot be used while prerendering a static page`);
|
|
172
|
+
err.__krateDynamicUsage = api;
|
|
173
|
+
err.digest = 'DYNAMIC_SERVER_USAGE';
|
|
174
|
+
return err;
|
|
175
|
+
}
|
|
176
|
+
export function isDynamicUsageError(err) {
|
|
177
|
+
if (!err || typeof err !== 'object')
|
|
178
|
+
return false;
|
|
179
|
+
const e = err;
|
|
180
|
+
if (typeof e.__krateDynamicUsage === 'string' && e.__krateDynamicUsage !== '')
|
|
181
|
+
return true;
|
|
182
|
+
return e.digest === 'DYNAMIC_SERVER_USAGE';
|
|
183
|
+
}
|
|
184
|
+
export function dynamicUsageReason(err) {
|
|
185
|
+
if (!err || typeof err !== 'object')
|
|
186
|
+
return 'dynamic server usage';
|
|
187
|
+
const e = err;
|
|
188
|
+
if (typeof e.__krateDynamicUsage === 'string' && e.__krateDynamicUsage !== '')
|
|
189
|
+
return e.__krateDynamicUsage;
|
|
190
|
+
if (typeof e.message === 'string' && e.message !== '')
|
|
191
|
+
return e.message;
|
|
192
|
+
return 'dynamic server usage';
|
|
193
|
+
}
|
package/dist/router.js
CHANGED
|
@@ -2102,6 +2102,21 @@ function clickHandler(e) {
|
|
|
2102
2102
|
scroll: a.getAttribute('data-krate-scroll') !== 'false',
|
|
2103
2103
|
});
|
|
2104
2104
|
}
|
|
2105
|
+
/**
|
|
2106
|
+
* True when the form (or its submit button) runs a client action: an island's
|
|
2107
|
+
* `<form action={fn}>` (react-compat sets `__krateForm` / `__krateFormAction`)
|
|
2108
|
+
* or a server-action form (`data-krate-action`). Those listeners bail once the
|
|
2109
|
+
* event is defaultPrevented, so the router must not claim the submit first.
|
|
2110
|
+
*/
|
|
2111
|
+
function carriesClientAction(form, submitter) {
|
|
2112
|
+
const own = (el) => {
|
|
2113
|
+
if (!el)
|
|
2114
|
+
return false;
|
|
2115
|
+
const a = el;
|
|
2116
|
+
return !!(a.__krateForm || a.__krateFormAction) || el.hasAttribute('data-krate-action');
|
|
2117
|
+
};
|
|
2118
|
+
return own(form) || own(submitter);
|
|
2119
|
+
}
|
|
2105
2120
|
function submitHandler(e) {
|
|
2106
2121
|
if (e.defaultPrevented)
|
|
2107
2122
|
return;
|
|
@@ -2111,6 +2126,8 @@ function submitHandler(e) {
|
|
|
2111
2126
|
if (form.hasAttribute('data-krate-reload'))
|
|
2112
2127
|
return;
|
|
2113
2128
|
const submitter = (e.submitter || null);
|
|
2129
|
+
if (carriesClientAction(form, submitter))
|
|
2130
|
+
return;
|
|
2114
2131
|
const method = ((submitter && submitter.getAttribute('formmethod')) || form.getAttribute('method') || 'get').toLowerCase();
|
|
2115
2132
|
if (method !== 'get')
|
|
2116
2133
|
return;
|
package/dist/server-handler.d.ts
CHANGED
|
@@ -82,6 +82,8 @@ export interface HandlerPage {
|
|
|
82
82
|
segDir?: string;
|
|
83
83
|
/** A segment page that renders per request: reached through its synthetic route, never a URL. */
|
|
84
84
|
segment?: boolean;
|
|
85
|
+
/** Route params of a page expanded from generateStaticParams, whose route is a plain path. */
|
|
86
|
+
params?: Record<string, string>;
|
|
85
87
|
}
|
|
86
88
|
/**
|
|
87
89
|
* A per-request metadata route. `path` is an exact URL; `prefix` and `suffix`
|
|
@@ -229,5 +231,7 @@ export declare function ruleHeaderPairs(h: Record<string, string> | Array<{
|
|
|
229
231
|
* key derived from the action secret (the format the server renderer seals).
|
|
230
232
|
*/
|
|
231
233
|
export declare function openInlineToken(token: unknown, entry: ActionEntry, secret: string): Promise<unknown[]>;
|
|
234
|
+
/** Opens a "k1." token for the action: inline captures, or the arguments a module action was bound to. */
|
|
235
|
+
export declare function openSealedToken(token: unknown, entry: ActionEntry, secret: string): Promise<unknown[]>;
|
|
232
236
|
export declare function createKrateHandler(options: HandlerOptions): KrateHandler;
|
|
233
237
|
export { isDynamicPattern };
|
package/dist/server-handler.js
CHANGED
|
@@ -229,6 +229,13 @@ function decodeInlineValue(v) {
|
|
|
229
229
|
* key derived from the action secret (the format the server renderer seals).
|
|
230
230
|
*/
|
|
231
231
|
export async function openInlineToken(token, entry, secret) {
|
|
232
|
+
const values = await openSealedToken(token, entry, secret);
|
|
233
|
+
if (values.length !== (entry.captures || []).length)
|
|
234
|
+
throw new Error("closure token does not match the action");
|
|
235
|
+
return values;
|
|
236
|
+
}
|
|
237
|
+
/** Opens a "k1." token for the action: inline captures, or the arguments a module action was bound to. */
|
|
238
|
+
export async function openSealedToken(token, entry, secret) {
|
|
232
239
|
if (typeof token !== "string" || !token.startsWith("k1."))
|
|
233
240
|
throw new Error("missing closure token");
|
|
234
241
|
if (!secret)
|
|
@@ -243,7 +250,7 @@ export async function openInlineToken(token, entry, secret) {
|
|
|
243
250
|
const key = await crypto.subtle.importKey("raw", digest, "AES-GCM", false, ["decrypt"]);
|
|
244
251
|
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: raw.subarray(0, 12), additionalData: enc.encode(entry.id) }, key, raw.subarray(12));
|
|
245
252
|
const values = JSON.parse(new TextDecoder().decode(plain));
|
|
246
|
-
if (!Array.isArray(values)
|
|
253
|
+
if (!Array.isArray(values))
|
|
247
254
|
throw new Error("closure token does not match the action");
|
|
248
255
|
return values.map(decodeInlineValue);
|
|
249
256
|
}
|
|
@@ -361,10 +368,17 @@ export function createKrateHandler(options) {
|
|
|
361
368
|
for (const p of pagesBySpecificity) {
|
|
362
369
|
const params = matchRoutePattern(urlPath, p.route);
|
|
363
370
|
if (params)
|
|
364
|
-
return { page: p, params };
|
|
371
|
+
return { page: p, params: p.params && Object.keys(params).length === 0 ? { ...p.params } : params };
|
|
365
372
|
}
|
|
366
373
|
return null;
|
|
367
374
|
}
|
|
375
|
+
const ssgRoutes = data.allPages.filter((p) => p.mode === "ssg").map((p) => p.route);
|
|
376
|
+
/** A prerendered page that matches urlPath with a more specific route than the request-time page that did. */
|
|
377
|
+
function ssgShadows(urlPath, page) {
|
|
378
|
+
if (!page)
|
|
379
|
+
return false;
|
|
380
|
+
return ssgRoutes.some((r) => compareRouteSpecificity(r, page.route) < 0 && matchRoutePattern(urlPath, r) !== null);
|
|
381
|
+
}
|
|
368
382
|
const templates = [...data.templates].sort((a, b) => compareRouteSpecificity(a.pattern, b.pattern));
|
|
369
383
|
const corsOrigins = cfg.cors.origins.length ? cfg.cors.origins : ["*"];
|
|
370
384
|
// Middleware
|
|
@@ -583,6 +597,8 @@ export function createKrateHandler(options) {
|
|
|
583
597
|
if (k !== "host")
|
|
584
598
|
out[canonicalHeader(k)] = v;
|
|
585
599
|
});
|
|
600
|
+
// The Go server passes Host (Go hoists it out of the header map); so do we.
|
|
601
|
+
out["Host"] = rs.headers.get("host") || new URL(rs.request.url).host;
|
|
586
602
|
return out;
|
|
587
603
|
}
|
|
588
604
|
function canonicalHeader(k) {
|
|
@@ -788,7 +804,7 @@ export function createKrateHandler(options) {
|
|
|
788
804
|
let route = requestRoute(rs.path);
|
|
789
805
|
const found = findPageForRoute(route);
|
|
790
806
|
const page = found ? found.page : null;
|
|
791
|
-
if (await shouldServeStatic(rs.path, page))
|
|
807
|
+
if ((await shouldServeStatic(rs.path, page)) || ssgShadows(rs.path, page))
|
|
792
808
|
return staticHandler(rs);
|
|
793
809
|
if (!found || !page)
|
|
794
810
|
return staticHandler(rs);
|
|
@@ -878,6 +894,7 @@ export function createKrateHandler(options) {
|
|
|
878
894
|
let notFound = false;
|
|
879
895
|
let denied = 0;
|
|
880
896
|
let redirect = "";
|
|
897
|
+
let redirectCode = 307;
|
|
881
898
|
let renderErr = "";
|
|
882
899
|
let fatalErr = "";
|
|
883
900
|
let errStack = "";
|
|
@@ -891,8 +908,10 @@ export function createKrateHandler(options) {
|
|
|
891
908
|
if (id !== "page" && (frame.notFound || frame.denied || frame.redirect)) {
|
|
892
909
|
notFound = notFound || !!frame.notFound;
|
|
893
910
|
denied = denied || frame.denied || 0;
|
|
894
|
-
if (!redirect)
|
|
895
|
-
redirect = frame.redirect
|
|
911
|
+
if (!redirect && frame.redirect) {
|
|
912
|
+
redirect = frame.redirect;
|
|
913
|
+
redirectCode = frame.status === 308 ? 308 : 307;
|
|
914
|
+
}
|
|
896
915
|
continue;
|
|
897
916
|
}
|
|
898
917
|
if (frame.noStore)
|
|
@@ -905,6 +924,8 @@ export function createKrateHandler(options) {
|
|
|
905
924
|
notFound = !!frame.notFound;
|
|
906
925
|
denied = denied || frame.denied || 0;
|
|
907
926
|
redirect = frame.redirect || "";
|
|
927
|
+
if (redirect)
|
|
928
|
+
redirectCode = frame.status === 308 ? 308 : 307;
|
|
908
929
|
if ((frame.status || 0) >= 500 || frame.error) {
|
|
909
930
|
renderErr = frame.error || `page-region render failed with status ${frame.status}`;
|
|
910
931
|
errStack = frame.stack || "";
|
|
@@ -962,7 +983,7 @@ export function createKrateHandler(options) {
|
|
|
962
983
|
}
|
|
963
984
|
if (notFound || denied || redirect) {
|
|
964
985
|
if (redirect)
|
|
965
|
-
return goRedirect(redirect, rs.path, rs.method,
|
|
986
|
+
return goRedirect(redirect, rs.path, rs.method, redirectCode, rs.res);
|
|
966
987
|
if (denied)
|
|
967
988
|
return accessDenied(rs, denied, routeRef);
|
|
968
989
|
const page404 = errorPage(rs.path, 404, routeRef);
|
|
@@ -1667,7 +1688,7 @@ export function createKrateHandler(options) {
|
|
|
1667
1688
|
}
|
|
1668
1689
|
// Runs an API route inside the action store so headers(), cookies() and
|
|
1669
1690
|
// redirect() work in it like in a server action: cookies it sets are added to
|
|
1670
|
-
// the response and a redirect() signal becomes a 307.
|
|
1691
|
+
// the response and a redirect() signal becomes a 307 (308 for permanentRedirect()).
|
|
1671
1692
|
async function runRoute(request, run) {
|
|
1672
1693
|
const ctx = makeActionContext(request.headers, "", new URL(request.url).pathname);
|
|
1673
1694
|
ctx.method = request.method;
|
|
@@ -1678,7 +1699,7 @@ export function createKrateHandler(options) {
|
|
|
1678
1699
|
catch (e) {
|
|
1679
1700
|
if (!e || typeof e.__krateRedirect !== "string")
|
|
1680
1701
|
throw e;
|
|
1681
|
-
out = new Response(null, { status: 307, headers: { location: e.__krateRedirect, "cache-control": "no-store" } });
|
|
1702
|
+
out = new Response(null, { status: e.__krateRedirectStatus === 308 ? 308 : 307, headers: { location: e.__krateRedirect, "cache-control": "no-store" } });
|
|
1682
1703
|
}
|
|
1683
1704
|
if (ctx.setCookies.length > 0) {
|
|
1684
1705
|
const h = new Headers(out.headers);
|
|
@@ -1900,6 +1921,20 @@ export function createKrateHandler(options) {
|
|
|
1900
1921
|
return withHeaders(rs, actionFail(400, "Invalid server action request"));
|
|
1901
1922
|
}
|
|
1902
1923
|
}
|
|
1924
|
+
// Arguments a module action was bound to before it crossed into a client
|
|
1925
|
+
// component: sealed in the URL, so the client cannot choose them.
|
|
1926
|
+
const boundToken = query.get("__krate_bound");
|
|
1927
|
+
if (boundToken !== null) {
|
|
1928
|
+
try {
|
|
1929
|
+
if (entry.inline)
|
|
1930
|
+
throw new Error("an inline action has no bound arguments");
|
|
1931
|
+
args.unshift(...(await openSealedToken(boundToken, entry, actionSecret)));
|
|
1932
|
+
}
|
|
1933
|
+
catch (e) {
|
|
1934
|
+
console.error(`[krate] rejected bound arguments for server action ${entry.source || id}: ${e.message}`);
|
|
1935
|
+
return withHeaders(rs, actionFail(400, "Invalid server action request"));
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1903
1938
|
const ctx = makeActionContext(reqHeaders, id, rs.path);
|
|
1904
1939
|
const scope = { kind: "action", paths: [], tags: [] };
|
|
1905
1940
|
let result;
|