@k8ordo/framework 1.0.0 → 1.2.0
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/README.md +13 -9
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +33 -0
- package/dist/generated.mjs +1 -2
- package/dist/index.mjs +1 -2
- package/dist/runtime/app-router.d.mts +7 -2
- package/dist/runtime/app-router.mjs +32 -6
- package/dist/runtime/browser-payloads.mjs +3 -2
- package/dist/runtime/client-ready.d.mts +27 -0
- package/dist/runtime/client-ready.mjs +89 -0
- package/dist/runtime/entry.browser.mjs +17 -12
- package/dist/runtime/entry.rsc.mjs +102 -43
- package/dist/runtime/fallback-boundary.d.mts +2 -1
- package/dist/runtime/guard.d.mts +2 -1
- package/dist/runtime/page-boundary.d.mts +2 -1
- package/dist/runtime/params.d.mts +2 -1
- package/dist/runtime/redirect-file.d.mts +2 -1
- package/dist/runtime/redirect.d.mts +2 -1
- package/dist/runtime/route.d.mts +2 -1
- package/dist/static-BaGdAVF1.d.mts +66 -0
- package/dist/vercel.d.mts +49 -3
- package/dist/vercel.mjs +34 -15
- package/dist/vite.d.mts +2 -59
- package/dist/vite.mjs +251 -176
- package/docs/GUIDE.md +26 -7
- package/docs/llms.txt +31 -7
- package/docs/references/csp.md +12 -3
- package/docs/references/deploy.md +157 -0
- package/docs/references/routing.md +79 -30
- package/package.json +19 -9
package/dist/vite.mjs
CHANGED
|
@@ -514,7 +514,6 @@ const beliefs = (tree, withParams) => {
|
|
|
514
514
|
return found;
|
|
515
515
|
};
|
|
516
516
|
const schemaName = (componentName) => `${componentName}_params`;
|
|
517
|
-
const searchName = (componentName) => `${componentName}_search`;
|
|
518
517
|
/**
|
|
519
518
|
* The guards along each pattern's directories. A redirect is left out: it
|
|
520
519
|
* answers before any guard runs, since the URL it answers has no page to
|
|
@@ -543,93 +542,122 @@ const guardsOf = (tree) => {
|
|
|
543
542
|
own
|
|
544
543
|
};
|
|
545
544
|
};
|
|
545
|
+
/**
|
|
546
|
+
* The slots a request reaches one file at a time: the page or the not-found
|
|
547
|
+
* that answers it, a route.ts, a page's shell. The table reads each of them
|
|
548
|
+
* when a request reaches it — imported with the table, it would be in the
|
|
549
|
+
* handler's own chunk, and what it renders in the browser and the CSS it
|
|
550
|
+
* imports would be in what every page loads. A layout, an error and a
|
|
551
|
+
* loading are the frame of every page below them, and a guard and a redirect
|
|
552
|
+
* answer before anything renders, so those are imported with the table.
|
|
553
|
+
*/
|
|
554
|
+
const LATE = /* @__PURE__ */ new Set([
|
|
555
|
+
"page",
|
|
556
|
+
"notFound",
|
|
557
|
+
"route",
|
|
558
|
+
"fallback"
|
|
559
|
+
]);
|
|
560
|
+
const isLate = (file) => {
|
|
561
|
+
const slot = slotOf(file);
|
|
562
|
+
return slot !== null && LATE.has(slot);
|
|
563
|
+
};
|
|
546
564
|
const emitRoutesModule = (tree, options) => {
|
|
547
565
|
const namer = createNamer();
|
|
548
|
-
const
|
|
566
|
+
const valueOf = (file) => isLate(file) ? `lazy(${namer.take(file)})` : namer.take(file);
|
|
567
|
+
const table = buildTable(tree, (file) => slotOf(file) === "route" || slotOf(file) === "redirect" ? ANSWERED : valueOf(file));
|
|
549
568
|
const routeFiles = declaredRouteFiles(tree).map((route) => ({
|
|
550
569
|
pattern: route.pattern,
|
|
551
|
-
file: route.file,
|
|
552
570
|
name: namer.take(route.file)
|
|
553
571
|
}));
|
|
572
|
+
const redirects = declaredRedirects(tree).map((redirect) => ({
|
|
573
|
+
pattern: redirect.pattern,
|
|
574
|
+
name: namer.take(redirect.file)
|
|
575
|
+
}));
|
|
554
576
|
const shells = options.mode === "static" ? fallbackShapes(tree) : [];
|
|
555
577
|
for (const shape of shells) namer.take(shape.file);
|
|
578
|
+
const guarded = guardsOf(tree);
|
|
579
|
+
const guardStacks = new Map([...guarded.stacks].map(([pattern, files]) => [pattern, files.map((file) => namer.take(file))]));
|
|
580
|
+
const guardChecks = [...guarded.own].map(([file, pattern]) => `${pad(1)}${namer.take(file)} satisfies Guard<'${pattern}'>,`);
|
|
581
|
+
const hasGuards = guardChecks.length > 0;
|
|
556
582
|
const withParams = options.withParams ?? /* @__PURE__ */ new Set();
|
|
557
583
|
const withSearch = options.withSearch ?? /* @__PURE__ */ new Set();
|
|
558
584
|
const byFile = beliefs(tree, withParams);
|
|
559
585
|
const asserted = /* @__PURE__ */ new Map();
|
|
560
586
|
const stacks = /* @__PURE__ */ new Map();
|
|
561
587
|
const catchAllStacks = /* @__PURE__ */ new Map();
|
|
588
|
+
const searchReaders = /* @__PURE__ */ new Map();
|
|
562
589
|
for (const [file, name] of namer.names) {
|
|
563
590
|
const belief = byFile.get(file);
|
|
564
591
|
if (belief === void 0) continue;
|
|
565
|
-
const
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
else if (belief.kind === "
|
|
592
|
+
const value = valueOf(file);
|
|
593
|
+
const layouts = belief.schemas.filter((schema) => schema !== file).map((schema) => schemaName(namer.take(schema)));
|
|
594
|
+
if (belief.kind === "layout") asserted.set(value, `Layout<'${belief.pattern}'>`);
|
|
595
|
+
else if (belief.kind === "error") asserted.set(value, "ErrorComponent");
|
|
596
|
+
else if (belief.kind === "loading") asserted.set(value, "ComponentType");
|
|
569
597
|
else if (belief.kind === "notFound") {
|
|
570
|
-
asserted.set(
|
|
571
|
-
if (
|
|
572
|
-
} else if (belief.kind === "route") {
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
598
|
+
asserted.set(value, `Page<'${belief.pattern}'>`);
|
|
599
|
+
if (layouts.length > 0) catchAllStacks.set(belief.pattern, layouts);
|
|
600
|
+
} else if (belief.kind === "page" || belief.kind === "route") {
|
|
601
|
+
const { pattern } = belief;
|
|
602
|
+
if (withParams.has(file)) {
|
|
603
|
+
const module = belief.kind === "page" ? "page" : "route";
|
|
604
|
+
stacks.set(pattern, `(${module}: Loaded<typeof ${name}>) => [${[...layouts, `${module}.paramsSchema`].join(", ")}] as const`);
|
|
605
|
+
} else if (layouts.length > 0) stacks.set(pattern, `() => [${layouts.join(", ")}] as const`);
|
|
606
|
+
if (belief.kind === "route") continue;
|
|
607
|
+
if (withSearch.has(file)) searchReaders.set(pattern, `(page: Loaded<typeof ${name}>) => urlReader(page.search)`);
|
|
608
|
+
const typedBy = stacks.has(pattern) ? `ParamSchemas['${pattern}']` : "[]";
|
|
609
|
+
asserted.set(value, withSearch.has(file) ? `Page<'${pattern}', ${typedBy}, { search: SearchReads['${pattern}'] }>` : stacks.has(pattern) ? `Page<'${pattern}', ${typedBy}>` : `Page<'${pattern}'>`);
|
|
578
610
|
}
|
|
579
611
|
}
|
|
580
612
|
const body = Object.entries(table).map(([key, node]) => `${pad(1)}'${key}': ${renderNode(node, 1, asserted)},`);
|
|
581
|
-
const guarded = guardsOf(tree);
|
|
582
|
-
const guardStacks = new Map([...guarded.stacks].map(([pattern, files]) => [pattern, files.map((file) => namer.take(file))]));
|
|
583
|
-
const guardChecks = [...guarded.own].map(([file, pattern]) => `${pad(1)}${namer.take(file)} satisfies Guard<'${pattern}'>,`);
|
|
584
|
-
const hasGuards = guardChecks.length > 0;
|
|
585
613
|
const hasLayout = [...asserted.values()].some((type) => type.startsWith("Layout<"));
|
|
586
|
-
const
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
const
|
|
590
|
-
return
|
|
614
|
+
const hasLazy = [...namer.names.keys()].some((file) => slotOf(file) === "page" || slotOf(file) === "notFound");
|
|
615
|
+
const schemaChecks = [...namer.names].filter(([file]) => withParams.has(file)).map(([file, name]) => {
|
|
616
|
+
const belief = byFile.get(file);
|
|
617
|
+
const schema = isLate(file) ? `Loaded<typeof ${name}>['paramsSchema']` : `typeof ${schemaName(name)}`;
|
|
618
|
+
return `${pad(1)}Checked<${schema}, ParamsSchemaFor<'${belief.pattern}'>>,`;
|
|
591
619
|
});
|
|
592
|
-
const
|
|
593
|
-
const
|
|
594
|
-
const
|
|
620
|
+
const routeChecks = routeFiles.map(({ pattern, name }) => stacks.has(pattern) ? `${pad(1)}Checked<Loaded<typeof ${name}>, RouteModule<'${pattern}', ParamSchemas['${pattern}']>>,` : `${pad(1)}Checked<Loaded<typeof ${name}>, RouteModule<'${pattern}'>>,`);
|
|
621
|
+
const fallbackChecks = shells.map(({ file }) => `${pad(1)}Checked<Loaded<typeof ${namer.take(file)}>['default'], ComponentType>,`);
|
|
622
|
+
const hasChecks = schemaChecks.length + routeChecks.length + fallbackChecks.length > 0;
|
|
623
|
+
const readsLate = routeFiles.length > 0 || shells.length > 0 || searchReaders.size > 0 || [...namer.names.keys()].some((file) => withParams.has(file) && isLate(file));
|
|
595
624
|
const hasRoutes = routeFiles.length > 0;
|
|
596
625
|
const hasError = [...asserted.values()].includes("ErrorComponent");
|
|
597
|
-
const hasSchemas = withParams.size > 0;
|
|
598
626
|
const withRequest = options.mode === "server";
|
|
599
627
|
const requestLine = withRequest ? [" request: RouteRequest;"] : [];
|
|
600
|
-
const
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
}));
|
|
604
|
-
const redirectImports = redirects.map(({ name }) => `import ${name} from '${options.importPrefix}/${namerFile(namer, name).replace(/\.[jt]sx?$/u, "")}';`);
|
|
605
|
-
const schemaChecks = [...namer.names].filter(([file]) => withParams.has(file)).map(([file, name]) => {
|
|
606
|
-
const belief = byFile.get(file);
|
|
607
|
-
return `${pad(1)}${schemaName(name)} satisfies ParamsSchemaFor<'${belief.pattern}'>,`;
|
|
608
|
-
});
|
|
628
|
+
const specifier = (file) => `'${options.importPrefix}/${file.replace(/\.[jt]sx?$/u, "")}'`;
|
|
629
|
+
const importLines = [...namer.names].filter(([file]) => !isLate(file)).map(([file, name]) => withParams.has(file) ? `import ${name}, { paramsSchema as ${schemaName(name)} } from ${specifier(file)};` : `import ${name} from ${specifier(file)};`);
|
|
630
|
+
const loaderLines = [...namer.names].filter(([file]) => isLate(file)).map(([file, name]) => `const ${name} = () => import(${specifier(file)});`);
|
|
609
631
|
const toMap = (map) => [...map].map(([pattern, schemas]) => `${pad(1)}'${pattern}': [${schemas.join(", ")}],`);
|
|
632
|
+
const toFunctions = (map) => [...map].map(([pattern, made]) => `${pad(1)}'${pattern}': ${made},`);
|
|
610
633
|
const typeImports = [
|
|
611
634
|
...hasError ? ["ErrorComponent"] : [],
|
|
612
635
|
...hasLayout || hasGuards ? ["ParamsOf"] : [],
|
|
613
|
-
...
|
|
636
|
+
...schemaChecks.length > 0 ? ["ParamsSchemaFor"] : [],
|
|
614
637
|
"ParsedParams"
|
|
615
638
|
];
|
|
616
639
|
return [
|
|
617
640
|
bannerFrom("routes/"),
|
|
618
641
|
"",
|
|
619
642
|
`import { defineRoutes } from '${GENERATED_FROM}';`,
|
|
620
|
-
...searchReaders.
|
|
643
|
+
...searchReaders.size > 0 ? [`import { urlReader } from '@k8ordo/state';`] : [],
|
|
621
644
|
`import type { ${typeImports.join(", ")} } from '${GENERATED_FROM}';`,
|
|
645
|
+
...hasLazy ? [`import { lazy } from 'react';`] : [],
|
|
622
646
|
`import type { ComponentType${hasLayout ? ", ReactNode" : ""} } from 'react';`,
|
|
623
647
|
"",
|
|
624
|
-
...importLines,
|
|
625
|
-
...redirectImports,
|
|
626
|
-
"",
|
|
627
|
-
...routeSchemaLines.length > 0 ? [...routeSchemaLines, ""] : [],
|
|
648
|
+
...importLines.length > 0 ? [...importLines, ""] : [],
|
|
628
649
|
...withRequest ? [
|
|
629
650
|
"// What a page may read of the request, under a running server only.",
|
|
630
651
|
`import type { RouteRequest } from '${ROUTE_REQUEST_FROM}';`,
|
|
631
652
|
""
|
|
632
653
|
] : [],
|
|
654
|
+
...loaderLines.length > 0 ? [
|
|
655
|
+
"// The files a request reaches one at a time, read when it does: what",
|
|
656
|
+
"// each renders in the browser, and the CSS it imports, goes only to the",
|
|
657
|
+
"// pages that render it.",
|
|
658
|
+
...loaderLines,
|
|
659
|
+
""
|
|
660
|
+
] : [],
|
|
633
661
|
"// What the renderer passes. `satisfies` below is where a route file's",
|
|
634
662
|
"// own props are checked against the pattern its directory puts it under,",
|
|
635
663
|
"// and where its params take the types the `paramsSchema` exports along",
|
|
@@ -659,14 +687,24 @@ const emitRoutesModule = (tree, options) => {
|
|
|
659
687
|
"// params fill in, and whether the move is permanent.",
|
|
660
688
|
"type Redirect = string | { readonly to: string; readonly permanent?: boolean };"
|
|
661
689
|
] : [],
|
|
690
|
+
...readsLate ? [
|
|
691
|
+
"",
|
|
692
|
+
"// A file read when a request reaches it, as the module it is read as.",
|
|
693
|
+
"type Loaded<L extends () => Promise<unknown>> = Awaited<ReturnType<L>>;"
|
|
694
|
+
] : [],
|
|
695
|
+
...hasChecks ? [
|
|
696
|
+
"",
|
|
697
|
+
"// `satisfies`, for an export the table holds no value of: compiles only",
|
|
698
|
+
"// when T is assignable to U.",
|
|
699
|
+
"type Checked<T extends U, U> = T;"
|
|
700
|
+
] : [],
|
|
662
701
|
"",
|
|
663
|
-
...
|
|
702
|
+
...schemaChecks.length > 0 ? [
|
|
664
703
|
"// The `paramsSchema` exports the route files declared, each checked against",
|
|
665
704
|
"// the pattern its file sits under.",
|
|
666
|
-
"
|
|
705
|
+
"export type SchemaChecks = [",
|
|
667
706
|
...schemaChecks,
|
|
668
|
-
"]
|
|
669
|
-
"void schemas;",
|
|
707
|
+
"];",
|
|
670
708
|
""
|
|
671
709
|
] : [],
|
|
672
710
|
...hasGuards ? [
|
|
@@ -686,12 +724,18 @@ const emitRoutesModule = (tree, options) => {
|
|
|
686
724
|
""
|
|
687
725
|
] : [],
|
|
688
726
|
"// Per page pattern, the schemas that run before it renders — every",
|
|
689
|
-
"// layout above it that declared one, then its own
|
|
690
|
-
"//
|
|
727
|
+
"// layout above it that declared one, then its own, read off the file the",
|
|
728
|
+
"// handler read for it. The handler runs them; a schema that refuses makes",
|
|
729
|
+
"// the pattern not answer the pathname.",
|
|
691
730
|
"export const paramSchemas = {",
|
|
692
|
-
...
|
|
731
|
+
...toFunctions(stacks),
|
|
693
732
|
"} as const;",
|
|
694
733
|
"",
|
|
734
|
+
"// The same stacks, as the router types a page's params and links to it.",
|
|
735
|
+
"export type ParamSchemas = {",
|
|
736
|
+
" readonly [P in keyof typeof paramSchemas]: (typeof paramSchemas)[P] extends (...args: never) => infer S ? S : never;",
|
|
737
|
+
"};",
|
|
738
|
+
"",
|
|
695
739
|
"// Per catch-all pattern, the schemas of the layouts above its not-found.",
|
|
696
740
|
"// The handler runs them for what they write to the render (the locale a",
|
|
697
741
|
"// 404 is in); a refusal does not stop a catch-all from answering.",
|
|
@@ -715,10 +759,9 @@ const emitRoutesModule = (tree, options) => {
|
|
|
715
759
|
"",
|
|
716
760
|
"// The route.ts modules, each checked against the pattern its directory",
|
|
717
761
|
"// puts it under.",
|
|
718
|
-
"
|
|
762
|
+
"export type RouteChecks = [",
|
|
719
763
|
...routeChecks,
|
|
720
|
-
"]
|
|
721
|
-
"void routeChecks;",
|
|
764
|
+
"];",
|
|
722
765
|
""
|
|
723
766
|
] : [],
|
|
724
767
|
...hasRoutes || redirects.length > 0 ? [
|
|
@@ -729,13 +772,26 @@ const emitRoutesModule = (tree, options) => {
|
|
|
729
772
|
""
|
|
730
773
|
] : [],
|
|
731
774
|
"// Per page pattern that exports `search`, what reads it out of the URL —",
|
|
732
|
-
"// @k8ordo/state's reading of a url schema
|
|
733
|
-
"// and a client navigation that changes
|
|
775
|
+
"// @k8ordo/state's reading of a url schema, made from the page's module.",
|
|
776
|
+
"// The page receives what it read, and a client navigation that changes",
|
|
777
|
+
"// the search loads it again.",
|
|
734
778
|
"export const searchReaders = {",
|
|
735
|
-
...searchReaders,
|
|
779
|
+
...toFunctions(searchReaders),
|
|
736
780
|
"} as const;",
|
|
737
781
|
"",
|
|
738
|
-
"//
|
|
782
|
+
"// What each of those pages receives as `search`.",
|
|
783
|
+
"export type SearchReads = {",
|
|
784
|
+
" readonly [P in keyof typeof searchReaders]: (typeof searchReaders)[P] extends (...args: never) => (...args: never) => infer R ? R : never;",
|
|
785
|
+
"};",
|
|
786
|
+
"",
|
|
787
|
+
"// Per pattern, what reads the page or the not-found that answers it. The",
|
|
788
|
+
"// handler renders what it read in the place `lazy()` holds below.",
|
|
789
|
+
"export const pageModules = {",
|
|
790
|
+
...[...namer.names].filter(([file]) => slotOf(file) === "page" || slotOf(file) === "notFound").map(([file, name]) => `${pad(1)}'${byFile.get(file).pattern}': ${name},`),
|
|
791
|
+
"} as const;",
|
|
792
|
+
"",
|
|
793
|
+
"// Per pattern, what reads the route.ts that answers it, by the methods it",
|
|
794
|
+
"// exports.",
|
|
739
795
|
"export const routeModules = {",
|
|
740
796
|
...routeFiles.map(({ pattern, name }) => `${pad(1)}'${pattern}': ${name},`),
|
|
741
797
|
"} as const;",
|
|
@@ -753,18 +809,25 @@ const emitRoutesModule = (tree, options) => {
|
|
|
753
809
|
"} as const;",
|
|
754
810
|
"",
|
|
755
811
|
...options.mode === "static" ? [
|
|
756
|
-
"// Per page pattern with a fallback.tsx: what
|
|
812
|
+
"// Per page pattern with a fallback.tsx: what reads its shell for a value",
|
|
757
813
|
"// the build did not write, the params a shell may leave to the browser, and",
|
|
758
814
|
"// the schemas of the layouts above it, which run over the params it fills.",
|
|
759
815
|
"export const fallbacks = {",
|
|
760
816
|
...shells.flatMap(({ pattern, file, open }) => [
|
|
761
817
|
`${pad(1)}'${pattern}': {`,
|
|
762
|
-
`${pad(2)}
|
|
818
|
+
`${pad(2)}load: ${namer.take(file)},`,
|
|
763
819
|
`${pad(2)}open: [${open.map((param) => `'${param}'`).join(", ")}],`,
|
|
764
820
|
`${pad(2)}schemas: [${byFile.get(file).schemas.map((layout) => schemaName(namer.take(layout))).join(", ")}],`,
|
|
765
821
|
`${pad(1)}},`
|
|
766
822
|
]),
|
|
767
|
-
"} as const;"
|
|
823
|
+
"} as const;",
|
|
824
|
+
...fallbackChecks.length > 0 ? [
|
|
825
|
+
"",
|
|
826
|
+
"// The fallback.tsx files, each checked as a component handed nothing.",
|
|
827
|
+
"export type FallbackChecks = [",
|
|
828
|
+
...fallbackChecks,
|
|
829
|
+
"];"
|
|
830
|
+
] : []
|
|
768
831
|
] : ["// A running server renders every value with its page: no shells.", "export const fallbacks = {} as const;"],
|
|
769
832
|
"",
|
|
770
833
|
"export const routes = defineRoutes({",
|
|
@@ -773,10 +836,6 @@ const emitRoutesModule = (tree, options) => {
|
|
|
773
836
|
""
|
|
774
837
|
].join("\n");
|
|
775
838
|
};
|
|
776
|
-
const namerFile = (namer, name) => {
|
|
777
|
-
for (const [file, taken] of namer.names) if (taken === name) return file;
|
|
778
|
-
throw new Error(`no file was named ${name}`);
|
|
779
|
-
};
|
|
780
839
|
/**
|
|
781
840
|
* Both packages read the app's route table through declaration merging, so
|
|
782
841
|
* the app gets typed paths everywhere without writing the ceremony itself.
|
|
@@ -797,19 +856,15 @@ const emitRegisterModule = (options) => {
|
|
|
797
856
|
...localesModule === null ? [] : [`import type { LocaleOf } from '${I18N}';`],
|
|
798
857
|
...wantsState ? [`import type {} from '${options.stateModule}';`] : [],
|
|
799
858
|
...localesModule === null ? [] : [`import type { locales } from '${localesModule}';`],
|
|
800
|
-
`import type {
|
|
859
|
+
`import type { ParamSchemas, routes, SearchReads } from '${options.routesModule}';`,
|
|
801
860
|
"",
|
|
802
861
|
`declare module '${GENERATED_FROM}' {`,
|
|
803
862
|
" interface Register {",
|
|
804
863
|
" routes: typeof routes;",
|
|
805
864
|
" // A link takes a param as the page receives it — typed by its schema.",
|
|
806
|
-
" params: ParsedParamsMap<
|
|
865
|
+
" params: ParsedParamsMap<ParamSchemas>;",
|
|
807
866
|
" // A page that exports `search` receives what it reads.",
|
|
808
|
-
" search:
|
|
809
|
-
" readonly [P in keyof typeof searchReaders]: ReturnType<",
|
|
810
|
-
" (typeof searchReaders)[P]",
|
|
811
|
-
" >;",
|
|
812
|
-
" };",
|
|
867
|
+
" search: SearchReads;",
|
|
813
868
|
...withRequest ? [" // A route file receives the request: this is a running server.", " request: RouteRequest;"] : [],
|
|
814
869
|
" }",
|
|
815
870
|
"}"
|
|
@@ -1078,104 +1133,109 @@ const engine = (options, host) => {
|
|
|
1078
1133
|
outDir,
|
|
1079
1134
|
mode: host.mode
|
|
1080
1135
|
});
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
{
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1136
|
+
const api = { async generate() {
|
|
1137
|
+
const { problems, warnings } = await generate(generateOptions());
|
|
1138
|
+
for (const warning of warnings) logger.warnOnce(`k8ordo: ${warning}`);
|
|
1139
|
+
if (problems.length > 0) throw new Error(`routes/ is not a valid pathname space:\n${problems.map((problem) => ` routes/${problem.path}: ${problem.message}`).join("\n")}`);
|
|
1140
|
+
} };
|
|
1141
|
+
const plugin = {
|
|
1142
|
+
name: "k8ordo:engine",
|
|
1143
|
+
enforce: "pre",
|
|
1144
|
+
config(_config, env) {
|
|
1145
|
+
return {
|
|
1146
|
+
define: {
|
|
1147
|
+
"process.env.NODE_ENV": JSON.stringify(isProduction(env.mode) ? "production" : "development"),
|
|
1148
|
+
"import.meta.env.K8ORDO_MODE": JSON.stringify(host.mode)
|
|
1149
|
+
},
|
|
1150
|
+
resolve: { dedupe: ["react", "react-dom"] },
|
|
1151
|
+
environments: {
|
|
1152
|
+
rsc: {
|
|
1153
|
+
resolve: { noExternal: [FAMILY] },
|
|
1154
|
+
build: { rolldownOptions: {
|
|
1155
|
+
input: { index: runtime("entry.rsc") },
|
|
1156
|
+
output: { entryFileNames: ESM_ENTRY },
|
|
1157
|
+
onLog(level, log, handle) {
|
|
1158
|
+
if (log.code === "INEFFECTIVE_DYNAMIC_IMPORT" && SERVER_REFERENCES_ONLY.test(log.message)) return;
|
|
1159
|
+
handle(level, log);
|
|
1160
|
+
}
|
|
1161
|
+
} }
|
|
1092
1162
|
},
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
} }
|
|
1105
|
-
},
|
|
1106
|
-
ssr: {
|
|
1107
|
-
resolve: { noExternal: [FAMILY] },
|
|
1108
|
-
build: { rolldownOptions: {
|
|
1109
|
-
input: { index: runtime("entry.ssr") },
|
|
1110
|
-
output: { entryFileNames: ESM_ENTRY }
|
|
1111
|
-
} }
|
|
1163
|
+
ssr: {
|
|
1164
|
+
resolve: { noExternal: [FAMILY] },
|
|
1165
|
+
build: { rolldownOptions: {
|
|
1166
|
+
input: { index: runtime("entry.ssr") },
|
|
1167
|
+
output: { entryFileNames: ESM_ENTRY }
|
|
1168
|
+
} }
|
|
1169
|
+
},
|
|
1170
|
+
client: {
|
|
1171
|
+
optimizeDeps: {
|
|
1172
|
+
include: CLIENT_DEPS,
|
|
1173
|
+
exclude: CLIENT_UNBUNDLED
|
|
1112
1174
|
},
|
|
1113
|
-
|
|
1114
|
-
optimizeDeps: {
|
|
1115
|
-
include: CLIENT_DEPS,
|
|
1116
|
-
exclude: CLIENT_UNBUNDLED
|
|
1117
|
-
},
|
|
1118
|
-
build: { rolldownOptions: { input: { index: runtime("entry.browser") } } }
|
|
1119
|
-
}
|
|
1175
|
+
build: { rolldownOptions: { input: { index: runtime("entry.browser") } } }
|
|
1120
1176
|
}
|
|
1121
|
-
};
|
|
1122
|
-
},
|
|
1123
|
-
configEnvironment(_name, config) {
|
|
1124
|
-
const include = config.optimizeDeps?.include;
|
|
1125
|
-
if (include !== void 0) config.optimizeDeps = {
|
|
1126
|
-
...config.optimizeDeps,
|
|
1127
|
-
include: include.map((entry) => entry.startsWith("@vitejs/plugin-rsc") ? `${FRAMEWORK} > ${entry}` : entry)
|
|
1128
|
-
};
|
|
1129
|
-
},
|
|
1130
|
-
configResolved(config) {
|
|
1131
|
-
if (!config.base.startsWith("/") || config.base.startsWith("//")) throw new Error(`k8ordo serves its pages under Vite's base, so base has to be a path from the root, like '/docs/' — got '${config.base}'`);
|
|
1132
|
-
({root, logger} = config);
|
|
1133
|
-
routesDir = path.resolve(root, options.routesDir ?? "src/routes");
|
|
1134
|
-
localesModule = path.resolve(root, LOCALES_MODULE);
|
|
1135
|
-
outDir = path.resolve(root, OUT_DIR);
|
|
1136
|
-
},
|
|
1137
|
-
buildApp: {
|
|
1138
|
-
order: "post",
|
|
1139
|
-
async handler(builder) {
|
|
1140
|
-
const dirOf = (name) => {
|
|
1141
|
-
const out = builder.environments[name]?.config.build.outDir;
|
|
1142
|
-
if (out === void 0) throw new Error(`the build ran without the ${name} environment`);
|
|
1143
|
-
return path.resolve(root, out);
|
|
1144
|
-
};
|
|
1145
|
-
const shared = sharedDir(dirOf("rsc"), dirOf("ssr"));
|
|
1146
|
-
const toRoot = path.relative(shared, root);
|
|
1147
|
-
if (!toRoot.startsWith("..") && !path.isAbsolute(toRoot)) throw new Error(`the rsc and ssr builds share ${path.relative(root, shared) || "."}, which holds the application, and the build writes a package.json saying type: module where they meet — put both in a directory of their own, as dist/rsc and dist/ssr`);
|
|
1148
|
-
await writeFile(path.join(shared, "package.json"), `${JSON.stringify({ type: "module" }, null, 2)}\n`);
|
|
1149
|
-
}
|
|
1150
|
-
},
|
|
1151
|
-
async buildStart() {
|
|
1152
|
-
const { problems, warnings } = await generate(generateOptions());
|
|
1153
|
-
for (const warning of warnings) logger.warnOnce(`k8ordo: ${warning}`);
|
|
1154
|
-
if (problems.length > 0) this.error(`routes/ is not a valid pathname space:\n${problems.map((problem) => ` routes/${problem.path}: ${problem.message}`).join("\n")}`);
|
|
1155
|
-
},
|
|
1156
|
-
configureServer(server) {
|
|
1157
|
-
server.watcher.add(routesDir);
|
|
1158
|
-
devServer = server;
|
|
1159
|
-
},
|
|
1160
|
-
async watchChange(file) {
|
|
1161
|
-
const changed = path.resolve(file);
|
|
1162
|
-
if (!changed.startsWith(`${routesDir}${path.sep}`) && changed !== localesModule) return;
|
|
1163
|
-
const run = generating.then(() => generate(generateOptions()));
|
|
1164
|
-
generating = run.then(() => void 0, () => void 0);
|
|
1165
|
-
const { problems, warnings } = await run;
|
|
1166
|
-
for (const problem of problems) logger.error(`routes/${problem.path}: ${problem.message}`);
|
|
1167
|
-
for (const warning of warnings) logger.warnOnce(`k8ordo: ${warning}`);
|
|
1168
|
-
if (changed === localesModule) return;
|
|
1169
|
-
for (const environment of Object.values(devServer?.environments ?? {})) {
|
|
1170
|
-
const { moduleGraph } = environment;
|
|
1171
|
-
for (const module of moduleGraph.getModulesByFile(routesModule()) ?? []) moduleGraph.invalidateModule(module);
|
|
1172
1177
|
}
|
|
1173
|
-
}
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1178
|
+
};
|
|
1179
|
+
},
|
|
1180
|
+
configEnvironment(_name, config) {
|
|
1181
|
+
const include = config.optimizeDeps?.include;
|
|
1182
|
+
if (include !== void 0) config.optimizeDeps = {
|
|
1183
|
+
...config.optimizeDeps,
|
|
1184
|
+
include: include.map((entry) => entry.startsWith("@vitejs/plugin-rsc") ? `${FRAMEWORK} > ${entry}` : entry)
|
|
1185
|
+
};
|
|
1186
|
+
},
|
|
1187
|
+
configResolved(config) {
|
|
1188
|
+
if (!config.base.startsWith("/") || config.base.startsWith("//")) throw new Error(`k8ordo serves its pages under Vite's base, so base has to be a path from the root, like '/docs/' — got '${config.base}'`);
|
|
1189
|
+
({root, logger} = config);
|
|
1190
|
+
routesDir = path.resolve(root, options.routesDir ?? "src/routes");
|
|
1191
|
+
localesModule = path.resolve(root, LOCALES_MODULE);
|
|
1192
|
+
outDir = path.resolve(root, OUT_DIR);
|
|
1193
|
+
},
|
|
1194
|
+
buildApp: {
|
|
1195
|
+
order: "post",
|
|
1196
|
+
async handler(builder) {
|
|
1197
|
+
const dirOf = (name) => {
|
|
1198
|
+
const out = builder.environments[name]?.config.build.outDir;
|
|
1199
|
+
if (out === void 0) throw new Error(`the build ran without the ${name} environment`);
|
|
1200
|
+
return path.resolve(root, out);
|
|
1201
|
+
};
|
|
1202
|
+
const shared = sharedDir(dirOf("rsc"), dirOf("ssr"));
|
|
1203
|
+
const toRoot = path.relative(shared, root);
|
|
1204
|
+
if (!toRoot.startsWith("..") && !path.isAbsolute(toRoot)) throw new Error(`the rsc and ssr builds share ${path.relative(root, shared) || "."}, which holds the application, and the build writes a package.json saying type: module where they meet — put both in a directory of their own, as dist/rsc and dist/ssr`);
|
|
1205
|
+
await writeFile(path.join(shared, "package.json"), `${JSON.stringify({ type: "module" }, null, 2)}\n`);
|
|
1206
|
+
}
|
|
1207
|
+
},
|
|
1208
|
+
api,
|
|
1209
|
+
async buildStart() {
|
|
1210
|
+
await api.generate();
|
|
1211
|
+
},
|
|
1212
|
+
configureServer(server) {
|
|
1213
|
+
server.watcher.add(routesDir);
|
|
1214
|
+
devServer = server;
|
|
1215
|
+
},
|
|
1216
|
+
async watchChange(file) {
|
|
1217
|
+
const changed = path.resolve(file);
|
|
1218
|
+
if (!changed.startsWith(`${routesDir}${path.sep}`) && changed !== localesModule) return;
|
|
1219
|
+
const run = generating.then(() => generate(generateOptions()));
|
|
1220
|
+
generating = run.then(() => void 0, () => void 0);
|
|
1221
|
+
const { problems, warnings } = await run;
|
|
1222
|
+
for (const problem of problems) logger.error(`routes/${problem.path}: ${problem.message}`);
|
|
1223
|
+
for (const warning of warnings) logger.warnOnce(`k8ordo: ${warning}`);
|
|
1224
|
+
if (changed === localesModule) return;
|
|
1225
|
+
for (const environment of Object.values(devServer?.environments ?? {})) {
|
|
1226
|
+
const { moduleGraph } = environment;
|
|
1227
|
+
for (const module of moduleGraph.getModulesByFile(routesModule()) ?? []) moduleGraph.invalidateModule(module);
|
|
1177
1228
|
}
|
|
1229
|
+
},
|
|
1230
|
+
resolveId(source) {
|
|
1231
|
+
if (source === VIRTUAL_ROUTES) return routesModule();
|
|
1232
|
+
return null;
|
|
1178
1233
|
}
|
|
1234
|
+
};
|
|
1235
|
+
return [
|
|
1236
|
+
react({ compiler: options.reactCompiler === true }),
|
|
1237
|
+
rsc(),
|
|
1238
|
+
plugin
|
|
1179
1239
|
];
|
|
1180
1240
|
};
|
|
1181
1241
|
//#endregion
|
|
@@ -1351,10 +1411,12 @@ const redirectPage = (to) => {
|
|
|
1351
1411
|
const escaped = escapeMarkup(to);
|
|
1352
1412
|
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=${escaped}"><link rel="canonical" href="${escaped}"><title>Redirecting</title></head><body><a href="${escaped}">${escaped}</a></body></html>\n`;
|
|
1353
1413
|
};
|
|
1354
|
-
const
|
|
1355
|
-
|
|
1356
|
-
"
|
|
1357
|
-
"
|
|
1414
|
+
const IGNORED = "is ignored in a <meta> — set it as a header at the host";
|
|
1415
|
+
const HEADER_ONLY = /* @__PURE__ */ new Map([
|
|
1416
|
+
["frame-ancestors", IGNORED],
|
|
1417
|
+
["report-uri", IGNORED],
|
|
1418
|
+
["sandbox", IGNORED],
|
|
1419
|
+
["report-to", "names an endpoint only a Reporting-Endpoints response header defines — set the policy as a header at the host"]
|
|
1358
1420
|
]);
|
|
1359
1421
|
/** What decides scripts: `script-src`, or `default-src` without it. */
|
|
1360
1422
|
const scriptDirectiveOf = (policy) => {
|
|
@@ -1374,15 +1436,16 @@ const elementDirectivesOf = (policy) => {
|
|
|
1374
1436
|
};
|
|
1375
1437
|
/**
|
|
1376
1438
|
* What would make a policy wrong to write into every page, named at once:
|
|
1377
|
-
* a directive a
|
|
1439
|
+
* a directive that works only from a header, a source that is not one, and
|
|
1378
1440
|
* `'strict-dynamic'`, under which the framework's module script — allowed by
|
|
1379
1441
|
* where it comes from, since a file cannot sign it — would never load.
|
|
1380
1442
|
*/
|
|
1381
1443
|
const policyProblems = (policy) => {
|
|
1382
1444
|
const problems = [];
|
|
1383
1445
|
for (const [name, sources] of Object.entries(policy)) {
|
|
1446
|
+
const headerOnly = HEADER_ONLY.get(name);
|
|
1384
1447
|
if (!/^[a-z][a-z-]*$/u.test(name)) problems.push(`"${name}" is not a directive name`);
|
|
1385
|
-
else if (
|
|
1448
|
+
else if (headerOnly !== void 0) problems.push(`${name} ${headerOnly}`);
|
|
1386
1449
|
for (const source of sources) if (source === "" || /[\s;,]/u.test(source)) problems.push(`"${source}" in ${name} is not one source — give each its own entry`);
|
|
1387
1450
|
}
|
|
1388
1451
|
for (const [name, sources] of elementDirectivesOf(policy)) if (sources.includes("'strict-dynamic'")) problems.push(`'strict-dynamic' in ${name} would block the framework's module script, which a file allows by where it comes from ('self'), not by a hash`);
|
|
@@ -2085,10 +2148,13 @@ const staticMode = (options) => {
|
|
|
2085
2148
|
const failed = [];
|
|
2086
2149
|
const redirected = /* @__PURE__ */ new Set();
|
|
2087
2150
|
const unanswered = [];
|
|
2151
|
+
const types = /* @__PURE__ */ new Map();
|
|
2088
2152
|
await inParallel(plan.paths.flatMap((pathname) => {
|
|
2089
2153
|
if (byRoute.has(pathname)) return [async () => {
|
|
2090
|
-
const
|
|
2154
|
+
const file = path.join(clientDir, dirFor(pathname));
|
|
2155
|
+
const { status, type } = await writeRoute(file, handler, urlFor(pathname));
|
|
2091
2156
|
if (status !== 200) unanswered.push(`${pathname} (${String(status)})`);
|
|
2157
|
+
else if (type !== null) types.set(path.relative(clientDir, file).split(path.sep).join("/"), type);
|
|
2092
2158
|
}];
|
|
2093
2159
|
const dir = path.join(clientDir, dirFor(pathname));
|
|
2094
2160
|
return [async () => {
|
|
@@ -2153,7 +2219,8 @@ const staticMode = (options) => {
|
|
|
2153
2219
|
client: clientDir,
|
|
2154
2220
|
base,
|
|
2155
2221
|
rewrites,
|
|
2156
|
-
notFound: unmatched !== null
|
|
2222
|
+
notFound: unmatched !== null,
|
|
2223
|
+
types
|
|
2157
2224
|
});
|
|
2158
2225
|
else if (vercel === void 0 && process.env.VERCEL !== void 0 && plan.shells.length > 0) builder.config.logger.warn("k8ordo: this build runs on Vercel, which does not read _redirects — add vercel() from @k8ordo/framework/vercel, or the shells are never served");
|
|
2159
2226
|
const shells = plan.shells.length === 0 ? "" : `, ${String(plan.shells.length)} ${plan.shells.length === 1 ? "shell" : "shells"} (${plan.shells.map((shell) => shell.location).join(", ")})`;
|
|
@@ -2209,19 +2276,27 @@ const write = async (file, handler, url, csp, { notFoundIsPage, shell }) => {
|
|
|
2209
2276
|
return written;
|
|
2210
2277
|
};
|
|
2211
2278
|
/**
|
|
2212
|
-
* Writes what a route.ts's GET answered, as the file at its pathname
|
|
2213
|
-
*
|
|
2214
|
-
*
|
|
2279
|
+
* Writes what a route.ts's GET answered, as the file at its pathname, and
|
|
2280
|
+
* says the type it answered with — a file keeps none, so a static host serves
|
|
2281
|
+
* it with the type its extension says, and only an adapter that can name a
|
|
2282
|
+
* file's type (`vercel()`) serves the GET's. Anything but a 200 is not a file
|
|
2283
|
+
* the site has, and nothing is written.
|
|
2215
2284
|
*/
|
|
2216
2285
|
const writeRoute = async (file, handler, url) => {
|
|
2217
2286
|
const response = await handler(new Request(url));
|
|
2218
2287
|
if (response.status !== 200) {
|
|
2219
2288
|
if (response.status === 500) console.error(`k8ordo: ${url} — ${await response.text()}`);
|
|
2220
|
-
return
|
|
2289
|
+
return {
|
|
2290
|
+
status: response.status,
|
|
2291
|
+
type: null
|
|
2292
|
+
};
|
|
2221
2293
|
}
|
|
2222
2294
|
await mkdir(path.dirname(file), { recursive: true });
|
|
2223
2295
|
await writeFile(file, Buffer.from(await response.arrayBuffer()));
|
|
2224
|
-
return
|
|
2296
|
+
return {
|
|
2297
|
+
status: response.status,
|
|
2298
|
+
type: response.headers.get("content-type")
|
|
2299
|
+
};
|
|
2225
2300
|
};
|
|
2226
2301
|
//#endregion
|
|
2227
2302
|
//#region src/vite.ts
|