@decocms/blocks 8.0.0 → 8.1.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -82
  3. package/src/index.ts +35 -8
  4. package/src/protocol/assets.ts +124 -0
  5. package/src/protocol/canonical.ts +7 -0
  6. package/src/protocol/ciphertext.ts +6 -0
  7. package/src/protocol/client.ts +170 -0
  8. package/src/protocol/conformance/cases/assets.ts +81 -0
  9. package/src/protocol/conformance/cases/guards.ts +314 -0
  10. package/src/protocol/conformance/cases/reads.ts +168 -0
  11. package/src/protocol/conformance/cases/types.ts +9 -0
  12. package/src/protocol/conformance/cases/wire.ts +138 -0
  13. package/src/protocol/conformance/cases/writes.ts +345 -0
  14. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  15. package/src/protocol/conformance/context.ts +222 -0
  16. package/src/protocol/conformance/index.ts +140 -0
  17. package/src/protocol/errors.ts +142 -0
  18. package/src/protocol/index.ts +39 -0
  19. package/src/protocol/keys.ts +279 -0
  20. package/src/protocol/params.ts +67 -0
  21. package/src/protocol/secrets.ts +231 -0
  22. package/src/protocol/server/assets.ts +119 -0
  23. package/src/protocol/server/auth.ts +49 -0
  24. package/src/protocol/server/bodyCache.ts +84 -0
  25. package/src/protocol/server/content.ts +175 -0
  26. package/src/protocol/server/core.ts +112 -0
  27. package/src/protocol/server/handler.ts +102 -0
  28. package/src/protocol/server/http.ts +139 -0
  29. package/src/protocol/server/index.ts +11 -0
  30. package/src/protocol/server/methods/apply.ts +341 -0
  31. package/src/protocol/server/methods/read.ts +156 -0
  32. package/src/protocol/server/rpc.ts +136 -0
  33. package/src/protocol/storage/fs/hash.ts +21 -0
  34. package/src/protocol/storage/fs/index.ts +338 -0
  35. package/src/protocol/storage/fs/lock.ts +68 -0
  36. package/src/protocol/storage/fs/transaction.ts +183 -0
  37. package/src/protocol/storage/fs/unsupported.ts +15 -0
  38. package/src/protocol/storage/memory.ts +238 -0
  39. package/src/protocol/storage.ts +182 -0
  40. package/src/protocol/types.ts +172 -0
  41. package/src/v8/analytics.ts +50 -0
  42. package/src/v8/background.ts +107 -0
  43. package/src/v8/builtins/data.ts +23 -0
  44. package/src/v8/builtins/index.ts +26 -0
  45. package/src/v8/builtins/lazy.ts +23 -0
  46. package/src/v8/builtins/legacy.ts +65 -0
  47. package/src/v8/builtins/matchers.ts +31 -0
  48. package/src/v8/builtins/multivariate.ts +25 -0
  49. package/src/v8/builtins/secret.ts +82 -0
  50. package/src/v8/canonical.ts +117 -0
  51. package/src/v8/ciphertext.ts +158 -0
  52. package/src/v8/cli/builtins.ts +20 -0
  53. package/src/v8/cli/check/index.ts +774 -0
  54. package/src/v8/cli/check/messages.ts +168 -0
  55. package/src/v8/cli/content.ts +287 -0
  56. package/src/v8/cli/index.ts +17 -0
  57. package/src/v8/cli/log.ts +18 -0
  58. package/src/v8/cli/main.ts +12 -0
  59. package/src/v8/cli/root.ts +66 -0
  60. package/src/v8/cli/run.ts +236 -0
  61. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  62. package/src/v8/cli/schema/generate.ts +507 -0
  63. package/src/v8/cli/schema/index.ts +63 -0
  64. package/src/v8/cli/schema/tsProgram.ts +497 -0
  65. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  66. package/src/v8/cli/serve/server.ts +303 -0
  67. package/src/v8/cli/watch.ts +86 -0
  68. package/src/v8/client.ts +147 -0
  69. package/src/v8/cms.ts +237 -0
  70. package/src/v8/content.ts +195 -0
  71. package/src/v8/draft.ts +136 -0
  72. package/src/v8/errors.ts +59 -0
  73. package/src/v8/fetch.ts +133 -0
  74. package/src/v8/identity.ts +65 -0
  75. package/src/v8/index.ts +39 -0
  76. package/src/v8/json.ts +74 -0
  77. package/src/v8/matchRoute.ts +204 -0
  78. package/src/v8/remoteLoader.ts +282 -0
  79. package/src/v8/resolver.ts +278 -0
  80. package/src/v8/secrets.ts +17 -0
  81. package/src/v8/telemetry.ts +533 -0
  82. package/src/v8/types.ts +240 -0
  83. package/src/cms/applySectionConventions.ts +0 -124
  84. package/src/cms/blockSource.test.ts +0 -76
  85. package/src/cms/blockSource.ts +0 -191
  86. package/src/cms/client.browserBundle.test.ts +0 -44
  87. package/src/cms/client.ts +0 -80
  88. package/src/cms/draftSource.test.ts +0 -343
  89. package/src/cms/draftSource.ts +0 -362
  90. package/src/cms/index.ts +0 -151
  91. package/src/cms/layoutCacheRace.test.ts +0 -181
  92. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  93. package/src/cms/loadDecofileDirectory.ts +0 -89
  94. package/src/cms/loader.test.ts +0 -200
  95. package/src/cms/loader.ts +0 -304
  96. package/src/cms/registry.test.ts +0 -110
  97. package/src/cms/registry.ts +0 -242
  98. package/src/cms/resolve.test.ts +0 -980
  99. package/src/cms/resolve.ts +0 -2282
  100. package/src/cms/schema.test.ts +0 -356
  101. package/src/cms/schema.ts +0 -1215
  102. package/src/cms/sectionLoaderContext.test.ts +0 -111
  103. package/src/cms/sectionLoaderContext.ts +0 -113
  104. package/src/cms/sectionLoaders.test.ts +0 -533
  105. package/src/cms/sectionLoaders.ts +0 -636
  106. package/src/cms/sectionMixins.test.ts +0 -167
  107. package/src/cms/sectionMixins.ts +0 -153
  108. package/src/cms/stickyFlags.test.ts +0 -117
  109. package/src/flags/audience.ts +0 -56
  110. package/src/flags/everyone.ts +0 -29
  111. package/src/flags/flag.ts +0 -15
  112. package/src/flags/flags.test.ts +0 -148
  113. package/src/flags/multivariate/image.ts +0 -11
  114. package/src/flags/multivariate/message.ts +0 -11
  115. package/src/flags/multivariate/page.ts +0 -16
  116. package/src/flags/multivariate/section.ts +0 -16
  117. package/src/flags/multivariate.ts +0 -1
  118. package/src/flags/types.ts +0 -59
  119. package/src/flags/utils/multivariate.ts +0 -20
  120. package/src/hooks/Image.test.ts +0 -100
  121. package/src/hooks/Image.tsx +0 -250
  122. package/src/hooks/JsonLd.tsx +0 -353
  123. package/src/hooks/LazySection.tsx +0 -121
  124. package/src/hooks/LiveControls.tsx +0 -122
  125. package/src/hooks/Picture.tsx +0 -127
  126. package/src/hooks/RenderSection.test.tsx +0 -81
  127. package/src/hooks/RenderSection.tsx +0 -91
  128. package/src/hooks/SectionErrorFallback.tsx +0 -97
  129. package/src/hooks/index.ts +0 -30
  130. package/src/matchers/builtins.test.ts +0 -318
  131. package/src/matchers/builtins.ts +0 -459
  132. package/src/matchers/countryNames.ts +0 -104
  133. package/src/matchers/override.test.ts +0 -205
  134. package/src/matchers/override.ts +0 -136
  135. package/src/matchers/posthog.ts +0 -154
  136. package/src/middleware/decoState.ts +0 -55
  137. package/src/middleware/healthMetrics.ts +0 -133
  138. package/src/middleware/hydrationContext.test.ts +0 -61
  139. package/src/middleware/hydrationContext.ts +0 -79
  140. package/src/middleware/index.ts +0 -88
  141. package/src/middleware/liveness.ts +0 -21
  142. package/src/middleware/observability.test.ts +0 -242
  143. package/src/middleware/observability.ts +0 -643
  144. package/src/middleware/validateSection.test.ts +0 -147
  145. package/src/middleware/validateSection.ts +0 -100
  146. package/src/sdk/abTesting.test.ts +0 -326
  147. package/src/sdk/abTesting.ts +0 -499
  148. package/src/sdk/analytics.ts +0 -77
  149. package/src/sdk/cacheHeaders.test.ts +0 -115
  150. package/src/sdk/cacheHeaders.ts +0 -433
  151. package/src/sdk/cachedLoader.test.ts +0 -122
  152. package/src/sdk/cachedLoader.ts +0 -503
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/clx.ts +0 -5
  155. package/src/sdk/cn.test.ts +0 -34
  156. package/src/sdk/cn.ts +0 -28
  157. package/src/sdk/composite.test.ts +0 -121
  158. package/src/sdk/composite.ts +0 -114
  159. package/src/sdk/cookie.test.ts +0 -108
  160. package/src/sdk/cookie.ts +0 -129
  161. package/src/sdk/crypto.ts +0 -185
  162. package/src/sdk/csp.ts +0 -59
  163. package/src/sdk/detectDevice.ts +0 -45
  164. package/src/sdk/djb2.ts +0 -20
  165. package/src/sdk/encoding.test.ts +0 -71
  166. package/src/sdk/encoding.ts +0 -47
  167. package/src/sdk/env.test.ts +0 -33
  168. package/src/sdk/env.ts +0 -54
  169. package/src/sdk/flags.test.ts +0 -91
  170. package/src/sdk/flags.ts +0 -108
  171. package/src/sdk/http.test.ts +0 -71
  172. package/src/sdk/http.ts +0 -124
  173. package/src/sdk/index.ts +0 -90
  174. package/src/sdk/inflightTimeout.test.ts +0 -35
  175. package/src/sdk/inflightTimeout.ts +0 -53
  176. package/src/sdk/instrumentedFetch.test.ts +0 -559
  177. package/src/sdk/instrumentedFetch.ts +0 -339
  178. package/src/sdk/invoke.test.ts +0 -115
  179. package/src/sdk/invoke.ts +0 -298
  180. package/src/sdk/logger.test.ts +0 -432
  181. package/src/sdk/logger.ts +0 -304
  182. package/src/sdk/mergeCacheControl.ts +0 -150
  183. package/src/sdk/normalizeUrls.ts +0 -91
  184. package/src/sdk/observability.ts +0 -109
  185. package/src/sdk/otel.test.ts +0 -526
  186. package/src/sdk/otel.ts +0 -1012
  187. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  188. package/src/sdk/otelAdapters.test.ts +0 -89
  189. package/src/sdk/otelAdapters.ts +0 -144
  190. package/src/sdk/otelHttpLog.test.ts +0 -457
  191. package/src/sdk/otelHttpLog.ts +0 -419
  192. package/src/sdk/otelHttpMeter.test.ts +0 -292
  193. package/src/sdk/otelHttpMeter.ts +0 -506
  194. package/src/sdk/otelHttpTracer.test.ts +0 -474
  195. package/src/sdk/otelHttpTracer.ts +0 -543
  196. package/src/sdk/redirects.ts +0 -228
  197. package/src/sdk/requestContext.ts +0 -281
  198. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  199. package/src/sdk/requestContextStorage.browser.ts +0 -43
  200. package/src/sdk/requestContextStorage.ts +0 -35
  201. package/src/sdk/retry.ts +0 -45
  202. package/src/sdk/serverTimings.ts +0 -68
  203. package/src/sdk/signal.ts +0 -42
  204. package/src/sdk/sitemap.ts +0 -160
  205. package/src/sdk/urlRedaction.test.ts +0 -73
  206. package/src/sdk/urlRedaction.ts +0 -82
  207. package/src/sdk/urlUtils.ts +0 -134
  208. package/src/sdk/useDevice.test.ts +0 -130
  209. package/src/sdk/useDevice.ts +0 -89
  210. package/src/sdk/useDeviceContext.tsx +0 -108
  211. package/src/sdk/useId.ts +0 -7
  212. package/src/sdk/useScript.test.ts +0 -128
  213. package/src/sdk/useScript.ts +0 -210
  214. package/src/sdk/useSuggestions.test.ts +0 -230
  215. package/src/sdk/useSuggestions.ts +0 -188
  216. package/src/sdk/wrapCaughtErrors.ts +0 -107
  217. package/src/setup.ts +0 -120
  218. package/src/types/index.ts +0 -53
  219. package/src/types/widgets.ts +0 -14
  220. package/tsconfig.json +0 -7
