@decocms/blocks 7.72.0 → 8.0.0-next.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/bin/deco.js +13 -0
- package/package.json +32 -3
- package/src/cms/schema.ts +1 -1
- package/src/hooks/LiveControls.tsx +2 -0
- package/src/hooks/useLoadMore.ts +2 -0
- package/src/index.ts +37 -0
- package/src/protocol/assets.ts +124 -0
- package/src/protocol/canonical.ts +7 -0
- package/src/protocol/ciphertext.ts +6 -0
- package/src/protocol/client.ts +170 -0
- package/src/protocol/conformance/cases/assets.ts +81 -0
- package/src/protocol/conformance/cases/guards.ts +314 -0
- package/src/protocol/conformance/cases/reads.ts +168 -0
- package/src/protocol/conformance/cases/types.ts +9 -0
- package/src/protocol/conformance/cases/wire.ts +138 -0
- package/src/protocol/conformance/cases/writes.ts +345 -0
- package/src/protocol/conformance/contentHashFixtures.ts +79 -0
- package/src/protocol/conformance/context.ts +222 -0
- package/src/protocol/conformance/index.ts +140 -0
- package/src/protocol/errors.ts +142 -0
- package/src/protocol/index.ts +39 -0
- package/src/protocol/keys.ts +279 -0
- package/src/protocol/params.ts +67 -0
- package/src/protocol/secrets.ts +231 -0
- package/src/protocol/server/assets.ts +119 -0
- package/src/protocol/server/auth.ts +49 -0
- package/src/protocol/server/bodyCache.ts +84 -0
- package/src/protocol/server/content.ts +175 -0
- package/src/protocol/server/core.ts +112 -0
- package/src/protocol/server/handler.ts +102 -0
- package/src/protocol/server/http.ts +139 -0
- package/src/protocol/server/index.ts +11 -0
- package/src/protocol/server/methods/apply.ts +341 -0
- package/src/protocol/server/methods/read.ts +156 -0
- package/src/protocol/server/rpc.ts +136 -0
- package/src/protocol/storage/fs/hash.ts +21 -0
- package/src/protocol/storage/fs/index.ts +338 -0
- package/src/protocol/storage/fs/lock.ts +68 -0
- package/src/protocol/storage/fs/transaction.ts +183 -0
- package/src/protocol/storage/fs/unsupported.ts +15 -0
- package/src/protocol/storage/memory.ts +238 -0
- package/src/protocol/storage.ts +182 -0
- package/src/protocol/types.ts +172 -0
- package/src/v8/analytics.ts +50 -0
- package/src/v8/background.ts +107 -0
- package/src/v8/builtins/data.ts +23 -0
- package/src/v8/builtins/index.ts +26 -0
- package/src/v8/builtins/lazy.ts +23 -0
- package/src/v8/builtins/legacy.ts +65 -0
- package/src/v8/builtins/matchers.ts +31 -0
- package/src/v8/builtins/multivariate.ts +25 -0
- package/src/v8/builtins/secret.ts +82 -0
- package/src/v8/canonical.ts +117 -0
- package/src/v8/ciphertext.ts +158 -0
- package/src/v8/cli/builtins.ts +20 -0
- package/src/v8/cli/check/index.ts +774 -0
- package/src/v8/cli/check/messages.ts +168 -0
- package/src/v8/cli/content.ts +287 -0
- package/src/v8/cli/index.ts +17 -0
- package/src/v8/cli/log.ts +18 -0
- package/src/v8/cli/main.ts +12 -0
- package/src/v8/cli/root.ts +66 -0
- package/src/v8/cli/run.ts +236 -0
- package/src/v8/cli/schema/builtinSchemas.ts +236 -0
- package/src/v8/cli/schema/generate.ts +507 -0
- package/src/v8/cli/schema/index.ts +63 -0
- package/src/v8/cli/schema/tsProgram.ts +497 -0
- package/src/v8/cli/schema/typeToSchema.ts +689 -0
- package/src/v8/cli/serve/server.ts +303 -0
- package/src/v8/cli/watch.ts +86 -0
- package/src/v8/client.ts +147 -0
- package/src/v8/cms.ts +237 -0
- package/src/v8/content.ts +195 -0
- package/src/v8/draft.ts +136 -0
- package/src/v8/errors.ts +59 -0
- package/src/v8/fetch.ts +152 -0
- package/src/v8/identity.ts +65 -0
- package/src/v8/index.ts +39 -0
- package/src/v8/json.ts +74 -0
- package/src/v8/matchRoute.ts +204 -0
- package/src/v8/remoteLoader.ts +282 -0
- package/src/v8/resolver.ts +278 -0
- package/src/v8/secrets.ts +17 -0
- package/src/v8/telemetry.ts +533 -0
- package/src/v8/types.ts +240 -0
- package/src/cms/blockSource.test.ts +0 -76
- package/src/cms/client.browserBundle.test.ts +0 -44
- package/src/cms/deferredTrigger.test.ts +0 -32
- package/src/cms/draftSource.test.ts +0 -519
- package/src/cms/layoutCacheRace.test.ts +0 -181
- package/src/cms/loadDecofileDirectory.test.ts +0 -109
- package/src/cms/loader.test.ts +0 -557
- package/src/cms/registry.test.ts +0 -110
- package/src/cms/renderJson.test.ts +0 -167
- package/src/cms/resolve.test.ts +0 -1492
- package/src/cms/schema.test.ts +0 -356
- package/src/cms/sectionLoaderContext.test.ts +0 -111
- package/src/cms/sectionLoaders.test.ts +0 -625
- package/src/cms/sectionMixins.test.ts +0 -167
- package/src/cms/stickyFlags.test.ts +0 -117
- package/src/flags/flags.test.ts +0 -148
- package/src/hooks/Image.test.ts +0 -239
- package/src/hooks/RenderSection.test.tsx +0 -81
- package/src/hooks/Stats.test.ts +0 -112
- package/src/hooks/useLoadMore.test.ts +0 -205
- package/src/matchers/builtins.test.ts +0 -318
- package/src/matchers/override.test.ts +0 -205
- package/src/middleware/hydrationContext.test.ts +0 -61
- package/src/middleware/observability.test.ts +0 -335
- package/src/middleware/validateSection.test.ts +0 -147
- package/src/preview/DraftPreviewBadge.render.test.tsx +0 -67
- package/src/preview/DraftPreviewBadge.test.ts +0 -55
- package/src/sdk/abTesting.test.ts +0 -381
- package/src/sdk/cacheHeaders.test.ts +0 -258
- package/src/sdk/cacheStorage.test.ts +0 -242
- package/src/sdk/cachedLoader.test.ts +0 -122
- package/src/sdk/cachedLoaderMaxBytes.test.ts +0 -23
- package/src/sdk/cachedLoaderModule.test.ts +0 -209
- package/src/sdk/cachedLoaderSizeMetric.test.ts +0 -93
- package/src/sdk/cn.test.ts +0 -34
- package/src/sdk/composite.test.ts +0 -121
- package/src/sdk/cookie.test.ts +0 -108
- package/src/sdk/crypto.test.ts +0 -65
- package/src/sdk/deepOmit.test.ts +0 -45
- package/src/sdk/encoding.test.ts +0 -71
- package/src/sdk/env.test.ts +0 -33
- package/src/sdk/experiments.test.ts +0 -328
- package/src/sdk/fetchCache.test.ts +0 -164
- package/src/sdk/flags.test.ts +0 -91
- package/src/sdk/http.test.ts +0 -71
- package/src/sdk/inflightTimeout.test.ts +0 -35
- package/src/sdk/instrumentedFetch.test.ts +0 -559
- package/src/sdk/invoke.test.ts +0 -115
- package/src/sdk/logger.test.ts +0 -432
- package/src/sdk/otel.test.ts +0 -691
- package/src/sdk/otelAdapters.test.ts +0 -89
- package/src/sdk/otelHttpLog.test.ts +0 -457
- package/src/sdk/otelHttpMeter.test.ts +0 -395
- package/src/sdk/otelHttpTracer.test.ts +0 -474
- package/src/sdk/replaceStream.test.ts +0 -117
- package/src/sdk/requestContextStorage.browser.test.ts +0 -29
- package/src/sdk/splitExactRedirects.test.ts +0 -154
- package/src/sdk/urlRedaction.test.ts +0 -73
- package/src/sdk/urlUtils.test.ts +0 -34
- package/src/sdk/useDevice.test.ts +0 -130
- package/src/sdk/useScript.test.ts +0 -128
- package/src/sdk/useSuggestions.test.ts +0 -230
- package/tsconfig.json +0 -7
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validator errors rewritten into short plain lines (spec: internals › How
|
|
3
|
+
* deco check works): `title: required`, `title: 214 characters, max 60`,
|
|
4
|
+
* `size: "xl" isn't one of "sm", "md", "lg"`.
|
|
5
|
+
*/
|
|
6
|
+
import type { ErrorObject } from "ajv";
|
|
7
|
+
|
|
8
|
+
export const BLOCK_DEF = "__deco_block__";
|
|
9
|
+
|
|
10
|
+
/** `sections[2].title` from a base path and a JSON pointer. */
|
|
11
|
+
export function joinPath(base: string, pointer: string): string {
|
|
12
|
+
let out = base;
|
|
13
|
+
for (const raw of pointer.split("/").slice(1)) {
|
|
14
|
+
const seg = raw.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
15
|
+
if (/^\d+$/.test(seg)) out += `[${seg}]`;
|
|
16
|
+
else if (/^[A-Za-z_$][\w$-]*$/.test(seg)) out += out ? `.${seg}` : seg;
|
|
17
|
+
else out += `[${JSON.stringify(seg)}]`;
|
|
18
|
+
}
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const show = (value: unknown) => JSON.stringify(value) ?? String(value);
|
|
23
|
+
|
|
24
|
+
function typeName(value: unknown): string {
|
|
25
|
+
if (value === null) return "null";
|
|
26
|
+
if (Array.isArray(value)) return "a list";
|
|
27
|
+
switch (typeof value) {
|
|
28
|
+
case "string":
|
|
29
|
+
return "a string";
|
|
30
|
+
case "number":
|
|
31
|
+
return "a number";
|
|
32
|
+
case "boolean":
|
|
33
|
+
return "a boolean";
|
|
34
|
+
case "object":
|
|
35
|
+
return "an object";
|
|
36
|
+
default:
|
|
37
|
+
return typeof value;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function expected(type: unknown): string {
|
|
42
|
+
const types = Array.isArray(type) ? type : [type];
|
|
43
|
+
return types
|
|
44
|
+
.map((t) =>
|
|
45
|
+
t === "array"
|
|
46
|
+
? "a list"
|
|
47
|
+
: t === "object"
|
|
48
|
+
? "an object"
|
|
49
|
+
: t === "integer"
|
|
50
|
+
? "an integer"
|
|
51
|
+
: `a ${t}`,
|
|
52
|
+
)
|
|
53
|
+
.join(" or ");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function valueAt(data: unknown, pointer: string): unknown {
|
|
57
|
+
let cur: any = data;
|
|
58
|
+
for (const raw of pointer.split("/").slice(1)) {
|
|
59
|
+
if (cur === null || typeof cur !== "object") return undefined;
|
|
60
|
+
cur = cur[raw.replace(/~1/g, "/").replace(/~0/g, "~")];
|
|
61
|
+
}
|
|
62
|
+
return cur;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface PlainError {
|
|
66
|
+
path: string;
|
|
67
|
+
message: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function plain(error: ErrorObject, data: unknown, base: string): PlainError {
|
|
71
|
+
const value = valueAt(data, error.instancePath);
|
|
72
|
+
const at = joinPath(base, error.instancePath);
|
|
73
|
+
const p = error.params as Record<string, any>;
|
|
74
|
+
switch (error.keyword) {
|
|
75
|
+
case "required":
|
|
76
|
+
return { path: joinPath(at, `/${p.missingProperty}`), message: "required" };
|
|
77
|
+
case "additionalProperties":
|
|
78
|
+
return { path: joinPath(at, `/${p.additionalProperty}`), message: "unknown field" };
|
|
79
|
+
// Characters as the validator counts them: code points, not UTF-16 units.
|
|
80
|
+
case "maxLength":
|
|
81
|
+
return { path: at, message: `${[...String(value)].length} characters, max ${p.limit}` };
|
|
82
|
+
case "minLength":
|
|
83
|
+
return { path: at, message: `${[...String(value)].length} characters, min ${p.limit}` };
|
|
84
|
+
case "maximum":
|
|
85
|
+
return { path: at, message: `${show(value)}, max ${p.limit}` };
|
|
86
|
+
case "minimum":
|
|
87
|
+
return { path: at, message: `${show(value)}, min ${p.limit}` };
|
|
88
|
+
case "exclusiveMaximum":
|
|
89
|
+
return { path: at, message: `${show(value)}, must be under ${p.limit}` };
|
|
90
|
+
case "exclusiveMinimum":
|
|
91
|
+
return { path: at, message: `${show(value)}, must be over ${p.limit}` };
|
|
92
|
+
case "maxItems":
|
|
93
|
+
return { path: at, message: `${(value as unknown[]).length} items, max ${p.limit}` };
|
|
94
|
+
case "minItems":
|
|
95
|
+
return { path: at, message: `${(value as unknown[]).length} items, min ${p.limit}` };
|
|
96
|
+
case "enum": {
|
|
97
|
+
const allowed = (p.allowedValues as unknown[]).map(show).join(", ");
|
|
98
|
+
return { path: at, message: `${show(value)} isn't one of ${allowed}` };
|
|
99
|
+
}
|
|
100
|
+
case "const":
|
|
101
|
+
return { path: at, message: `${show(value)} isn't ${show(p.allowedValue)}` };
|
|
102
|
+
case "type":
|
|
103
|
+
return { path: at, message: `expected ${expected(p.type)}, got ${typeName(value)}` };
|
|
104
|
+
case "format":
|
|
105
|
+
return { path: at, message: `${show(value)} isn't a valid ${p.format}` };
|
|
106
|
+
case "pattern":
|
|
107
|
+
return { path: at, message: `doesn't match the pattern ${p.pattern}` };
|
|
108
|
+
case "anyOf":
|
|
109
|
+
case "oneOf":
|
|
110
|
+
return { path: at, message: "doesn't match any allowed form" };
|
|
111
|
+
default:
|
|
112
|
+
return { path: at, message: error.message ?? error.keyword };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const COMBINATORS = new Set(["anyOf", "oneOf", "if", "not", "allOf"]);
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Turn one validation's errors into the few lines that explain it.
|
|
120
|
+
*
|
|
121
|
+
* Every field in the validation schema also accepts a block (the walker checks
|
|
122
|
+
* blocks separately), and fields that blocks can fill are unions, so a plain
|
|
123
|
+
* mistake fails several branches at once. Keep the errors of the branch that
|
|
124
|
+
* got furthest: drop the "it's not a block" branch errors, and drop a branch's
|
|
125
|
+
* type mismatch when another branch reported something deeper at that spot.
|
|
126
|
+
*/
|
|
127
|
+
export function rewriteErrors(
|
|
128
|
+
errors: ErrorObject[] | null | undefined,
|
|
129
|
+
data: unknown,
|
|
130
|
+
base = "",
|
|
131
|
+
): PlainError[] {
|
|
132
|
+
if (!errors?.length) return [];
|
|
133
|
+
const kept = errors.filter((e) => {
|
|
134
|
+
if (e.schemaPath.includes(BLOCK_DEF)) return false;
|
|
135
|
+
if (e.keyword === "required" && (e.params as any).missingProperty === "__resolveType")
|
|
136
|
+
return false;
|
|
137
|
+
return true;
|
|
138
|
+
});
|
|
139
|
+
const specific = kept.filter((e) => !COMBINATORS.has(e.keyword));
|
|
140
|
+
const chosen = specific.filter((e) => {
|
|
141
|
+
if (e.keyword !== "type" && e.keyword !== "const" && e.keyword !== "enum") return true;
|
|
142
|
+
// A union branch's mismatch, when another branch said more about this spot.
|
|
143
|
+
return !specific.some(
|
|
144
|
+
(o) =>
|
|
145
|
+
o !== e &&
|
|
146
|
+
(o.instancePath.startsWith(`${e.instancePath}/`) ||
|
|
147
|
+
(o.instancePath === e.instancePath && e.keyword === "type" && o.keyword !== "type")),
|
|
148
|
+
);
|
|
149
|
+
});
|
|
150
|
+
// A union nobody explained: say so once.
|
|
151
|
+
for (const e of kept) {
|
|
152
|
+
if (e.keyword !== "anyOf" && e.keyword !== "oneOf") continue;
|
|
153
|
+
const explained = chosen.some(
|
|
154
|
+
(o) => o.instancePath === e.instancePath || o.instancePath.startsWith(`${e.instancePath}/`),
|
|
155
|
+
);
|
|
156
|
+
if (!explained) chosen.push(e);
|
|
157
|
+
}
|
|
158
|
+
const seen = new Set<string>();
|
|
159
|
+
const out: PlainError[] = [];
|
|
160
|
+
for (const e of chosen) {
|
|
161
|
+
const line = plain(e, data, base);
|
|
162
|
+
const key = `${line.path}\0${line.message}`;
|
|
163
|
+
if (seen.has(key)) continue;
|
|
164
|
+
seen.add(key);
|
|
165
|
+
out.push(line);
|
|
166
|
+
}
|
|
167
|
+
return out;
|
|
168
|
+
}
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `deco content`: turns the JSON files in `.deco/blocks` into the content
|
|
3
|
+
* module, `.deco/blocks.gen.ts` (spec: content › The content module). It never
|
|
4
|
+
* reads the block map.
|
|
5
|
+
*/
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { computeContentRevision } from "../../protocol/canonical";
|
|
9
|
+
import {
|
|
10
|
+
blockNameFromFile,
|
|
11
|
+
checkBlockName,
|
|
12
|
+
entryHasPath,
|
|
13
|
+
isBlockFileName,
|
|
14
|
+
resolveSpellings,
|
|
15
|
+
type SpellingCandidate,
|
|
16
|
+
} from "../../protocol/keys";
|
|
17
|
+
import { isPlainObject } from "../json";
|
|
18
|
+
import { LEGACY_ALIASES } from "./builtins";
|
|
19
|
+
import { consoleReporter, type Reporter } from "./log";
|
|
20
|
+
import { CliError, type DecoPaths, decoPaths, findDecoRoot } from "./root";
|
|
21
|
+
|
|
22
|
+
export interface ContentDiagnostic {
|
|
23
|
+
/** The file name inside `.deco/blocks`. */
|
|
24
|
+
file: string;
|
|
25
|
+
/** "error" stops `deco content` and fails `deco check`; "warning" doesn't. */
|
|
26
|
+
severity: "error" | "warning";
|
|
27
|
+
message: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface SavedBlocks {
|
|
31
|
+
/**
|
|
32
|
+
* Every saved block, by entry name, as parsed from disk. Both maps have no
|
|
33
|
+
* prototype, so a block named `constructor` or `toString` is just a name:
|
|
34
|
+
* look names up with `Object.hasOwn`, never `in` or a bare index.
|
|
35
|
+
*/
|
|
36
|
+
blocks: Record<string, Record<string, unknown>>;
|
|
37
|
+
/** The file that holds each entry (the winning spelling). */
|
|
38
|
+
files: Record<string, string>;
|
|
39
|
+
diagnostics: ContentDiagnostic[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Read `.deco/blocks` by the file-name rule. A missing folder is an empty
|
|
44
|
+
* map. Files that aren't JSON objects, files whose name the rule rejects
|
|
45
|
+
* (`__proto__.json`, `con.json`, …) and losing spellings of one name are
|
|
46
|
+
* reported as diagnostics instead of entries.
|
|
47
|
+
*/
|
|
48
|
+
export function readSavedBlocks(blocksDir: string): SavedBlocks {
|
|
49
|
+
const diagnostics: ContentDiagnostic[] = [];
|
|
50
|
+
let dirents: fs.Dirent[] = [];
|
|
51
|
+
try {
|
|
52
|
+
dirents = fs.readdirSync(blocksDir, { withFileTypes: true });
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const candidates: (SpellingCandidate & { entry: Record<string, unknown> })[] = [];
|
|
58
|
+
for (const dirent of dirents.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
|
|
59
|
+
if (dirent.isDirectory()) {
|
|
60
|
+
diagnostics.push({
|
|
61
|
+
file: dirent.name,
|
|
62
|
+
severity: "warning",
|
|
63
|
+
message: "subfolders of .deco/blocks aren't read",
|
|
64
|
+
});
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (!isBlockFileName(dirent.name)) continue;
|
|
68
|
+
const [invalid] = checkBlockName(blockNameFromFile(dirent.name));
|
|
69
|
+
if (invalid) {
|
|
70
|
+
diagnostics.push({
|
|
71
|
+
file: dirent.name,
|
|
72
|
+
severity: "error",
|
|
73
|
+
message: `not a valid entry name (${invalid.message}); rename the file`,
|
|
74
|
+
});
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const text = fs.readFileSync(path.join(blocksDir, dirent.name), "utf8");
|
|
78
|
+
let entry: unknown;
|
|
79
|
+
try {
|
|
80
|
+
entry = JSON.parse(text);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
diagnostics.push({
|
|
83
|
+
file: dirent.name,
|
|
84
|
+
severity: "error",
|
|
85
|
+
message: `invalid JSON: ${(error as Error).message}`,
|
|
86
|
+
});
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (!isPlainObject(entry)) {
|
|
90
|
+
diagnostics.push({
|
|
91
|
+
file: dirent.name,
|
|
92
|
+
severity: "error",
|
|
93
|
+
message: "a saved block must be a JSON object",
|
|
94
|
+
});
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
candidates.push({ file: dirent.name, hasPath: entryHasPath(entry), entry });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const blocks: Record<string, Record<string, unknown>> = Object.create(null);
|
|
101
|
+
const files: Record<string, string> = Object.create(null);
|
|
102
|
+
for (const { name, winner, shadowed } of resolveSpellings(candidates).values()) {
|
|
103
|
+
blocks[name] = winner.entry;
|
|
104
|
+
files[name] = winner.file;
|
|
105
|
+
for (const loser of shadowed) {
|
|
106
|
+
diagnostics.push({
|
|
107
|
+
file: loser.file,
|
|
108
|
+
severity: "warning",
|
|
109
|
+
message: `another spelling of "${name}"; ${winner.file} wins`,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return { blocks, files, diagnostics };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const RESERVED = new Set(
|
|
117
|
+
`break case catch class const continue debugger default delete do else enum export extends false
|
|
118
|
+
finally for function if import in instanceof new null return super switch this throw true try
|
|
119
|
+
typeof var void while with yield let static implements interface package private protected public
|
|
120
|
+
await arguments eval undefined NaN Infinity content`.split(/\s+/),
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
function identifierFor(name: string, taken: Set<string>): string {
|
|
124
|
+
let id = name.replace(/[^A-Za-z0-9_$]/g, "_");
|
|
125
|
+
if (id === "" || /^[0-9]/.test(id)) id = `_${id}`;
|
|
126
|
+
if (RESERVED.has(id)) id = `_${id}`;
|
|
127
|
+
let candidate = id;
|
|
128
|
+
for (let i = 2; taken.has(candidate); i++) candidate = `${id}_${i}`;
|
|
129
|
+
taken.add(candidate);
|
|
130
|
+
return candidate;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* File names a bundler can import verbatim. Anything else is inlined, a
|
|
135
|
+
* deliberate departure from "one import per file": every name with a space,
|
|
136
|
+
* `/` or non-ASCII character is stored percent-encoded (`pages-Home%20Page`),
|
|
137
|
+
* and tools disagree on what a `%` in an import specifier means. Vite and
|
|
138
|
+
* esbuild read `./blocks/a%20b.json` as that file and fail on `a%2520b.json`;
|
|
139
|
+
* Node reads it as a URL and loads `a b.json` instead. No spelling of the
|
|
140
|
+
* specifier names the same file everywhere, so those entries are written into
|
|
141
|
+
* the module, and hand edits to them need `deco content` again (`--watch`
|
|
142
|
+
* does it; `deco serve` regenerates after every save).
|
|
143
|
+
*/
|
|
144
|
+
const IMPORTABLE_FILE = /^[A-Za-z0-9_][A-Za-z0-9._-]*\.json$/;
|
|
145
|
+
|
|
146
|
+
/** The files `renderContentModule` inlines instead of importing. */
|
|
147
|
+
function inlinedFiles(saved: SavedBlocks): string[] {
|
|
148
|
+
return Object.keys(saved.blocks)
|
|
149
|
+
.sort()
|
|
150
|
+
.map((name) => saved.files[name])
|
|
151
|
+
.filter((file) => !IMPORTABLE_FILE.test(file));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The `.deco` folder's identity for `createCMS` (one instance per folder, so
|
|
156
|
+
* a hot-reloaded module keeps its instance): its path from the repository
|
|
157
|
+
* root, or `.deco` outside a repository. Relative, so builds are reproducible.
|
|
158
|
+
*/
|
|
159
|
+
export function contentRoot(deco: string): string {
|
|
160
|
+
for (let dir = path.dirname(deco); ; dir = path.dirname(dir)) {
|
|
161
|
+
if (fs.existsSync(path.join(dir, ".git"))) {
|
|
162
|
+
return path.relative(dir, deco).split(path.sep).join("/");
|
|
163
|
+
}
|
|
164
|
+
if (path.dirname(dir) === dir) return ".deco";
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The source of `.deco/blocks.gen.ts` for a set of saved blocks. */
|
|
169
|
+
export async function renderContentModule(saved: SavedBlocks, root = ".deco"): Promise<string> {
|
|
170
|
+
const names = Object.keys(saved.blocks).sort();
|
|
171
|
+
const revision = await computeContentRevision(saved.blocks);
|
|
172
|
+
const taken = new Set<string>();
|
|
173
|
+
const imports: string[] = [];
|
|
174
|
+
const entries: string[] = [];
|
|
175
|
+
for (const name of names) {
|
|
176
|
+
const file = saved.files[name];
|
|
177
|
+
if (IMPORTABLE_FILE.test(file)) {
|
|
178
|
+
const id = identifierFor(name, taken);
|
|
179
|
+
imports.push(`import ${id} from "./blocks/${file}" with { type: "json" };`);
|
|
180
|
+
entries.push(` ${JSON.stringify(name)}: ${id},`);
|
|
181
|
+
} else {
|
|
182
|
+
entries.push(
|
|
183
|
+
` // inlined: ${JSON.stringify(file)} isn't a portable import path\n` +
|
|
184
|
+
` ${JSON.stringify(name)}: ${JSON.stringify(saved.blocks[name])},`,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const aliases = Object.entries(LEGACY_ALIASES).map(
|
|
189
|
+
([alias, target]) => ` ${JSON.stringify(alias)}: ${JSON.stringify(target)},`,
|
|
190
|
+
);
|
|
191
|
+
return [
|
|
192
|
+
"// Generated by deco content; don't edit.",
|
|
193
|
+
...imports,
|
|
194
|
+
"",
|
|
195
|
+
"const content: {",
|
|
196
|
+
" revision: string;",
|
|
197
|
+
" blocks: Record<string, unknown>;",
|
|
198
|
+
" aliases: Record<string, string>;",
|
|
199
|
+
" root: string;",
|
|
200
|
+
"} = {",
|
|
201
|
+
` revision: ${JSON.stringify(revision)},`,
|
|
202
|
+
" blocks: {",
|
|
203
|
+
...entries,
|
|
204
|
+
" },",
|
|
205
|
+
" aliases: {",
|
|
206
|
+
...aliases,
|
|
207
|
+
" },",
|
|
208
|
+
` root: ${JSON.stringify(root)},`,
|
|
209
|
+
"};",
|
|
210
|
+
"",
|
|
211
|
+
"export default content;",
|
|
212
|
+
"",
|
|
213
|
+
].join("\n");
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export interface ContentResult {
|
|
217
|
+
root: string;
|
|
218
|
+
file: string;
|
|
219
|
+
revision: string;
|
|
220
|
+
count: number;
|
|
221
|
+
/** False when the file already had this content. */
|
|
222
|
+
changed: boolean;
|
|
223
|
+
/** Files written into the module instead of imported (see `inlinedFiles`). */
|
|
224
|
+
inlined: string[];
|
|
225
|
+
diagnostics: ContentDiagnostic[];
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Write a file only when its content changed, so watchers and HMR stay quiet. */
|
|
229
|
+
export function writeIfChanged(file: string, content: string): boolean {
|
|
230
|
+
try {
|
|
231
|
+
if (fs.readFileSync(file, "utf8") === content) return false;
|
|
232
|
+
} catch {
|
|
233
|
+
// missing: write it
|
|
234
|
+
}
|
|
235
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
236
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
237
|
+
fs.writeFileSync(tmp, content);
|
|
238
|
+
fs.renameSync(tmp, file);
|
|
239
|
+
return true;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Generate `.deco/blocks.gen.ts` for a root. Throws on unreadable content. */
|
|
243
|
+
export async function writeContent(paths: DecoPaths): Promise<ContentResult> {
|
|
244
|
+
const saved = readSavedBlocks(paths.blocks);
|
|
245
|
+
const errors = saved.diagnostics.filter((d) => d.severity === "error");
|
|
246
|
+
if (errors.length > 0) {
|
|
247
|
+
throw new CliError(errors.map((d) => `.deco/blocks/${d.file}: ${d.message}`).join("\n"));
|
|
248
|
+
}
|
|
249
|
+
const source = await renderContentModule(saved, contentRoot(paths.deco));
|
|
250
|
+
const changed = writeIfChanged(paths.content, source);
|
|
251
|
+
return {
|
|
252
|
+
root: paths.root,
|
|
253
|
+
file: paths.content,
|
|
254
|
+
revision: await computeContentRevision(saved.blocks),
|
|
255
|
+
count: Object.keys(saved.blocks).length,
|
|
256
|
+
changed,
|
|
257
|
+
inlined: inlinedFiles(saved),
|
|
258
|
+
diagnostics: saved.diagnostics,
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export interface ContentOptions {
|
|
263
|
+
root?: string;
|
|
264
|
+
cwd?: string;
|
|
265
|
+
reporter?: Reporter;
|
|
266
|
+
/** Set by `--watch`: inlined files are kept up to date, so no hint about them. */
|
|
267
|
+
watching?: boolean;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** `deco content`, once. Returns the exit code. */
|
|
271
|
+
export async function content(options: ContentOptions = {}): Promise<number> {
|
|
272
|
+
const reporter = options.reporter ?? consoleReporter;
|
|
273
|
+
const paths = decoPaths(findDecoRoot(options));
|
|
274
|
+
const result = await writeContent(paths);
|
|
275
|
+
for (const d of result.diagnostics) reporter.warn(`.deco/blocks/${d.file}: ${d.message}`);
|
|
276
|
+
reporter.info(
|
|
277
|
+
`${result.changed ? "wrote" : "unchanged"} .deco/blocks.gen.ts (${result.count} blocks, revision ${result.revision.slice(0, 12)})`,
|
|
278
|
+
);
|
|
279
|
+
const inlined = result.inlined.length;
|
|
280
|
+
if (inlined > 0 && !options.watching) {
|
|
281
|
+
reporter.info(
|
|
282
|
+
`${inlined} file${inlined === 1 ? "" : "s"} with % in the name ${inlined === 1 ? "is" : "are"} inlined, not imported: ` +
|
|
283
|
+
"after editing one by hand, run deco content again (or keep deco content --watch running)",
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
return 0;
|
|
287
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@decocms/blocks/cli`: the `deco` commands, importable (spec: internals ›
|
|
3
|
+
* How the CLI ships). Apps never import this subpath and the runtime never
|
|
4
|
+
* does either, so neither the CLI nor the TypeScript compiler it loads ever
|
|
5
|
+
* reaches an app bundle.
|
|
6
|
+
*
|
|
7
|
+
* The four commands and their options, plus what the one-time migration
|
|
8
|
+
* (`@decocms/blocks-migrate`) reads: the built-in block names, the alias
|
|
9
|
+
* table and the saved-blocks reader.
|
|
10
|
+
*/
|
|
11
|
+
export { BUILT_IN_BLOCKS, LEGACY_ALIASES } from "./builtins";
|
|
12
|
+
export { type CheckOptions, check } from "./check/index";
|
|
13
|
+
export { type ContentOptions, content, readSavedBlocks, type SavedBlocks } from "./content";
|
|
14
|
+
export { type Reporter, silentReporter } from "./log";
|
|
15
|
+
export { runCli } from "./run";
|
|
16
|
+
export { type SchemaOptions, schema } from "./schema/index";
|
|
17
|
+
export { type ServeOptions, serve } from "./serve/server";
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Where commands print. Tests pass a recorder; the bin passes the console. */
|
|
2
|
+
export interface Reporter {
|
|
3
|
+
info(message: string): void;
|
|
4
|
+
warn(message: string): void;
|
|
5
|
+
error(message: string): void;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export const consoleReporter: Reporter = {
|
|
9
|
+
info: (message) => console.log(message),
|
|
10
|
+
warn: (message) => console.warn(message),
|
|
11
|
+
error: (message) => console.error(message),
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export const silentReporter: Reporter = {
|
|
15
|
+
info: () => {},
|
|
16
|
+
warn: () => {},
|
|
17
|
+
error: () => {},
|
|
18
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** The `deco` bin's entry: run the command line, then exit with its code. */
|
|
2
|
+
import { runCli } from "./run";
|
|
3
|
+
|
|
4
|
+
runCli(process.argv.slice(2)).then(
|
|
5
|
+
(code) => {
|
|
6
|
+
process.exitCode = code;
|
|
7
|
+
},
|
|
8
|
+
(error) => {
|
|
9
|
+
console.error(error instanceof Error ? (error.stack ?? error.message) : error);
|
|
10
|
+
process.exitCode = 1;
|
|
11
|
+
},
|
|
12
|
+
);
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
/** An error the CLI prints as a single line, without a stack trace. */
|
|
5
|
+
export class CliError extends Error {
|
|
6
|
+
override name = "CliError";
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function isDirectory(p: string): boolean {
|
|
10
|
+
try {
|
|
11
|
+
return fs.statSync(p).isDirectory();
|
|
12
|
+
} catch {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The folder that contains `.deco/` (spec: cli › Finding the .deco folder).
|
|
19
|
+
*
|
|
20
|
+
* With `--root`, that folder, relative to `cwd`; it must contain `.deco/`.
|
|
21
|
+
* Without it, walk up from `cwd` to the first folder with a `.deco/`.
|
|
22
|
+
*/
|
|
23
|
+
export function findDecoRoot(options: { root?: string; cwd?: string } = {}): string {
|
|
24
|
+
const cwd = path.resolve(options.cwd ?? process.cwd());
|
|
25
|
+
if (options.root !== undefined) {
|
|
26
|
+
const root = path.resolve(cwd, options.root);
|
|
27
|
+
if (!isDirectory(path.join(root, ".deco"))) {
|
|
28
|
+
throw new CliError(`no .deco/ in ${root}; pass the folder that contains .deco/ as --root`);
|
|
29
|
+
}
|
|
30
|
+
return root;
|
|
31
|
+
}
|
|
32
|
+
let dir = cwd;
|
|
33
|
+
for (;;) {
|
|
34
|
+
if (isDirectory(path.join(dir, ".deco"))) return dir;
|
|
35
|
+
const parent = path.dirname(dir);
|
|
36
|
+
if (parent === dir) break;
|
|
37
|
+
dir = parent;
|
|
38
|
+
}
|
|
39
|
+
throw new CliError(`no .deco/ found from ${cwd}; run inside your app or pass --root`);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The paths of the files every command reads or writes, inside one root. */
|
|
43
|
+
export function decoPaths(root: string) {
|
|
44
|
+
const deco = path.join(root, ".deco");
|
|
45
|
+
return {
|
|
46
|
+
root,
|
|
47
|
+
deco,
|
|
48
|
+
blocks: path.join(deco, "blocks"),
|
|
49
|
+
schema: path.join(deco, "schema.gen.json"),
|
|
50
|
+
legacySchema: path.join(deco, "meta.gen.json"),
|
|
51
|
+
content: path.join(deco, "blocks.gen.ts"),
|
|
52
|
+
blockMapCandidates: [path.join(deco, "index.ts"), path.join(deco, "index.tsx")],
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export type DecoPaths = ReturnType<typeof decoPaths>;
|
|
57
|
+
|
|
58
|
+
/** This package's version, for `deco-meta@1` and `describe`. */
|
|
59
|
+
export function packageVersion(): string {
|
|
60
|
+
try {
|
|
61
|
+
const manifest = new URL("../../../package.json", import.meta.url);
|
|
62
|
+
return JSON.parse(fs.readFileSync(manifest, "utf8")).version ?? "0.0.0";
|
|
63
|
+
} catch {
|
|
64
|
+
return "0.0.0";
|
|
65
|
+
}
|
|
66
|
+
}
|