@decocms/blocks 8.1.0-next.7 → 8.1.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/dist/v8/cli/check/index.d.ts +6 -2
- package/dist/v8/cli/check/index.d.ts.map +1 -1
- package/dist/v8/cli/check/index.js +34 -7
- package/dist/v8/cli/check/index.js.map +1 -1
- package/dist/v8/cli/color.d.ts +14 -0
- package/dist/v8/cli/color.d.ts.map +1 -0
- package/dist/v8/cli/color.js +14 -0
- package/dist/v8/cli/color.js.map +1 -0
- package/dist/v8/cli/log.d.ts +4 -0
- package/dist/v8/cli/log.d.ts.map +1 -1
- package/dist/v8/cli/log.js +9 -0
- package/dist/v8/cli/log.js.map +1 -1
- package/dist/v8/cli/run.d.ts +1 -0
- package/dist/v8/cli/run.d.ts.map +1 -1
- package/dist/v8/cli/run.js +17 -3
- package/dist/v8/cli/run.js.map +1 -1
- package/dist/v8/cli/schema/index.d.ts.map +1 -1
- package/dist/v8/cli/schema/index.js +5 -3
- package/dist/v8/cli/schema/index.js.map +1 -1
- package/dist/v8/cli/schema/tsProgram.d.ts +1 -0
- package/dist/v8/cli/schema/tsProgram.d.ts.map +1 -1
- package/dist/v8/cli/schema/tsProgram.js +1 -0
- package/dist/v8/cli/schema/tsProgram.js.map +1 -1
- package/dist/v8/cli/schema/typeToSchema.d.ts.map +1 -1
- package/dist/v8/cli/schema/typeToSchema.js +50 -7
- package/dist/v8/cli/schema/typeToSchema.js.map +1 -1
- package/dist/v8/cms.js +1 -1
- package/dist/v8/cms.js.map +1 -1
- package/dist/v8/matchRoute.d.ts +12 -10
- package/dist/v8/matchRoute.d.ts.map +1 -1
- package/dist/v8/matchRoute.js +60 -86
- package/dist/v8/matchRoute.js.map +1 -1
- package/dist/v8/remoteLoader.d.ts +2 -0
- package/dist/v8/remoteLoader.d.ts.map +1 -1
- package/dist/v8/remoteLoader.js +7 -16
- package/dist/v8/remoteLoader.js.map +1 -1
- package/dist/v8/routeTrie.d.ts +43 -0
- package/dist/v8/routeTrie.d.ts.map +1 -0
- package/dist/v8/routeTrie.js +88 -0
- package/dist/v8/routeTrie.js.map +1 -0
- package/dist/v8/types.d.ts +12 -1
- package/dist/v8/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/v8/cli/check/index.ts +32 -7
- package/src/v8/cli/color.ts +29 -0
- package/src/v8/cli/log.ts +12 -0
- package/src/v8/cli/run.ts +18 -3
- package/src/v8/cli/schema/index.ts +5 -3
- package/src/v8/cli/schema/tsProgram.ts +2 -1
- package/src/v8/cli/schema/typeToSchema.ts +47 -7
- package/src/v8/cms.ts +1 -1
- package/src/v8/matchRoute.ts +70 -106
- package/src/v8/remoteLoader.ts +13 -17
- package/src/v8/routeTrie.ts +103 -0
- package/src/v8/types.ts +12 -1
|
@@ -25,6 +25,7 @@ import { SETTINGS_BLOCK, SETTINGS_TYPE } from "../../builtins/data.ts";
|
|
|
25
25
|
import { isBlock, own } from "../../json.ts";
|
|
26
26
|
import { findRouteConflicts } from "../../matchRoute.ts";
|
|
27
27
|
import { isBuiltIn, storesPlainVariants } from "../builtins.ts";
|
|
28
|
+
import { paint } from "../color.ts";
|
|
28
29
|
import { readSavedBlocks, type SavedBlocks } from "../content.ts";
|
|
29
30
|
import { consoleReporter, type Reporter } from "../log.ts";
|
|
30
31
|
import { CliError, decoPaths, findDecoRoot } from "../root.ts";
|
|
@@ -736,8 +737,13 @@ export function checkContent(meta: DecoMeta, saved: SavedBlocks): Problem[] {
|
|
|
736
737
|
});
|
|
737
738
|
}
|
|
738
739
|
|
|
739
|
-
/**
|
|
740
|
-
|
|
740
|
+
/**
|
|
741
|
+
* Print problems grouped per file, the format the docs show. With colour, the
|
|
742
|
+
* same text plus escapes: file bold, path dim, an error's message red and the
|
|
743
|
+
* word `warning` yellow.
|
|
744
|
+
*/
|
|
745
|
+
export function formatProblems(problems: Problem[], color = false): string {
|
|
746
|
+
const c = paint(color);
|
|
741
747
|
const byFile = new Map<string, Problem[]>();
|
|
742
748
|
for (const p of problems) {
|
|
743
749
|
const list = byFile.get(p.file) ?? [];
|
|
@@ -746,10 +752,12 @@ export function formatProblems(problems: Problem[]): string {
|
|
|
746
752
|
}
|
|
747
753
|
const lines: string[] = [];
|
|
748
754
|
for (const file of [...byFile.keys()].sort()) {
|
|
749
|
-
lines.push(file);
|
|
755
|
+
lines.push(c.bold(file));
|
|
750
756
|
for (const p of byFile.get(file)!) {
|
|
751
|
-
const
|
|
752
|
-
|
|
757
|
+
const warning = p.severity === "warning";
|
|
758
|
+
const prefix = warning ? `${c.yellow("warning")}: ` : "";
|
|
759
|
+
const message = warning ? p.message : c.red(p.message);
|
|
760
|
+
lines.push(` ${prefix}${p.path ? `${c.dim(p.path)}: ` : ""}${message}`);
|
|
753
761
|
}
|
|
754
762
|
}
|
|
755
763
|
return lines.join("\n");
|
|
@@ -808,13 +816,30 @@ export function check(options: CheckOptions = {}): number {
|
|
|
808
816
|
const errors = problems.filter((p) => p.severity === "error").length;
|
|
809
817
|
const warnings = problems.length - errors;
|
|
810
818
|
if (problems.length > 0) {
|
|
811
|
-
const text = formatProblems(problems);
|
|
819
|
+
const text = formatProblems(problems, reporter.color);
|
|
812
820
|
if (errors > 0) reporter.error(text);
|
|
813
821
|
else reporter.warn(text);
|
|
814
822
|
}
|
|
815
823
|
const count = Object.keys(saved.blocks).length;
|
|
816
|
-
const summary =
|
|
824
|
+
const summary = checkSummary(count, errors, warnings, reporter.color);
|
|
817
825
|
if (errors > 0) reporter.error(summary);
|
|
818
826
|
else reporter.info(summary);
|
|
819
827
|
return errors > 0 ? 1 : 0;
|
|
820
828
|
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* `39 saved blocks checked: 0 errors, 0 warnings`. With colour it leads with
|
|
832
|
+
* a status mark, where the eye lands first (✓ green, ⚠ yellow, ✗ red), and
|
|
833
|
+
* colours the counts that decide it.
|
|
834
|
+
*/
|
|
835
|
+
function checkSummary(count: number, errors: number, warnings: number, color = false): string {
|
|
836
|
+
const c = paint(color);
|
|
837
|
+
const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
838
|
+
const head = `${plural(count, "saved block")} checked: `;
|
|
839
|
+
const errorText = plural(errors, "error");
|
|
840
|
+
const warningText = plural(warnings, "warning");
|
|
841
|
+
if (!color) return `${head}${errorText}, ${warningText}`;
|
|
842
|
+
if (errors > 0) return `${c.red("✗")} ${head}${c.red(errorText)}, ${warningText}`;
|
|
843
|
+
if (warnings > 0) return `${c.yellow("⚠")} ${head}${errorText}, ${c.yellow(warningText)}`;
|
|
844
|
+
return `${c.green("✓")} ${head}${c.green(`${errorText}, ${warningText}`)}`;
|
|
845
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ANSI colour for the `deco` CLI's output. Off unless the run asked for it:
|
|
3
|
+
* `--color`, or a terminal on both stdout and stderr (see `runCli`). When off,
|
|
4
|
+
* every function returns its text unchanged, so piped output stays plain.
|
|
5
|
+
*/
|
|
6
|
+
export interface Paint {
|
|
7
|
+
green(text: string): string;
|
|
8
|
+
red(text: string): string;
|
|
9
|
+
yellow(text: string): string;
|
|
10
|
+
dim(text: string): string;
|
|
11
|
+
bold(text: string): string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const sgr = (open: number, close: number) => (text: string) => `\x1b[${open}m${text}\x1b[${close}m`;
|
|
15
|
+
|
|
16
|
+
const ON: Paint = {
|
|
17
|
+
green: sgr(32, 39),
|
|
18
|
+
red: sgr(31, 39),
|
|
19
|
+
yellow: sgr(33, 39),
|
|
20
|
+
dim: sgr(2, 22),
|
|
21
|
+
bold: sgr(1, 22),
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const plain = (text: string) => text;
|
|
25
|
+
const OFF: Paint = { green: plain, red: plain, yellow: plain, dim: plain, bold: plain };
|
|
26
|
+
|
|
27
|
+
export function paint(color: boolean | undefined): Paint {
|
|
28
|
+
return color ? ON : OFF;
|
|
29
|
+
}
|
package/src/v8/cli/log.ts
CHANGED
|
@@ -3,6 +3,8 @@ export interface Reporter {
|
|
|
3
3
|
info(message: string): void;
|
|
4
4
|
warn(message: string): void;
|
|
5
5
|
error(message: string): void;
|
|
6
|
+
/** Whether messages may carry ANSI colour (`--color`, or a terminal). Off when absent. */
|
|
7
|
+
color?: boolean;
|
|
6
8
|
}
|
|
7
9
|
|
|
8
10
|
export const consoleReporter: Reporter = {
|
|
@@ -11,6 +13,16 @@ export const consoleReporter: Reporter = {
|
|
|
11
13
|
error: (message) => console.error(message),
|
|
12
14
|
};
|
|
13
15
|
|
|
16
|
+
/** The same reporter, with colour turned on or off. */
|
|
17
|
+
export function withColor(reporter: Reporter, color: boolean): Reporter {
|
|
18
|
+
return {
|
|
19
|
+
info: (message) => reporter.info(message),
|
|
20
|
+
warn: (message) => reporter.warn(message),
|
|
21
|
+
error: (message) => reporter.error(message),
|
|
22
|
+
color,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
14
26
|
export const silentReporter: Reporter = {
|
|
15
27
|
info: () => {},
|
|
16
28
|
warn: () => {},
|
package/src/v8/cli/run.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { check } from "./check/index.ts";
|
|
6
6
|
import { content, writeContent } from "./content.ts";
|
|
7
|
-
import { consoleReporter, type Reporter } from "./log.ts";
|
|
7
|
+
import { consoleReporter, type Reporter, withColor } from "./log.ts";
|
|
8
8
|
import { CliError, decoPaths, findDecoRoot } from "./root.ts";
|
|
9
9
|
import { reportSchema, schema, writeSchema } from "./schema/index.ts";
|
|
10
10
|
import { serve, startServer } from "./serve/server.ts";
|
|
@@ -48,7 +48,8 @@ ${Object.values(COMMANDS)
|
|
|
48
48
|
.map((c) => ` ${c.usage}`)
|
|
49
49
|
.join("\n")}
|
|
50
50
|
|
|
51
|
-
Every command finds .deco/ by walking up from the current folder, or takes --root
|
|
51
|
+
Every command finds .deco/ by walking up from the current folder, or takes --root.
|
|
52
|
+
Every command takes --color or --no-color; without either, output is coloured only on a terminal.`;
|
|
52
53
|
|
|
53
54
|
export type ParsedFlags = Record<string, string | boolean | string[]>;
|
|
54
55
|
|
|
@@ -59,8 +60,14 @@ export function parseFlags(command: string, args: string[]): ParsedFlags {
|
|
|
59
60
|
const arg = args[i];
|
|
60
61
|
if (!arg.startsWith("--"))
|
|
61
62
|
throw new CliError(`unexpected argument "${arg}"\n${COMMANDS[command].usage}`);
|
|
63
|
+
// Every command's: `color` is true, false or absent; the last one given wins.
|
|
64
|
+
if (arg === "--color" || arg === "--no-color") {
|
|
65
|
+
flags.color = arg === "--color";
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
62
68
|
const eq = arg.indexOf("=");
|
|
63
69
|
const name = arg.slice(2, eq === -1 ? undefined : eq);
|
|
70
|
+
if (name === "color" || name === "no-color") throw new CliError(`--${name} takes no value`);
|
|
64
71
|
const kind = Object.hasOwn(spec, name) ? spec[name] : undefined;
|
|
65
72
|
if (!kind) throw new CliError(`unknown flag --${name}\n${COMMANDS[command].usage}`);
|
|
66
73
|
if (kind === "boolean") {
|
|
@@ -83,6 +90,7 @@ export function parseFlags(command: string, args: string[]): ParsedFlags {
|
|
|
83
90
|
|
|
84
91
|
export interface RunOptions {
|
|
85
92
|
cwd?: string;
|
|
93
|
+
/** Defaults to the console, coloured when stdout and stderr are both terminals. */
|
|
86
94
|
reporter?: Reporter;
|
|
87
95
|
/** Resolves when a `--watch` or `serve` run should stop (tests); defaults to SIGINT/SIGTERM. */
|
|
88
96
|
until?: Promise<void>;
|
|
@@ -128,7 +136,7 @@ Deco CMS, Studio's Publish (or Resync) makes the commit a release without a depl
|
|
|
128
136
|
|
|
129
137
|
/** Run one `deco` invocation; returns the exit code. */
|
|
130
138
|
export async function runCli(argv: string[], options: RunOptions = {}): Promise<number> {
|
|
131
|
-
|
|
139
|
+
let reporter = options.reporter ?? consoleReporter;
|
|
132
140
|
const [command, ...rest] = argv;
|
|
133
141
|
if (!command || command === "help" || command === "--help" || command === "-h") {
|
|
134
142
|
reporter.info(USAGE);
|
|
@@ -145,6 +153,13 @@ export async function runCli(argv: string[], options: RunOptions = {}): Promise<
|
|
|
145
153
|
}
|
|
146
154
|
try {
|
|
147
155
|
const flags = parseFlags(command, rest);
|
|
156
|
+
const color =
|
|
157
|
+
typeof flags.color === "boolean"
|
|
158
|
+
? flags.color
|
|
159
|
+
: options.reporter
|
|
160
|
+
? Boolean(options.reporter.color)
|
|
161
|
+
: Boolean(process.stdout.isTTY && process.stderr.isTTY);
|
|
162
|
+
reporter = withColor(reporter, color);
|
|
148
163
|
const root = flags.root as string | undefined;
|
|
149
164
|
const base = { root, cwd: options.cwd, reporter };
|
|
150
165
|
switch (command) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
+
import { paint } from "../color.ts";
|
|
2
3
|
import { writeIfChanged } from "../content.ts";
|
|
3
4
|
import { consoleReporter, type Reporter } from "../log.ts";
|
|
4
5
|
import { CliError, type DecoPaths, decoPaths, findDecoRoot } from "../root.ts";
|
|
@@ -29,12 +30,13 @@ export async function writeSchema(paths: DecoPaths): Promise<WriteSchemaResult>
|
|
|
29
30
|
}
|
|
30
31
|
|
|
31
32
|
export function reportSchema(result: WriteSchemaResult, reporter: Reporter): number {
|
|
33
|
+
const c = paint(reporter.color);
|
|
32
34
|
for (const d of result.diagnostics) {
|
|
33
|
-
if (d.severity === "error") reporter.error(d.message);
|
|
34
|
-
else reporter.warn(
|
|
35
|
+
if (d.severity === "error") reporter.error(c.red(d.message));
|
|
36
|
+
else reporter.warn(`${c.yellow("warning")}: ${d.message}`);
|
|
35
37
|
}
|
|
36
38
|
if (!result.written) {
|
|
37
|
-
reporter.error(".deco/schema.gen.json not written: fix the errors above");
|
|
39
|
+
reporter.error(c.red(".deco/schema.gen.json not written: fix the errors above"));
|
|
38
40
|
return 1;
|
|
39
41
|
}
|
|
40
42
|
const groups = result.meta.manifest.blocks;
|
|
@@ -293,7 +293,7 @@ export class TsSignature {
|
|
|
293
293
|
/** One JSDoc comment: its description and its tags. */
|
|
294
294
|
export interface JsDocView {
|
|
295
295
|
getDescription(): string;
|
|
296
|
-
getTags(): { getTagName(): string; getCommentText(): string | undefined }[];
|
|
296
|
+
getTags(): { getTagName(): string; getCommentText(): string | undefined; getText(): string }[];
|
|
297
297
|
}
|
|
298
298
|
|
|
299
299
|
export class TsNode {
|
|
@@ -458,6 +458,7 @@ function jsDocView(ts: TypeScript, doc: TS.JSDoc): JsDocView {
|
|
|
458
458
|
return (doc.tags ?? []).map((tag) => ({
|
|
459
459
|
getTagName: () => tag.tagName.getText(sourceFile),
|
|
460
460
|
getCommentText: () => commentText(tag.comment),
|
|
461
|
+
getText: () => tag.getText(sourceFile),
|
|
461
462
|
}));
|
|
462
463
|
},
|
|
463
464
|
};
|
|
@@ -81,6 +81,11 @@ export function getJsDocTags(symbol: MorphSymbol): Record<string, string> {
|
|
|
81
81
|
const desc = doc.getDescription().trim();
|
|
82
82
|
if (desc) tags.description = desc;
|
|
83
83
|
for (const tag of doc.getTags()) {
|
|
84
|
+
// deco-cx/deco reads tags with /@(\w+)\s+/, so `@description: text` was
|
|
85
|
+
// never a description there and the editor did not show it. The TS
|
|
86
|
+
// parser splits it into tag `description` + comment `: text`; skip it
|
|
87
|
+
// rather than emit a description that starts with ": ".
|
|
88
|
+
if (/^@\w+[^\w\s]/.test(tag.getText())) continue;
|
|
84
89
|
tags[tag.getTagName()] = tag.getCommentText()?.trim() || "true";
|
|
85
90
|
}
|
|
86
91
|
}
|
|
@@ -543,13 +548,39 @@ function isOpaqueSectionType(propType: Type): boolean {
|
|
|
543
548
|
return type.isAny() || type.isUnknown();
|
|
544
549
|
}
|
|
545
550
|
|
|
551
|
+
/**
|
|
552
|
+
* The schema of a type met again while it is still being expanded (a
|
|
553
|
+
* recursive type, `interface Link { submenu?: Link[] }`): a `$ref` to the
|
|
554
|
+
* type's shared definition, looking through the array / `| null` wrapper the
|
|
555
|
+
* cycle was met on, so `submenu` is `{ type: "array", items: { $ref } }`.
|
|
556
|
+
* Null when there is nothing to reference (anonymous or generic types).
|
|
557
|
+
*/
|
|
558
|
+
function recursiveRef(type: Type, ctx?: SchemaContext): any | null {
|
|
559
|
+
if (!ctx) return null;
|
|
560
|
+
if (type.isUnion()) {
|
|
561
|
+
const parts = type.getUnionTypes();
|
|
562
|
+
const nonNull = parts.filter((t) => !t.isNull() && !t.isUndefined());
|
|
563
|
+
if (nonNull.length !== 1) return null;
|
|
564
|
+
const inner = recursiveRef(nonNull[0], ctx);
|
|
565
|
+
return inner && nonNull.length < parts.length ? { ...inner, nullable: true } : inner;
|
|
566
|
+
}
|
|
567
|
+
if (type.isArray()) {
|
|
568
|
+
const element = type.getArrayElementType();
|
|
569
|
+
const items = element ? recursiveRef(element, ctx) : null;
|
|
570
|
+
return items ? { type: "array", items } : null;
|
|
571
|
+
}
|
|
572
|
+
return ctx.namedDefinition(type);
|
|
573
|
+
}
|
|
574
|
+
|
|
546
575
|
export function typeToJsonSchema(
|
|
547
576
|
type: Type,
|
|
548
577
|
visited = new Set<string>(),
|
|
549
578
|
ctx?: SchemaContext,
|
|
550
579
|
): any {
|
|
551
580
|
const typeText = type.getText();
|
|
552
|
-
|
|
581
|
+
// A cycle: reference the type's shared definition instead of collapsing it
|
|
582
|
+
// to a bare object, as deco-cx/deco does.
|
|
583
|
+
if (visited.has(typeText)) return recursiveRef(type, ctx) ?? { type: "object" };
|
|
553
584
|
visited.add(typeText);
|
|
554
585
|
|
|
555
586
|
try {
|
|
@@ -571,9 +602,12 @@ export function typeToJsonSchema(
|
|
|
571
602
|
if (isSectionType(type)) return sectionRef();
|
|
572
603
|
|
|
573
604
|
if (type.isString() || type.isStringLiteral()) {
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
605
|
+
if (!type.isStringLiteral()) return { type: "string" };
|
|
606
|
+
// deco-cx/deco pairs every `const` with an equal `default`, so the editor
|
|
607
|
+
// writes the literal into new entries, e.g. a hidden `__type: "image"`
|
|
608
|
+
// discriminator the component branches on.
|
|
609
|
+
const value = type.getLiteralValue();
|
|
610
|
+
return { type: "string", const: value, default: value };
|
|
577
611
|
}
|
|
578
612
|
if (type.isNumber() || type.isNumberLiteral()) return { type: "number" };
|
|
579
613
|
if (type.isBoolean() || type.isBooleanLiteral()) return { type: "boolean" };
|
|
@@ -682,7 +716,10 @@ export function typeToJsonSchema(
|
|
|
682
716
|
|
|
683
717
|
for (const prop of type.getProperties()) {
|
|
684
718
|
const name = prop.getName();
|
|
685
|
-
|
|
719
|
+
// `_`-prefixed props are site data (`__title` labels a list entry in the
|
|
720
|
+
// editor, `_id` keys a dynamic-options picker) and deco-cx/deco keeps
|
|
721
|
+
// them; only the block-reference discriminator is framework-owned.
|
|
722
|
+
if (name === "__resolveType" || name.startsWith("$") || name === "@type") continue;
|
|
686
723
|
if (REACT_INTERNAL_PROPS.has(name)) continue;
|
|
687
724
|
|
|
688
725
|
const decl = prop.getValueDeclaration() ?? prop.getDeclarations()[0];
|
|
@@ -732,8 +769,11 @@ export function typeToJsonSchema(
|
|
|
732
769
|
schema.title ??= titleCase(name);
|
|
733
770
|
properties[name] = schema;
|
|
734
771
|
// A hidden prop can't be filled in by an editor; requiring it would
|
|
735
|
-
// deadlock the form.
|
|
736
|
-
|
|
772
|
+
// deadlock the form. Unless it has a default the editor writes for
|
|
773
|
+
// the user (a hidden literal such as `__title: "…"`), which
|
|
774
|
+
// deco-cx/deco keeps required.
|
|
775
|
+
const fillable = schema.hide !== "true" || "default" in schema;
|
|
776
|
+
if (!optional && fillable) required.push(name);
|
|
737
777
|
}
|
|
738
778
|
|
|
739
779
|
const result: any = { type: "object", properties };
|
package/src/v8/cms.ts
CHANGED
|
@@ -362,7 +362,7 @@ export function resetForTests(): void {
|
|
|
362
362
|
/** With `site`, the content is the fallback of hosted releases. */
|
|
363
363
|
function contentOf(config: CMSConfig): Snapshot | Loader {
|
|
364
364
|
if (!config.site) return config.content;
|
|
365
|
-
return remoteLoader(config.content, { site: config.site });
|
|
365
|
+
return remoteLoader(config.content, { site: config.site, dev: config.dev });
|
|
366
366
|
}
|
|
367
367
|
|
|
368
368
|
function validate(config: CMSConfig): void {
|
package/src/v8/matchRoute.ts
CHANGED
|
@@ -2,30 +2,37 @@
|
|
|
2
2
|
* `matchRoute(url, items)`: finds the entry for a URL (see /next/routing and
|
|
3
3
|
* /next/router-internals).
|
|
4
4
|
*
|
|
5
|
-
* Paths compile into a segment trie, cached per array
|
|
6
|
-
* the URL's depth, not the number of routes. At every
|
|
7
|
-
* literal child, then the parameter child, then a
|
|
8
|
-
* or more remaining segments), so exact paths win
|
|
9
|
-
* parameters over a splat, per segment. Redirects are
|
|
10
|
-
* first
|
|
11
|
-
*
|
|
12
|
-
* one
|
|
5
|
+
* Paths compile into a segment trie (`routeTrie.ts`), cached per array
|
|
6
|
+
* object: a lookup costs the URL's depth, not the number of routes. At every
|
|
7
|
+
* node the walk tries the literal child, then the parameter child, then a
|
|
8
|
+
* trailing `*` (a splat: one or more remaining segments), so exact paths win
|
|
9
|
+
* over parameters and parameters over a splat, per segment. Redirects are
|
|
10
|
+
* checked first, in their own tries: one per query a `from` is scoped to
|
|
11
|
+
* (`/calcados?map=c,ft`), tried when the request's query is exactly that one,
|
|
12
|
+
* then one for the path-only sources. Two entries that reach the same leaf
|
|
13
|
+
* are a conflict `deco check` reports; here the earlier one keeps it, so a
|
|
14
|
+
* lookup never throws. No regex, no sorting.
|
|
13
15
|
*/
|
|
16
|
+
|
|
17
|
+
import type { TrieNode } from "./routeTrie.ts";
|
|
18
|
+
import {
|
|
19
|
+
buildTrie,
|
|
20
|
+
type Hit,
|
|
21
|
+
insert,
|
|
22
|
+
lookup,
|
|
23
|
+
safeDecode,
|
|
24
|
+
splitPath,
|
|
25
|
+
splitRef,
|
|
26
|
+
} from "./routeTrie.ts";
|
|
14
27
|
import type { LegacyRedirect, Match, Redirect, RedirectStatus, Route } from "./types.ts";
|
|
15
28
|
|
|
16
|
-
/**
|
|
17
|
-
type
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
param?: TrieNode<T>;
|
|
21
|
-
leaf?: Leaf<T>;
|
|
22
|
-
splat?: Leaf<T>;
|
|
23
|
-
};
|
|
24
|
-
type Hit<T> = { value: T; params: Record<string, string>; rest: string[] };
|
|
25
|
-
type NormalizedRedirect = Redirect & { status: RedirectStatus };
|
|
29
|
+
/** `query`: what `from` is scoped to, after its `?` (`""`: any query, or none). */
|
|
30
|
+
type NormalizedRedirect = Redirect & { status: RedirectStatus; query: string };
|
|
31
|
+
/** The redirect tries, by the query their sources are scoped to (`""`: path-only). */
|
|
32
|
+
type RedirectTries = Map<string, TrieNode<NormalizedRedirect>>;
|
|
26
33
|
|
|
27
34
|
const routeTries = new WeakMap<object, TrieNode<Route>>();
|
|
28
|
-
const redirectTries = new WeakMap<object,
|
|
35
|
+
const redirectTries = new WeakMap<object, RedirectTries>();
|
|
29
36
|
const STATUSES = new Set<number>([301, 302, 307, 308]);
|
|
30
37
|
|
|
31
38
|
export function matchRoute<T extends Route>(
|
|
@@ -36,21 +43,21 @@ export function matchRoute<T extends Route>(
|
|
|
36
43
|
if (target === null) return { kind: "not-found" };
|
|
37
44
|
|
|
38
45
|
const redirects: unknown[] = Array.isArray(items?.redirects) ? items.redirects : [];
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
if (redirect
|
|
46
|
+
const tries = cached(redirectTries, redirects, () => compileRedirects(redirects));
|
|
47
|
+
// A source scoped to the request's exact query string beats a path-only one,
|
|
48
|
+
// as Fresh's router tried `pathname + search` before `pathname`.
|
|
49
|
+
const scoped = target.search ? tries.get(target.search.slice(1)) : undefined;
|
|
50
|
+
const pathOnly = tries.get("");
|
|
51
|
+
const redirect =
|
|
52
|
+
(scoped && lookup(scoped, target.segments)) || (pathOnly && lookup(pathOnly, target.segments));
|
|
53
|
+
if (redirect) {
|
|
47
54
|
const location = buildLocation(redirect, target.search);
|
|
48
55
|
return { kind: "redirect", location, status: redirect.value.status };
|
|
49
56
|
}
|
|
50
57
|
|
|
51
58
|
const routes = Array.isArray(items?.routes) ? items.routes : [];
|
|
52
59
|
const trie = cached(routeTries, routes, () =>
|
|
53
|
-
routes.filter((r) => typeof r?.path === "string").map((r) => [r.path, r as Route]),
|
|
60
|
+
buildTrie(routes.filter((r) => typeof r?.path === "string").map((r) => [r.path, r as Route])),
|
|
54
61
|
);
|
|
55
62
|
const found = lookup(trie, target.segments);
|
|
56
63
|
if (found === null) return { kind: "not-found" };
|
|
@@ -70,95 +77,45 @@ function parseTarget(url: string | URL | Request): { segments: string[]; search:
|
|
|
70
77
|
}
|
|
71
78
|
}
|
|
72
79
|
|
|
73
|
-
/**
|
|
74
|
-
function
|
|
75
|
-
const query = path.indexOf("?");
|
|
76
|
-
const hash = path.indexOf("#");
|
|
77
|
-
const end = Math.min(query === -1 ? path.length : query, hash === -1 ? path.length : hash);
|
|
78
|
-
return path
|
|
79
|
-
.slice(0, end)
|
|
80
|
-
.split("/")
|
|
81
|
-
.filter((segment) => segment.length > 0);
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
function safeDecode(segment: string): string {
|
|
85
|
-
try {
|
|
86
|
-
return decodeURIComponent(segment);
|
|
87
|
-
} catch {
|
|
88
|
-
return segment;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/** The trie for an array, built once per array object. */
|
|
93
|
-
function cached<T>(cache: WeakMap<object, TrieNode<T>>, key: object, entries: () => [string, T][]) {
|
|
80
|
+
/** Built once per array object. */
|
|
81
|
+
function cached<V>(cache: WeakMap<object, V>, key: object, build: () => V): V {
|
|
94
82
|
const hit = cache.get(key);
|
|
95
83
|
if (hit) return hit;
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
return root;
|
|
84
|
+
const value = build();
|
|
85
|
+
cache.set(key, value);
|
|
86
|
+
return value;
|
|
100
87
|
}
|
|
101
88
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
if (node.splat) return node.splat.value;
|
|
110
|
-
node.splat = { value, names };
|
|
111
|
-
return undefined;
|
|
112
|
-
}
|
|
113
|
-
if (segment.startsWith(":") && segment.length > 1) {
|
|
114
|
-
names.push(segment.slice(1));
|
|
115
|
-
node = node.param ??= { literals: new Map() };
|
|
116
|
-
continue;
|
|
117
|
-
}
|
|
118
|
-
const literal = safeDecode(segment);
|
|
119
|
-
const child = node.literals.get(literal) ?? { literals: new Map() };
|
|
120
|
-
node.literals.set(literal, child);
|
|
121
|
-
node = child;
|
|
89
|
+
function compileRedirects(redirects: unknown[]): RedirectTries {
|
|
90
|
+
const tries: RedirectTries = new Map();
|
|
91
|
+
for (const redirect of redirects.map(normalizeRedirect)) {
|
|
92
|
+
if (redirect === null) continue;
|
|
93
|
+
const root = tries.get(redirect.query) ?? { literals: new Map() };
|
|
94
|
+
tries.set(redirect.query, root);
|
|
95
|
+
insert(root, redirect.from, redirect);
|
|
122
96
|
}
|
|
123
|
-
|
|
124
|
-
node.leaf = { value, names };
|
|
125
|
-
return undefined;
|
|
97
|
+
return tries;
|
|
126
98
|
}
|
|
127
99
|
|
|
128
100
|
/**
|
|
129
101
|
* The entries that reach a leaf an earlier entry already holds: two equal
|
|
130
|
-
* paths, or two templates of one shape (`/:slug/p` and `/:id/p`)
|
|
131
|
-
* serves the earlier one; `deco check` reports each pair.
|
|
102
|
+
* paths, or two templates of one shape (`/:slug/p` and `/:id/p`), scoped to the
|
|
103
|
+
* same query. `matchRoute` serves the earlier one; `deco check` reports each pair.
|
|
132
104
|
*/
|
|
133
105
|
export function findRouteConflicts<T extends { path: string }>(entries: readonly T[]) {
|
|
134
|
-
|
|
106
|
+
// A redirect scoped to a query (`/x?map=ft`) never meets `/x` or `/x?map=c`.
|
|
107
|
+
const roots = new Map<string, TrieNode<T>>();
|
|
135
108
|
const conflicts: { entry: T; other: T }[] = [];
|
|
136
109
|
for (const entry of entries) {
|
|
110
|
+
const query = splitRef(entry.path).query;
|
|
111
|
+
const root = roots.get(query) ?? { literals: new Map() };
|
|
112
|
+
roots.set(query, root);
|
|
137
113
|
const other = insert(root, entry.path, entry);
|
|
138
114
|
if (other !== undefined) conflicts.push({ entry, other });
|
|
139
115
|
}
|
|
140
116
|
return conflicts;
|
|
141
117
|
}
|
|
142
118
|
|
|
143
|
-
/** Walks the URL's segments: the literal child first, then the parameter child, then the splat. */
|
|
144
|
-
function lookup<T>(node: TrieNode<T>, segs: string[], i = 0, vals: string[] = []): Hit<T> | null {
|
|
145
|
-
if (i === segs.length) return node.leaf ? hit(node.leaf, vals, []) : null;
|
|
146
|
-
const literal = node.literals.get(segs[i]!);
|
|
147
|
-
let found = literal ? lookup(literal, segs, i + 1, vals) : null;
|
|
148
|
-
// A parameter is one segment and never contains a slash, even an encoded one.
|
|
149
|
-
if (!found && node.param && !segs[i]!.includes("/")) {
|
|
150
|
-
found = lookup(node.param, segs, i + 1, [...vals, segs[i]!]);
|
|
151
|
-
}
|
|
152
|
-
// A splat takes the rest (at least one segment, as there is one here).
|
|
153
|
-
return found ?? (node.splat ? hit(node.splat, vals, segs.slice(i)) : null);
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
function hit<T>({ value, names }: Leaf<T>, values: string[], rest: string[]): Hit<T> {
|
|
157
|
-
const params: Record<string, string> = Object.fromEntries(names.map((n, i) => [n, values[i]!]));
|
|
158
|
-
if (rest.length > 0) params["*"] = rest.join("/");
|
|
159
|
-
return { value, params, rest };
|
|
160
|
-
}
|
|
161
|
-
|
|
162
119
|
/**
|
|
163
120
|
* Both redirect shapes: the flat built-in `{ from, to, permanent, status?,
|
|
164
121
|
* discardQueryParameters? }` and the site editor's legacy nested
|
|
@@ -174,7 +131,17 @@ function normalizeRedirect(input: unknown): NormalizedRedirect | null {
|
|
|
174
131
|
if (nested) status = flat.type === "permanent" ? 301 : 307;
|
|
175
132
|
else if (STATUSES.has(flat.status as number)) status = flat.status as RedirectStatus;
|
|
176
133
|
const { from, to, discardQueryParameters } = flat;
|
|
177
|
-
|
|
134
|
+
const query = splitRef(from).query;
|
|
135
|
+
// A `to` naming the path `from` matches would match again, forever: `/a` →
|
|
136
|
+
// `/a`, `/a/` → `/a`, `/x` → `/x?utm=1` (a path-only source takes any
|
|
137
|
+
// query), `/p/:id` → `/p/:id`, and `/x?a=1` → `/x` (the query is carried
|
|
138
|
+
// over). Dropped, as Fresh's loader skipped `from === to`. Compared as
|
|
139
|
+
// written (`/café` and `/caf%C3%A9` aren't folded); `https://…` never equals.
|
|
140
|
+
const back = [splitRef(to).query, discardQueryParameters ? "" : query].filter(Boolean).join("&");
|
|
141
|
+
const loops = splitPath(from).join("/") === splitPath(to).join("/") && (!query || back === query);
|
|
142
|
+
if (to[0] === "/" && loops) return null;
|
|
143
|
+
const permanent = status === 301 || status === 308;
|
|
144
|
+
return { from, to, permanent, status, discardQueryParameters, query };
|
|
178
145
|
}
|
|
179
146
|
|
|
180
147
|
/**
|
|
@@ -185,11 +152,8 @@ function normalizeRedirect(input: unknown): NormalizedRedirect | null {
|
|
|
185
152
|
* into `//other.host` (or `/\other.host`).
|
|
186
153
|
*/
|
|
187
154
|
function buildLocation({ value: redirect, params, rest }: Hit<NormalizedRedirect>, search: string) {
|
|
188
|
-
const {
|
|
189
|
-
const
|
|
190
|
-
const queryAt = to.indexOf("?") === -1 || to.indexOf("?") > hashAt ? hashAt : to.indexOf("?");
|
|
191
|
-
const filled = to
|
|
192
|
-
.slice(0, queryAt)
|
|
155
|
+
const { path, query: written, hash } = splitRef(redirect.to);
|
|
156
|
+
const filled = path
|
|
193
157
|
.split("/")
|
|
194
158
|
.map((s) => {
|
|
195
159
|
if (s === "*" && rest.length > 0) return rest.map(encodeURIComponent).join("/");
|
|
@@ -199,6 +163,6 @@ function buildLocation({ value: redirect, params, rest }: Hit<NormalizedRedirect
|
|
|
199
163
|
})
|
|
200
164
|
.join("/");
|
|
201
165
|
const carried = redirect.discardQueryParameters ? "" : search.slice(1);
|
|
202
|
-
const query = [
|
|
203
|
-
return `${filled}${query ? `?${query}` : ""}${
|
|
166
|
+
const query = [written, carried].filter(Boolean).join("&");
|
|
167
|
+
return `${filled}${query ? `?${query}` : ""}${hash}`;
|
|
204
168
|
}
|
package/src/v8/remoteLoader.ts
CHANGED
|
@@ -25,7 +25,9 @@
|
|
|
25
25
|
* a publish still loses to it.
|
|
26
26
|
* Pointers aren't ordered among themselves, and the fallback's content is
|
|
27
27
|
* never compared: only the two timestamps are.
|
|
28
|
-
* -
|
|
28
|
+
* - With `dev: true` (`createCMS({ dev })`), it never swaps, so local files win.
|
|
29
|
+
* The SDK reads no environment variable to decide this: the site passes it
|
|
30
|
+
* (`import.meta.env.DEV`, `process.env.NODE_ENV === "development"`).
|
|
29
31
|
* - A release larger than `MAX_SNAPSHOT_BYTES` is refused while it downloads,
|
|
30
32
|
* before it's buffered whole (a Worker isolate has 128 MB).
|
|
31
33
|
* - Without `site` it's a plain loader over the fallback.
|
|
@@ -55,6 +57,8 @@ interface RemoteLoaderOptions {
|
|
|
55
57
|
site?: string;
|
|
56
58
|
/** ms between release checks, used when `createCMS` has no `interval` of its own. */
|
|
57
59
|
interval?: number;
|
|
60
|
+
/** Local development: never swap in a release, so local files win. */
|
|
61
|
+
dev?: boolean;
|
|
58
62
|
}
|
|
59
63
|
|
|
60
64
|
/** `sites/<site>/latest.json`: the release a site serves. */
|
|
@@ -73,11 +77,16 @@ class RemoteLoader implements Loader {
|
|
|
73
77
|
#fallbackSnapshot: Snapshot | undefined;
|
|
74
78
|
/** The release this process last swapped in; `undefined` serves the fallback. */
|
|
75
79
|
#current: Snapshot | undefined;
|
|
80
|
+
readonly #dev: boolean;
|
|
76
81
|
|
|
77
|
-
constructor(
|
|
82
|
+
constructor(
|
|
83
|
+
fallback: Snapshot | Loader,
|
|
84
|
+
options: { site: string; interval?: number; dev?: boolean },
|
|
85
|
+
) {
|
|
78
86
|
this.#fallback = fallback;
|
|
79
87
|
this.#site = options.site;
|
|
80
88
|
this.interval = options.interval;
|
|
89
|
+
this.#dev = options.dev === true;
|
|
81
90
|
}
|
|
82
91
|
|
|
83
92
|
/** A hot reload hands the same instance new fallback content. */
|
|
@@ -98,7 +107,7 @@ class RemoteLoader implements Loader {
|
|
|
98
107
|
}
|
|
99
108
|
|
|
100
109
|
async update(): Promise<{ updated: boolean }> {
|
|
101
|
-
if (
|
|
110
|
+
if (this.#dev) return { updated: false };
|
|
102
111
|
const fallback = this.#fallbackSnapshot ?? (await this.#loadFallback());
|
|
103
112
|
if (fallback.schemaHash === undefined) return { updated: false };
|
|
104
113
|
const site = encodeURIComponent(this.#site);
|
|
@@ -211,7 +220,7 @@ export function remoteLoader(fallback: Snapshot | Loader, options: RemoteLoaderO
|
|
|
211
220
|
return existing;
|
|
212
221
|
}
|
|
213
222
|
const instance = hosted
|
|
214
|
-
? new RemoteLoader(fallback, { site: site!, interval: options.interval })
|
|
223
|
+
? new RemoteLoader(fallback, { site: site!, interval: options.interval, dev: options.dev })
|
|
215
224
|
: new LocalLoader(fallback);
|
|
216
225
|
store[key] = instance;
|
|
217
226
|
return instance;
|
|
@@ -241,16 +250,3 @@ function deliveryOrigin(): string {
|
|
|
241
250
|
const override = (globalThis as Record<symbol, unknown>)[TEST_DELIVERY_ORIGIN];
|
|
242
251
|
return typeof override === "string" ? override : HOSTED_DELIVERY_ORIGIN;
|
|
243
252
|
}
|
|
244
|
-
|
|
245
|
-
/**
|
|
246
|
-
* The SDK's only environment read: local development never swaps in hosted
|
|
247
|
-
* releases, so local files win.
|
|
248
|
-
*/
|
|
249
|
-
function isDevelopment(): boolean {
|
|
250
|
-
try {
|
|
251
|
-
// Written out so bundlers that define process.env.NODE_ENV replace it.
|
|
252
|
-
return process.env.NODE_ENV === "development";
|
|
253
|
-
} catch {
|
|
254
|
-
return false;
|
|
255
|
-
}
|
|
256
|
-
}
|