@@ -0,0 +1,236 @@
1
+ /**
2
+ * The `deco` command line: `deco <schema|content|check|serve> [flags]`
3
+ * (spec: cli). Parses flags, runs one command and returns its exit code.
4
+ */
5
+ import { check } from "./check/index";
6
+ import { content, writeContent } from "./content";
7
+ import { consoleReporter, type Reporter } from "./log";
8
+ import { CliError, decoPaths, findDecoRoot } from "./root";
9
+ import { reportSchema, schema, writeSchema } from "./schema/index";
10
+ import { serve, startServer } from "./serve/server";
11
+ import { watchFiles, watchTree } from "./watch";
12
+
13
+ type FlagKind = "string" | "boolean" | "list";
14
+
15
+ const COMMANDS: Record<string, { usage: string; flags: Record<string, FlagKind> }> = {
16
+ schema: {
17
+ usage: "deco schema [--root <dir>] [--watch]",
18
+ flags: { root: "string", watch: "boolean" },
19
+ },
20
+ content: {
21
+ usage: "deco content [--root <dir>] [--watch]",
22
+ flags: { root: "string", watch: "boolean" },
23
+ },
24
+ check: { usage: "deco check [--root <dir>]", flags: { root: "string" } },
25
+ serve: {
26
+ usage:
27
+ "deco serve [--root <dir>] [--port <n>] [--host <addr>] [--preview <host:port|url>] [--token <t>] [--allow-origin <origin>]… [--assets <dir>] [--read-only]",
28
+ flags: {
29
+ root: "string",
30
+ port: "string",
31
+ host: "string",
32
+ preview: "string",
33
+ token: "string",
34
+ "allow-origin": "list",
35
+ assets: "string",
36
+ "read-only": "boolean",
37
+ },
38
+ },
39
+ };
40
+
41
+ export const USAGE = `Usage: deco <command> [flags]
42
+
43
+ Commands:
44
+ schema turn the types in .deco/index.ts into .deco/schema.gen.json
45
+ content turn .deco/blocks into the content module, .deco/blocks.gen.ts
46
+ check check that every saved block fits the schema (writes nothing)
47
+ serve serve .deco to the site editor on this machine
48
+
49
+ ${Object.values(COMMANDS)
50
+ .map((c) => ` ${c.usage}`)
51
+ .join("\n")}
52
+
53
+ Every command finds .deco/ by walking up from the current folder, or takes --root.`;
54
+
55
+ export type ParsedFlags = Record<string, string | boolean | string[]>;
56
+
57
+ export function parseFlags(command: string, args: string[]): ParsedFlags {
58
+ const spec = COMMANDS[command].flags;
59
+ const flags: ParsedFlags = {};
60
+ for (let i = 0; i < args.length; i++) {
61
+ const arg = args[i];
62
+ if (!arg.startsWith("--"))
63
+ throw new CliError(`unexpected argument "${arg}"\n${COMMANDS[command].usage}`);
64
+ const eq = arg.indexOf("=");
65
+ const name = arg.slice(2, eq === -1 ? undefined : eq);
66
+ const kind = Object.hasOwn(spec, name) ? spec[name] : undefined;
67
+ if (!kind) throw new CliError(`unknown flag --${name}\n${COMMANDS[command].usage}`);
68
+ if (kind === "boolean") {
69
+ if (eq !== -1) throw new CliError(`--${name} takes no value`);
70
+ flags[name] = true;
71
+ continue;
72
+ }
73
+ let value: string | undefined;
74
+ if (eq !== -1) value = arg.slice(eq + 1);
75
+ else {
76
+ value = args[i + 1];
77
+ if (value === undefined || value.startsWith("--"))
78
+ throw new CliError(`--${name} needs a value`);
79
+ i++;
80
+ }
81
+ if (kind === "list") flags[name] = [...((flags[name] as string[]) ?? []), value];
82
+ else flags[name] = value;
83
+ }
84
+ return flags;
85
+ }
86
+
87
+ export interface RunOptions {
88
+ cwd?: string;
89
+ reporter?: Reporter;
90
+ /** Resolves when a `--watch` or `serve` run should stop (tests); defaults to SIGINT/SIGTERM. */
91
+ until?: Promise<void>;
92
+ }
93
+
94
+ function stopSignal(): Promise<void> {
95
+ return new Promise((resolve) => {
96
+ process.once("SIGINT", () => resolve());
97
+ process.once("SIGTERM", () => resolve());
98
+ });
99
+ }
100
+
101
+ async function watchLoop(
102
+ dir: string,
103
+ filter: (rel: string) => boolean,
104
+ rerun: () => Promise<void> | void,
105
+ until: Promise<void>,
106
+ reporter: Reporter,
107
+ ) {
108
+ let running = Promise.resolve();
109
+ const watcher = watchTree(dir, filter, () => {
110
+ running = running.then(async () => {
111
+ try {
112
+ await rerun();
113
+ } catch (error) {
114
+ reporter.error((error as Error).message);
115
+ }
116
+ });
117
+ });
118
+ reporter.info("watching for changes (ctrl-c to stop)");
119
+ await until;
120
+ watcher.close();
121
+ await running;
122
+ }
123
+
124
+ /**
125
+ * What `deco publish` prints. It isn't one of the four commands and isn't in
126
+ * the usage: publishing is committing (/next/design-decisions).
127
+ */
128
+ const PUBLISH_SIGNPOST = `There is no publish command: Git is the source of truth for content, so publishing is committing.
129
+ Commit the changes in .deco/blocks (and push them). A deploy ships the commit; with the hosted
130
+ Deco CMS, a commit becomes a release without a deploy.`;
131
+
132
+ /** Run one `deco` invocation; returns the exit code. */
133
+ export async function runCli(argv: string[], options: RunOptions = {}): Promise<number> {
134
+ const reporter = options.reporter ?? consoleReporter;
135
+ const [command, ...rest] = argv;
136
+ if (!command || command === "help" || command === "--help" || command === "-h") {
137
+ reporter.info(USAGE);
138
+ return command ? 0 : 1;
139
+ }
140
+ if (command === "publish") {
141
+ // Not a command: a signpost for agents that look for one (design-decisions).
142
+ reporter.error(PUBLISH_SIGNPOST);
143
+ return 1;
144
+ }
145
+ if (!Object.hasOwn(COMMANDS, command)) {
146
+ reporter.error(`unknown command "${command}"\n\n${USAGE}`);
147
+ return 1;
148
+ }
149
+ try {
150
+ const flags = parseFlags(command, rest);
151
+ const root = flags.root as string | undefined;
152
+ const base = { root, cwd: options.cwd, reporter };
153
+ switch (command) {
154
+ case "schema": {
155
+ if (!flags.watch) return await schema(base);
156
+ const paths = decoPaths(findDecoRoot(base));
157
+ // Monorepo packages the block map imports live outside the root:
158
+ // watch the files the last run read there, too.
159
+ const external = watchFiles(() => void once());
160
+ let running = Promise.resolve();
161
+ const run = async () => {
162
+ const result = await writeSchema(paths);
163
+ external.update(result.externalSources);
164
+ reportSchema(result, reporter);
165
+ };
166
+ const once = () => {
167
+ running = running.then(run).catch((error) => reporter.error((error as Error).message));
168
+ return running;
169
+ };
170
+ await run();
171
+ // Regenerate when any source file changes; the schema only depends on code.
172
+ await watchLoop(
173
+ paths.root,
174
+ (rel) =>
175
+ /\.(ts|tsx|mts|cts)$/.test(rel) &&
176
+ !rel
177
+ .split("/")
178
+ .some((s) => s === "node_modules" || s.startsWith(".git") || s === "dist") &&
179
+ !rel.endsWith(".gen.ts"),
180
+ once,
181
+ options.until ?? stopSignal(),
182
+ reporter,
183
+ );
184
+ external.close();
185
+ await running;
186
+ return 0;
187
+ }
188
+ case "content": {
189
+ if (!flags.watch) return await content(base);
190
+ const paths = decoPaths(findDecoRoot(base));
191
+ const once = async () => {
192
+ const result = await writeContent(paths);
193
+ if (result.changed) reporter.info(`wrote .deco/blocks.gen.ts (${result.count} blocks)`);
194
+ };
195
+ await content({ ...base, watching: true });
196
+ await watchLoop(
197
+ paths.blocks,
198
+ (rel) => rel.endsWith(".json"),
199
+ once,
200
+ options.until ?? stopSignal(),
201
+ reporter,
202
+ );
203
+ return 0;
204
+ }
205
+ case "check":
206
+ return check(base);
207
+ case "serve": {
208
+ const port = flags.port === undefined ? undefined : Number(flags.port);
209
+ if (port !== undefined && !Number.isInteger(port))
210
+ throw new CliError(`--port must be a number, got ${flags.port}`);
211
+ const serveOptions = {
212
+ ...base,
213
+ port,
214
+ host: flags.host as string | undefined,
215
+ preview: flags.preview as string | undefined,
216
+ token: flags.token as string | undefined,
217
+ allowOrigins: flags["allow-origin"] as string[] | undefined,
218
+ assets: flags.assets as string | undefined,
219
+ readOnly: Boolean(flags["read-only"]),
220
+ };
221
+ if (!options.until) return await serve(serveOptions);
222
+ const running = await startServer(serveOptions);
223
+ await options.until;
224
+ await running.close();
225
+ return 0;
226
+ }
227
+ }
228
+ return 1;
229
+ } catch (error) {
230
+ if (error instanceof CliError) {
231
+ reporter.error(error.message);
232
+ return 1;
233
+ }
234
+ throw error;
235
+ }
236
+ }
@@ -0,0 +1,236 @@
1
+ /**
2
+ * The forms of the ten built-in blocks (spec: built-in-blocks, and the types
3
+ * in api-reference › Types). They're always in the schema, unless the block
4
+ * map declares the same key, which replaces the built-in.
5
+ */
6
+ import { lazySchema, resolvableRef, sectionRef } from "./typeToSchema";
7
+
8
+ export type ManifestGroup = "sections" | "matchers" | "loaders" | "pages" | "redirects" | "content";
9
+
10
+ export const BUILT_IN_GROUPS: Record<string, ManifestGroup> = {
11
+ lazy: "loaders",
12
+ multivariate: "loaders",
13
+ always: "matchers",
14
+ never: "matchers",
15
+ date: "matchers",
16
+ page: "pages",
17
+ redirect: "redirects",
18
+ telemetry: "content",
19
+ analytics: "content",
20
+ secret: "loaders",
21
+ };
22
+
23
+ const BUILT_IN_DOCS: Record<string, { title: string; description: string; icon?: string }> = {
24
+ lazy: { title: "Lazy", description: "Resolves its value only when the function calls it" },
25
+ multivariate: {
26
+ title: "Variants",
27
+ description: "Picks the first variant whose rule is true",
28
+ icon: "arrow-split",
29
+ },
30
+ always: { title: "Always", description: "Always true: the fallback variant", icon: "eye" },
31
+ never: { title: "Never", description: "Always false: hides a block", icon: "eye-off" },
32
+ date: {
33
+ title: "Date and time",
34
+ description: "True from start until end",
35
+ icon: "calendar-event",
36
+ },
37
+ page: { title: "Page", description: "A page at a URL" },
38
+ redirect: { title: "Redirect", description: "Sends one URL to another" },
39
+ telemetry: { title: "Telemetry", description: "Telemetry switches and sample rates" },
40
+ analytics: { title: "Analytics", description: "Page view analytics settings" },
41
+ secret: { title: "Secret", description: "An encrypted value, decrypted on the server" },
42
+ };
43
+
44
+ function resolveTypeProperty(key: string) {
45
+ return { type: "string", enum: [key], default: key };
46
+ }
47
+
48
+ /** A flat block definition: `__resolveType` plus the props, as v7 wrote loaders. */
49
+ export function flatDefinition(
50
+ key: string,
51
+ props: { properties?: Record<string, any>; required?: string[]; [k: string]: any },
52
+ extra: Record<string, any> = {},
53
+ ): any {
54
+ // Only the fields, as v7 wrote loaders: a props type's own annotations
55
+ // (nullable, hide) describe a field, not the block.
56
+ const { properties = {}, required = [] } = props;
57
+ return {
58
+ title: key,
59
+ ...extra,
60
+ type: "object",
61
+ required: ["__resolveType", ...required.filter((r) => r !== "__resolveType")],
62
+ properties: { __resolveType: resolveTypeProperty(key), ...properties },
63
+ };
64
+ }
65
+
66
+ export interface BuiltInContext {
67
+ /** `$ref`s of the blocks whose return type fits `Seo`, for the page's `seo` field. */
68
+ seoRefs: { $ref: string }[];
69
+ }
70
+
71
+ /** The rule field of a variant: a block whose function returns a boolean. */
72
+ function ruleSchema() {
73
+ return { title: "Rule", $ref: "#/root/matchers" };
74
+ }
75
+
76
+ /** The `variants` list of a multivariate block whose variants have the form `value`. */
77
+ function variantsSchema(value: any) {
78
+ return {
79
+ type: "array",
80
+ title: "Variants",
81
+ items: {
82
+ type: "object",
83
+ required: ["rule", "value"],
84
+ properties: {
85
+ rule: ruleSchema(),
86
+ value,
87
+ },
88
+ },
89
+ };
90
+ }
91
+
92
+ function builtInProps(name: string, ctx: BuiltInContext): any {
93
+ switch (name) {
94
+ case "lazy":
95
+ return lazySchema({ title: "Value" });
96
+ case "multivariate":
97
+ return {
98
+ type: "object",
99
+ required: ["variants"],
100
+ properties: {
101
+ // Under the short name, each value is wrapped in a lazy block, so
102
+ // only the picked variant's value resolves (spec: built-in-blocks ›
103
+ // Variants). Legacy names store it plain: see legacyMultivariateValue.
104
+ variants: variantsSchema(lazySchema({ title: "Value" })),
105
+ experiment: {
106
+ type: "string",
107
+ title: "Experiment",
108
+ description: "The stable ID of an A/B test",
109
+ },
110
+ },
111
+ };
112
+ case "always":
113
+ case "never":
114
+ return { type: "object", properties: {} };
115
+ case "date":
116
+ return {
117
+ type: "object",
118
+ properties: {
119
+ start: { type: "string", format: "date-time", title: "Start" },
120
+ end: { type: "string", format: "date-time", title: "End" },
121
+ },
122
+ };
123
+ case "page":
124
+ return {
125
+ type: "object",
126
+ required: ["name", "path", "sections"],
127
+ properties: {
128
+ name: { type: "string", title: "Name" },
129
+ path: { type: "string", title: "Path" },
130
+ seo: { title: "SEO", anyOf: [resolvableRef(), ...ctx.seoRefs], nullable: true },
131
+ sections: {
132
+ title: "Sections",
133
+ anyOf: [
134
+ { type: "array", title: "Sections", items: sectionRef() },
135
+ sectionListVariants(["multivariate"], true),
136
+ sectionListVariants(
137
+ ["website/flags/multivariate.ts", "website/flags/multivariate/section.ts"],
138
+ false,
139
+ ),
140
+ ],
141
+ },
142
+ },
143
+ };
144
+ case "redirect":
145
+ return {
146
+ type: "object",
147
+ required: ["from", "to", "permanent"],
148
+ properties: {
149
+ from: { type: "string", title: "From" },
150
+ to: { type: "string", title: "To" },
151
+ permanent: {
152
+ type: "boolean",
153
+ title: "Permanent",
154
+ description: "301 when true, 302 otherwise",
155
+ },
156
+ status: { type: "number", enum: [301, 302, 307, 308], title: "Status" },
157
+ discardQueryParameters: { type: "boolean", title: "Discard query parameters" },
158
+ },
159
+ };
160
+ case "telemetry":
161
+ return {
162
+ type: "object",
163
+ properties: {
164
+ enabled: { type: "boolean", title: "Enabled", default: true },
165
+ metrics: { type: "boolean", title: "Metrics", default: true },
166
+ errorSampleRate: {
167
+ type: "number",
168
+ title: "Error sample rate",
169
+ minimum: 0,
170
+ maximum: 1,
171
+ default: 0.05,
172
+ },
173
+ traceSampleRate: {
174
+ type: "number",
175
+ title: "Trace sample rate",
176
+ minimum: 0,
177
+ maximum: 1,
178
+ default: 0,
179
+ },
180
+ },
181
+ };
182
+ case "analytics":
183
+ return {
184
+ type: "object",
185
+ properties: {
186
+ collector: { type: "string", title: "Collector" },
187
+ enabled: { type: "boolean", title: "Enabled", default: true },
188
+ },
189
+ };
190
+ case "secret":
191
+ return {
192
+ type: "object",
193
+ required: ["ciphertext"],
194
+ properties: { ciphertext: { type: "string", title: "Ciphertext", writeOnly: true } },
195
+ };
196
+ }
197
+ }
198
+
199
+ /**
200
+ * A whole `sections` list with variants: each value is a list of sections,
201
+ * in a lazy block under `multivariate` and plain under the legacy names.
202
+ */
203
+ function sectionListVariants(names: string[], lazy: boolean) {
204
+ const sections = { type: "array", title: "Sections", items: sectionRef() };
205
+ return {
206
+ type: "object",
207
+ title: lazy ? "Variants" : "Variants (legacy)",
208
+ required: ["__resolveType"],
209
+ properties: {
210
+ __resolveType: { type: "string", enum: names },
211
+ variants: variantsSchema(lazy ? lazySchema(sections) : sections),
212
+ },
213
+ };
214
+ }
215
+
216
+ export function builtInDefinition(name: string, ctx: BuiltInContext): any {
217
+ const docs = BUILT_IN_DOCS[name];
218
+ return flatDefinition(name, builtInProps(name, ctx), {
219
+ description: docs.description,
220
+ ...(docs.icon ? { icon: docs.icon } : {}),
221
+ });
222
+ }
223
+
224
+ /**
225
+ * The per-kind multivariate definitions the site editor's field-variant UI
226
+ * reads (`variants.items.properties.value` is the form of the field). Legacy
227
+ * names store plain values; `multivariate` itself stores lazy ones.
228
+ */
229
+ export function legacyMultivariateValue(alias: string): any {
230
+ switch (alias) {
231
+ case "website/flags/multivariate/section.ts":
232
+ return { ...sectionRef(), title: "Section" };
233
+ default:
234
+ return { title: "Value" };
235
+ }
236
+ }