@decocms/blocks 8.1.0-next.2 → 8.1.0-next.4

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 (125) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/index.js.map +1 -1
  5. package/dist/protocol/conformance/contentHashFixtures.d.ts +29 -0
  6. package/dist/protocol/conformance/contentHashFixtures.d.ts.map +1 -1
  7. package/dist/protocol/conformance/contentHashFixtures.js +30 -0
  8. package/dist/protocol/conformance/contentHashFixtures.js.map +1 -1
  9. package/dist/protocol/conformance/index.d.ts +1 -1
  10. package/dist/protocol/conformance/index.d.ts.map +1 -1
  11. package/dist/protocol/conformance/index.js +1 -1
  12. package/dist/protocol/conformance/index.js.map +1 -1
  13. package/dist/protocol/index.d.ts +5 -2
  14. package/dist/protocol/index.d.ts.map +1 -1
  15. package/dist/protocol/index.js +5 -2
  16. package/dist/protocol/index.js.map +1 -1
  17. package/dist/protocol/secrets.d.ts.map +1 -1
  18. package/dist/protocol/secrets.js +9 -2
  19. package/dist/protocol/secrets.js.map +1 -1
  20. package/dist/protocol/server/assets.d.ts +1 -1
  21. package/dist/protocol/server/assets.js +1 -1
  22. package/dist/v8/builtins/data.d.ts +21 -5
  23. package/dist/v8/builtins/data.d.ts.map +1 -1
  24. package/dist/v8/builtins/data.js +47 -6
  25. package/dist/v8/builtins/data.js.map +1 -1
  26. package/dist/v8/builtins/index.d.ts.map +1 -1
  27. package/dist/v8/builtins/index.js +2 -3
  28. package/dist/v8/builtins/index.js.map +1 -1
  29. package/dist/v8/canonical.d.ts +28 -0
  30. package/dist/v8/canonical.d.ts.map +1 -1
  31. package/dist/v8/canonical.js +19 -0
  32. package/dist/v8/canonical.js.map +1 -1
  33. package/dist/v8/cli/check/index.d.ts.map +1 -1
  34. package/dist/v8/cli/check/index.js +13 -1
  35. package/dist/v8/cli/check/index.js.map +1 -1
  36. package/dist/v8/cli/index.d.ts +2 -1
  37. package/dist/v8/cli/index.d.ts.map +1 -1
  38. package/dist/v8/cli/index.js +2 -1
  39. package/dist/v8/cli/index.js.map +1 -1
  40. package/dist/v8/cli/run.d.ts.map +1 -1
  41. package/dist/v8/cli/run.js +2 -9
  42. package/dist/v8/cli/run.js.map +1 -1
  43. package/dist/v8/cli/schema/builtinSchemas.d.ts.map +1 -1
  44. package/dist/v8/cli/schema/builtinSchemas.js +48 -28
  45. package/dist/v8/cli/schema/builtinSchemas.js.map +1 -1
  46. package/dist/v8/cli/schema/generate.d.ts.map +1 -1
  47. package/dist/v8/cli/schema/generate.js +2 -2
  48. package/dist/v8/cli/schema/generate.js.map +1 -1
  49. package/dist/v8/cli/schema/tsProgram.d.ts +16 -0
  50. package/dist/v8/cli/schema/tsProgram.d.ts.map +1 -1
  51. package/dist/v8/cli/schema/tsProgram.js +48 -0
  52. package/dist/v8/cli/schema/tsProgram.js.map +1 -1
  53. package/dist/v8/cli/schema/typeToSchema.d.ts +13 -0
  54. package/dist/v8/cli/schema/typeToSchema.d.ts.map +1 -1
  55. package/dist/v8/cli/schema/typeToSchema.js +85 -2
  56. package/dist/v8/cli/schema/typeToSchema.js.map +1 -1
  57. package/dist/v8/cli/serve/server.d.ts +0 -4
  58. package/dist/v8/cli/serve/server.d.ts.map +1 -1
  59. package/dist/v8/cli/serve/server.js +20 -46
  60. package/dist/v8/cli/serve/server.js.map +1 -1
  61. package/dist/v8/cms.d.ts +5 -2
  62. package/dist/v8/cms.d.ts.map +1 -1
  63. package/dist/v8/cms.js +188 -20
  64. package/dist/v8/cms.js.map +1 -1
  65. package/dist/v8/content.d.ts +32 -2
  66. package/dist/v8/content.d.ts.map +1 -1
  67. package/dist/v8/content.js +82 -19
  68. package/dist/v8/content.js.map +1 -1
  69. package/dist/v8/draft.d.ts +13 -12
  70. package/dist/v8/draft.d.ts.map +1 -1
  71. package/dist/v8/draft.js +75 -9
  72. package/dist/v8/draft.js.map +1 -1
  73. package/dist/v8/hosts.d.ts +55 -0
  74. package/dist/v8/hosts.d.ts.map +1 -0
  75. package/dist/v8/hosts.js +197 -0
  76. package/dist/v8/hosts.js.map +1 -0
  77. package/dist/v8/index.d.ts +4 -3
  78. package/dist/v8/index.d.ts.map +1 -1
  79. package/dist/v8/index.js +3 -2
  80. package/dist/v8/index.js.map +1 -1
  81. package/dist/v8/remoteLoader.d.ts.map +1 -1
  82. package/dist/v8/remoteLoader.js +222 -26
  83. package/dist/v8/remoteLoader.js.map +1 -1
  84. package/dist/v8/settings.d.ts +27 -0
  85. package/dist/v8/settings.d.ts.map +1 -0
  86. package/dist/v8/settings.js +130 -0
  87. package/dist/v8/settings.js.map +1 -0
  88. package/dist/v8/telemetry.d.ts +13 -3
  89. package/dist/v8/telemetry.d.ts.map +1 -1
  90. package/dist/v8/telemetry.js +31 -32
  91. package/dist/v8/telemetry.js.map +1 -1
  92. package/dist/v8/types.d.ts +69 -3
  93. package/dist/v8/types.d.ts.map +1 -1
  94. package/dist/v8/variants.d.ts +3 -0
  95. package/dist/v8/variants.d.ts.map +1 -0
  96. package/dist/v8/variants.js +65 -0
  97. package/dist/v8/variants.js.map +1 -0
  98. package/package.json +1 -1
  99. package/src/index.ts +3 -3
  100. package/src/protocol/conformance/contentHashFixtures.ts +57 -0
  101. package/src/protocol/conformance/index.ts +6 -1
  102. package/src/protocol/index.ts +8 -1
  103. package/src/protocol/secrets.ts +10 -2
  104. package/src/protocol/server/assets.ts +1 -1
  105. package/src/v8/builtins/data.ts +56 -7
  106. package/src/v8/builtins/index.ts +2 -3
  107. package/src/v8/canonical.ts +36 -0
  108. package/src/v8/cli/check/index.ts +23 -1
  109. package/src/v8/cli/index.ts +2 -1
  110. package/src/v8/cli/run.ts +3 -8
  111. package/src/v8/cli/schema/builtinSchemas.ts +49 -28
  112. package/src/v8/cli/schema/generate.ts +2 -1
  113. package/src/v8/cli/schema/tsProgram.ts +44 -0
  114. package/src/v8/cli/schema/typeToSchema.ts +93 -2
  115. package/src/v8/cli/serve/server.ts +20 -55
  116. package/src/v8/cms.ts +235 -23
  117. package/src/v8/content.ts +84 -18
  118. package/src/v8/draft.ts +88 -15
  119. package/src/v8/hosts.ts +184 -0
  120. package/src/v8/index.ts +6 -8
  121. package/src/v8/remoteLoader.ts +258 -23
  122. package/src/v8/settings.ts +157 -0
  123. package/src/v8/telemetry.ts +43 -40
  124. package/src/v8/types.ts +62 -3
  125. package/src/v8/variants.ts +61 -0
@@ -1,4 +1,4 @@
1
- import type { Analytics, Redirect, Telemetry } from "../types.ts";
1
+ import type { Analytics, CMSSettings, Redirect, Telemetry } from "../types.ts";
2
2
 
3
3
  /** The hosted Deco CMS collector: where page views go when `collector` is left out. */
4
4
  export const HOSTED_ANALYTICS_COLLECTOR = "https://d.lilstts.com/events";
@@ -12,12 +12,61 @@ export const page = <P>(props: P): P => props;
12
12
  /** `redirect`: returns its arguments as saved. */
13
13
  export const redirect = (props: Redirect): Redirect => props;
14
14
 
15
- /** `telemetry`: the type of the well-known `Telemetry` saved block; returns its arguments. */
16
- export const telemetry = (props: Telemetry = {}): Telemetry => props;
15
+ /** The `telemetry` section's defaults (sample rates before code's caps). */
16
+ export const TELEMETRY_DEFAULTS: Readonly<Required<Telemetry>> = Object.freeze({
17
+ enabled: true,
18
+ metrics: true,
19
+ errorSampleRate: 0.05,
20
+ traceSampleRate: 0,
21
+ });
22
+
23
+ /** The well-known saved block that holds the CMS settings, and its built-in type. */
24
+ export const SETTINGS_BLOCK = "CMS";
25
+ export const SETTINGS_TYPE = "cms-settings";
26
+
27
+ /** The `telemetry` section with its defaults filled in; rates as saved, before any cap. */
28
+ export function telemetrySection(section: unknown): Required<Telemetry> {
29
+ const t = isRecord(section) ? section : {};
30
+ return {
31
+ enabled: typeof t.enabled === "boolean" ? t.enabled : TELEMETRY_DEFAULTS.enabled,
32
+ metrics: typeof t.metrics === "boolean" ? t.metrics : TELEMETRY_DEFAULTS.metrics,
33
+ errorSampleRate: rate(t.errorSampleRate, TELEMETRY_DEFAULTS.errorSampleRate),
34
+ traceSampleRate: rate(t.traceSampleRate, TELEMETRY_DEFAULTS.traceSampleRate),
35
+ };
36
+ }
37
+
38
+ /** The `analytics` section with its defaults filled in. */
39
+ export function analyticsSection(section: unknown): Required<Analytics> {
40
+ const a = isRecord(section) ? section : {};
41
+ return {
42
+ collector:
43
+ typeof a.collector === "string" && a.collector !== ""
44
+ ? a.collector
45
+ : HOSTED_ANALYTICS_COLLECTOR,
46
+ enabled: typeof a.enabled === "boolean" ? a.enabled : true,
47
+ };
48
+ }
17
49
 
18
- /** `analytics`: returns its input with the defaults filled in. */
19
- export const analytics = (props: Analytics = {}): Required<Analytics> => ({
50
+ /**
51
+ * `cms-settings`: the type of the well-known saved block `CMS`. Returns its
52
+ * input with the telemetry and analytics defaults filled in; `preview` stays
53
+ * as saved, since its default depends on code (`cms.settings()` applies it).
54
+ */
55
+ export const cmsSettings = (
56
+ props: CMSSettings = {},
57
+ ): CMSSettings & { telemetry: Required<Telemetry>; analytics: Required<Analytics> } => ({
20
58
  ...props,
21
- collector: props.collector ?? HOSTED_ANALYTICS_COLLECTOR,
22
- enabled: props.enabled ?? true,
59
+ telemetry: telemetrySection(props.telemetry),
60
+ analytics: analyticsSection(props.analytics),
23
61
  });
62
+
63
+ /** A sample rate between 0 and 1, or `fallback` when it isn't a number. */
64
+ export function rate(value: unknown, fallback: number): number {
65
+ return typeof value === "number" && Number.isFinite(value)
66
+ ? Math.min(1, Math.max(0, value))
67
+ : fallback;
68
+ }
69
+
70
+ function isRecord(value: unknown): value is Record<string, unknown> {
71
+ return typeof value === "object" && value !== null && !Array.isArray(value);
72
+ }
@@ -1,5 +1,5 @@
1
1
  import type { BlockFunction } from "../types.ts";
2
- import { analytics, page, redirect, telemetry } from "./data.ts";
2
+ import { cmsSettings, page, redirect, SETTINGS_TYPE } from "./data.ts";
3
3
  import { lazy } from "./lazy.ts";
4
4
  import { always, date, never } from "./matchers.ts";
5
5
  import { multivariate } from "./multivariate.ts";
@@ -17,8 +17,7 @@ export const builtIns: Readonly<Record<string, BlockFunction>> = Object.freeze({
17
17
  date,
18
18
  page,
19
19
  redirect,
20
- telemetry,
21
- analytics,
20
+ [SETTINGS_TYPE]: cmsSettings,
22
21
  secret: secretBlock(),
23
22
  });
24
23
 
@@ -115,3 +115,39 @@ export const APPLY_DIGEST_DOMAIN = "deco-content/blocks.apply@1\n";
115
115
  export function applyRequestDigest(params: object): Promise<string> {
116
116
  return sha256Hex(APPLY_DIGEST_DOMAIN + canonicalJson(params));
117
117
  }
118
+
119
+ /** The version of the draft overlay manifest format below. */
120
+ export const DRAFT_OVERLAY_FORMAT = 1;
121
+
122
+ /**
123
+ * A draft overlay manifest (see /next/content-delivery#exact-draft-previews):
124
+ * the complete, cumulative set of a draft's changes, never a patch over an
125
+ * earlier version. `set` maps each changed entry's name to the block hash of
126
+ * its JSON; `delete` names the entries the draft removed (tombstones). The two
127
+ * are disjoint. There is no base revision: the server rendering the draft layers it over the
128
+ * production content it already has.
129
+ */
130
+ export interface DraftOverlay {
131
+ format: typeof DRAFT_OVERLAY_FORMAT;
132
+ set: Record<string, string>;
133
+ delete: string[];
134
+ }
135
+
136
+ /**
137
+ * The block hash of one changed entry: SHA-256 over its canonical JSON,
138
+ * lowercase hex. A draft block asset is stored under it
139
+ * (`/sites/<site>/draft-blocks/<block-hash>.json`), and the SDK checks every
140
+ * asset it downloads hashes to its name.
141
+ */
142
+ export function computeBlockHash(entry: unknown): Promise<string> {
143
+ return sha256Hex(canonicalJson(entry));
144
+ }
145
+
146
+ /**
147
+ * The overlay version: SHA-256 over the manifest's canonical JSON, lowercase
148
+ * hex. The manifest is stored under it (`/sites/<site>/drafts/<version>.json`)
149
+ * and a draft pointer names it after its `@`.
150
+ */
151
+ export function computeOverlayVersion(overlay: DraftOverlay): Promise<string> {
152
+ return sha256Hex(canonicalJson(overlay));
153
+ }
@@ -20,6 +20,7 @@
20
20
  import fs from "node:fs";
21
21
  import { Ajv, type ValidateFunction } from "ajv";
22
22
  import { isWellFormedCiphertext } from "../../../protocol/secrets.ts";
23
+ import { SETTINGS_BLOCK, SETTINGS_TYPE } from "../../builtins/data.ts";
23
24
  import { isBlock, own } from "../../json.ts";
24
25
  import { findRouteConflicts } from "../../matchRoute.ts";
25
26
  import { isBuiltIn, storesPlainVariants } from "../builtins.ts";
@@ -70,6 +71,12 @@ function blockDefinitionName(schema: Json): string | null {
70
71
  return e && e.length === 1 && typeof schema.title === "string" && !schema.format ? e[0] : null;
71
72
  }
72
73
 
74
+ /** Prerelease built-ins folded into the CMS settings block, with no alias. */
75
+ const FOLDED_BUILT_INS: Record<string, string> = {
76
+ telemetry: `the built-in is now the telemetry section of the "${SETTINGS_BLOCK}" block (type "${SETTINGS_TYPE}"); see /next/renames-and-migrations#site-settings`,
77
+ analytics: `the built-in is now the analytics section of the "${SETTINGS_BLOCK}" block (type "${SETTINGS_TYPE}"); see /next/renames-and-migrations#site-settings`,
78
+ };
79
+
73
80
  // ---------------------------------------------------------------------------
74
81
  // The validation document: the schema, with every field also accepting a block
75
82
  // ---------------------------------------------------------------------------
@@ -481,7 +488,13 @@ class Checker {
481
488
 
482
489
  if (type === null) {
483
490
  if (!Object.hasOwn(this.saved.blocks, name)) {
484
- this.report(ctx, path, `unknown block type "${name}"`);
491
+ this.report(
492
+ ctx,
493
+ path,
494
+ Object.hasOwn(FOLDED_BUILT_INS, name)
495
+ ? `unknown block type "${name}": ${FOLDED_BUILT_INS[name]}`
496
+ : `unknown block type "${name}"`,
497
+ );
485
498
  return;
486
499
  }
487
500
  // A reference to a saved block: check what it resolves to against the field.
@@ -650,6 +663,15 @@ class Checker {
650
663
  this.report(ctx, "", "missing __resolveType: a saved block names the function it calls");
651
664
  continue;
652
665
  }
666
+ if (name === SETTINGS_BLOCK && entry.__resolveType !== SETTINGS_TYPE) {
667
+ this.report(
668
+ ctx,
669
+ "",
670
+ `"${SETTINGS_BLOCK}" is the name of the CMS settings block (type "${SETTINGS_TYPE}"); ` +
671
+ "this one is ignored as settings, so rename it",
672
+ "warning",
673
+ );
674
+ }
653
675
  this.checkBlock(ctx, entry, "", null);
654
676
  }
655
677
  problems.push(...this.routeProblems());
@@ -6,8 +6,9 @@
6
6
  *
7
7
  * The four commands and their options, plus what the one-time migration
8
8
  * (the `deco-v7-to-v8-migration` skill) reads: the built-in block names, the alias
9
- * table and the saved-blocks reader.
9
+ * table, the saved-blocks reader and the host-pattern parser.
10
10
  */
11
+ export { formatHostPattern, type HostPattern, parseHostPattern } from "../hosts.ts";
11
12
  export { BUILT_IN_BLOCKS, LEGACY_ALIASES } from "./builtins.ts";
12
13
  export { type CheckOptions, check } from "./check/index.ts";
13
14
  export { type ContentOptions, content, readSavedBlocks, type SavedBlocks } from "./content.ts";
package/src/v8/cli/run.ts CHANGED
@@ -10,7 +10,7 @@ import { reportSchema, schema, writeSchema } from "./schema/index.ts";
10
10
  import { serve, startServer } from "./serve/server.ts";
11
11
  import { watchFiles, watchTree } from "./watch.ts";
12
12
 
13
- type FlagKind = "string" | "boolean" | "list";
13
+ type FlagKind = "string" | "boolean";
14
14
 
15
15
  const COMMANDS: Record<string, { usage: string; flags: Record<string, FlagKind> }> = {
16
16
  schema: {
@@ -24,14 +24,12 @@ const COMMANDS: Record<string, { usage: string; flags: Record<string, FlagKind>
24
24
  check: { usage: "deco check [--root <dir>]", flags: { root: "string" } },
25
25
  serve: {
26
26
  usage:
27
- "deco serve [--root <dir>] [--port <n>] [--host <addr>] [--preview <host:port|url>] [--token <t>] [--allow-origin <origin>]… [--assets <dir>] [--read-only]",
27
+ "deco serve [--root <dir>] [--port <n>] [--host <addr>] [--preview <host:port|url>] [--assets <dir>] [--read-only]",
28
28
  flags: {
29
29
  root: "string",
30
30
  port: "string",
31
31
  host: "string",
32
32
  preview: "string",
33
- token: "string",
34
- "allow-origin": "list",
35
33
  assets: "string",
36
34
  "read-only": "boolean",
37
35
  },
@@ -78,8 +76,7 @@ export function parseFlags(command: string, args: string[]): ParsedFlags {
78
76
  throw new CliError(`--${name} needs a value`);
79
77
  i++;
80
78
  }
81
- if (kind === "list") flags[name] = [...((flags[name] as string[]) ?? []), value];
82
- else flags[name] = value;
79
+ flags[name] = value;
83
80
  }
84
81
  return flags;
85
82
  }
@@ -213,8 +210,6 @@ export async function runCli(argv: string[], options: RunOptions = {}): Promise<
213
210
  port,
214
211
  host: flags.host as string | undefined,
215
212
  preview: flags.preview as string | undefined,
216
- token: flags.token as string | undefined,
217
- allowOrigins: flags["allow-origin"] as string[] | undefined,
218
213
  assets: flags.assets as string | undefined,
219
214
  readOnly: Boolean(flags["read-only"]),
220
215
  };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The forms of the ten built-in blocks (spec: built-in-blocks, and the types
2
+ * The forms of the nine built-in blocks (spec: built-in-blocks, and the types
3
3
  * in api-reference › Types). They're always in the schema, unless the block
4
4
  * map declares the same key, which replaces the built-in.
5
5
  */
@@ -15,8 +15,7 @@ export const BUILT_IN_GROUPS: Record<string, ManifestGroup> = {
15
15
  date: "matchers",
16
16
  page: "pages",
17
17
  redirect: "redirects",
18
- telemetry: "content",
19
- analytics: "content",
18
+ "cms-settings": "content",
20
19
  secret: "loaders",
21
20
  };
22
21
 
@@ -36,8 +35,11 @@ const BUILT_IN_DOCS: Record<string, { title: string; description: string; icon?:
36
35
  },
37
36
  page: { title: "Page", description: "A page at a URL" },
38
37
  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" },
38
+ "cms-settings": {
39
+ title: "CMS settings",
40
+ description: "Preview hosts, telemetry and analytics: the saved block named CMS",
41
+ icon: "settings",
42
+ },
41
43
  secret: { title: "Secret", description: "An encrypted value, decrypted on the server" },
42
44
  };
43
45
 
@@ -157,34 +159,53 @@ function builtInProps(name: string, ctx: BuiltInContext): any {
157
159
  discardQueryParameters: { type: "boolean", title: "Discard query parameters" },
158
160
  },
159
161
  };
160
- case "telemetry":
162
+ case "cms-settings":
161
163
  return {
162
164
  type: "object",
163
165
  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,
166
+ preview: {
167
+ type: "object",
168
+ title: "Preview",
169
+ properties: {
170
+ hosts: {
171
+ type: "array",
172
+ title: "Hosts",
173
+ description:
174
+ "Host patterns drafts may be previewed on, such as staging.example.com or *.example.com; empty turns previews off. Without it, every host (or the hosts code allows).",
175
+ items: { type: "string" },
176
+ },
177
+ },
172
178
  },
173
- traceSampleRate: {
174
- type: "number",
175
- title: "Trace sample rate",
176
- minimum: 0,
177
- maximum: 1,
178
- default: 0,
179
+ telemetry: {
180
+ type: "object",
181
+ title: "Telemetry",
182
+ properties: {
183
+ enabled: { type: "boolean", title: "Enabled", default: true },
184
+ metrics: { type: "boolean", title: "Metrics", default: true },
185
+ errorSampleRate: {
186
+ type: "number",
187
+ title: "Error sample rate",
188
+ minimum: 0,
189
+ maximum: 1,
190
+ default: 0.05,
191
+ },
192
+ traceSampleRate: {
193
+ type: "number",
194
+ title: "Trace sample rate",
195
+ minimum: 0,
196
+ maximum: 1,
197
+ default: 0,
198
+ },
199
+ },
200
+ },
201
+ analytics: {
202
+ type: "object",
203
+ title: "Analytics",
204
+ properties: {
205
+ collector: { type: "string", title: "Collector" },
206
+ enabled: { type: "boolean", title: "Enabled", default: true },
207
+ },
179
208
  },
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
209
  },
189
210
  };
190
211
  case "secret":
@@ -27,6 +27,7 @@ import {
27
27
  awaitedOf,
28
28
  getJsDocTags,
29
29
  isDescriptorType,
30
+ isFreeFormMap,
30
31
  isJsxType,
31
32
  nonNullable,
32
33
  RESOLVABLE_KEY,
@@ -283,7 +284,7 @@ export async function generateSchema(paths: DecoPaths): Promise<SchemaResult> {
283
284
  root,
284
285
  fitting(type) {
285
286
  const target = nonNullable(type);
286
- if (target.isAny() || target.isUnknown()) return [];
287
+ if (target.isAny() || target.isUnknown() || isFreeFormMap(target)) return [];
287
288
  const cached = fitCache.get(target.compilerType);
288
289
  if (cached) return cached;
289
290
  const keys = candidates
@@ -321,6 +321,50 @@ export class TsNode {
321
321
  return t && typeof t === "object" && "kind" in t ? this.ctx.node(t) : undefined;
322
322
  }
323
323
 
324
+ /**
325
+ * The declarations of the type aliases a type annotation names, as written:
326
+ * `Kind` and `Kind | null` both give `Kind`'s. The checker drops the alias
327
+ * from `Kind | undefined`, so this is how a field finds its alias.
328
+ */
329
+ getAliasDeclarationTexts(): string[] {
330
+ const ts = this.ctx.ts;
331
+ const node = this.compilerNode as TS.TypeNode;
332
+ const members = ts.isUnionTypeNode(node) ? node.types : [node];
333
+ const texts: string[] = [];
334
+ for (const member of members) {
335
+ const decl = this.ctx.checker.getTypeFromTypeNode(member).aliasSymbol?.declarations?.[0];
336
+ if (decl) texts.push(decl.getText(decl.getSourceFile()));
337
+ }
338
+ return texts;
339
+ }
340
+
341
+ /**
342
+ * The `@format` on the type alias this annotation names: `Color`,
343
+ * `Color | null` and `Color[]` (then `items` is set) all give `Color`'s.
344
+ * Read from the alias's declaration, since the checker drops an alias of a
345
+ * primitive (`type Color = string` is just `string`).
346
+ */
347
+ getAliasFormat(): { format: string; items: boolean } | undefined {
348
+ const ts = this.ctx.ts;
349
+ const checker = this.ctx.checker;
350
+ const node = this.compilerNode as TS.TypeNode;
351
+ for (const member of ts.isUnionTypeNode(node) ? node.types : [node]) {
352
+ const items = ts.isArrayTypeNode(member);
353
+ const target = items ? member.elementType : member;
354
+ if (!ts.isTypeReferenceNode(target)) continue;
355
+ let symbol = checker.getSymbolAtLocation(target.typeName);
356
+ if (symbol && symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol);
357
+ const decl = symbol?.declarations?.find(ts.isTypeAliasDeclaration);
358
+ if (!decl) continue;
359
+ for (const tag of ts.getJSDocTags(decl)) {
360
+ if (tag.tagName.text !== "format") continue;
361
+ const format = ts.getTextOfJSDocComment(tag.comment)?.trim();
362
+ if (format) return { format, items };
363
+ }
364
+ }
365
+ return undefined;
366
+ }
367
+
324
368
  /** Whether `other` is this node or inside it. */
325
369
  contains(other: TsNode): boolean {
326
370
  const a = this.compilerNode;
@@ -123,9 +123,20 @@ function parseOptions(raw: string): { values: (string | number)[]; labels?: stri
123
123
  return labelled ? { values, labels } : { values };
124
124
  }
125
125
 
126
+ /**
127
+ * `@format` spellings that name a standard format under another name, kept
128
+ * from v7: `@format datetime` (Eitri's vocabulary) is the `date-time` picker,
129
+ * and `deco check` validates it as one.
130
+ */
131
+ const FORMAT_ALIASES: Record<string, string> = { datetime: "date-time" };
132
+
126
133
  function applyJsDocToSchema(schema: any, tags: Record<string, string>): void {
127
134
  for (const [tag, value] of Object.entries(tags)) {
128
135
  if (tag === "ignore") continue;
136
+ if (tag === "format") {
137
+ schema.format = FORMAT_ALIASES[value] ?? value;
138
+ continue;
139
+ }
129
140
  if (tag === "hide") {
130
141
  schema.hide = "true";
131
142
  continue;
@@ -220,6 +231,20 @@ function applyWidgetFormat(schema: any, typeHint: string): void {
220
231
  }
221
232
  }
222
233
 
234
+ /**
235
+ * `@format` written on a type alias (`/** @format color *\/ type Color = string`)
236
+ * reaches every field of that type, a literal select included; a field's own
237
+ * `@format` still wins, since its tags apply afterwards.
238
+ */
239
+ function applyAliasFormat(
240
+ schema: any,
241
+ alias: { format: string; items: boolean } | undefined,
242
+ ): void {
243
+ if (!alias) return;
244
+ const target = alias.items ? schema.items : schema;
245
+ if (target?.type === "string") target.format ??= FORMAT_ALIASES[alias.format] ?? alias.format;
246
+ }
247
+
223
248
  // ---------------------------------------------------------------------------
224
249
  // Recognizing the framework's own types
225
250
  // ---------------------------------------------------------------------------
@@ -324,6 +349,19 @@ export function nonNullable(type: Type): Type {
324
349
  return parts.length === 1 ? parts[0] : type.getNonNullableType();
325
350
  }
326
351
 
352
+ /**
353
+ * `Record<string, any>` and friends: a map of anything, which every block's
354
+ * output fits. It's a free-form value, not a place for a block, so the field
355
+ * doesn't offer the saved-block picker or list every block as a choice.
356
+ */
357
+ export function isFreeFormMap(type: Type): boolean {
358
+ const t = nonNullable(type);
359
+ if (!t.isObject() || t.getProperties().length > 0 || t.getCallSignatures().length > 0)
360
+ return false;
361
+ const value = t.getStringIndexType() ?? t.getNumberIndexType();
362
+ return value !== undefined && (value.isAny() || value.isUnknown());
363
+ }
364
+
327
365
  /** Types a block can fill: objects, arrays and intersections of objects, not primitives. */
328
366
  function isObjectLike(type: Type): boolean {
329
367
  const t = nonNullable(type);
@@ -434,10 +472,51 @@ function fieldSchema(
434
472
  }
435
473
 
436
474
  const schema = typeToJsonSchema(propType, new Set(visited), ctx);
475
+ orderEnumByHint(schema, typeHint);
437
476
  applyWidgetFormat(schema, typeHint);
438
477
  return schema;
439
478
  }
440
479
 
480
+ /**
481
+ * Literal values in the order `text` (the declaration as written) spells them.
482
+ * The checker orders a union's members by when it first met each literal,
483
+ * which another file can change, so `"a" | "b"` could come out as `["b", "a"]`.
484
+ * Values `text` doesn't spell all of keep the checker's order.
485
+ */
486
+ export function inDeclaredOrder<T extends string | number>(values: T[], text: string): T[] {
487
+ const at = values.map((value) => {
488
+ const spelled =
489
+ typeof value === "string"
490
+ ? [`"${value}"`, `'${value}'`, `\`${value}\``]
491
+ .map((q) => text.indexOf(q))
492
+ .filter((i) => i >= 0)
493
+ : [
494
+ ...text.matchAll(
495
+ new RegExp(`(?<![\\w.])${String(value).replace(".", "\\.")}(?![\\w.])`, "g"),
496
+ ),
497
+ ].map((m) => m.index ?? -1);
498
+ return spelled.length > 0 ? Math.min(...spelled) : -1;
499
+ });
500
+ if (at.some((i) => i < 0)) return values;
501
+ return values
502
+ .map((value, i) => ({ value, at: at[i] }))
503
+ .sort((a, b) => a.at - b.at)
504
+ .map((e) => e.value);
505
+ }
506
+
507
+ /** Reorder a literal select (or a list of them) by the field's annotation. */
508
+ function orderEnumByHint(schema: any, typeHint: string): void {
509
+ if (Array.isArray(schema?.enum)) schema.enum = inDeclaredOrder(schema.enum, typeHint);
510
+ else if (Array.isArray(schema?.items?.enum)) {
511
+ schema.items.enum = inDeclaredOrder(schema.items.enum, typeHint);
512
+ }
513
+ }
514
+
515
+ /** The declaration text of a type alias, for ordering its literal members. */
516
+ function aliasDeclarationText(type: Type): string {
517
+ return type.getAliasSymbol()?.getDeclarations()[0]?.getText() ?? "";
518
+ }
519
+
441
520
  /** The "plain value" branch of a field that blocks can fill. */
442
521
  function inlineSchema(type: Type, ctx: SchemaContext, visited: Set<string>): any {
443
522
  if (type.isArray()) {
@@ -514,12 +593,20 @@ export function typeToJsonSchema(
514
593
  }
515
594
  // String-literal unions and string enums: a select, written into the schema.
516
595
  if (nonNull.every((t) => t.isStringLiteral())) {
517
- const result: any = { type: "string", enum: nonNull.map((t) => t.getLiteralValue()) };
596
+ const values = nonNull.map((t) => t.getLiteralValue() as string);
597
+ const result: any = {
598
+ type: "string",
599
+ enum: inDeclaredOrder(values, aliasDeclarationText(type)),
600
+ };
518
601
  if (isNullable) result.nullable = true;
519
602
  return result;
520
603
  }
521
604
  if (nonNull.every((t) => t.isNumberLiteral())) {
522
- const result: any = { type: "number", enum: nonNull.map((t) => t.getLiteralValue()) };
605
+ const values = nonNull.map((t) => t.getLiteralValue() as number);
606
+ const result: any = {
607
+ type: "number",
608
+ enum: inDeclaredOrder(values, aliasDeclarationText(type)),
609
+ };
523
610
  if (isNullable) result.nullable = true;
524
611
  return result;
525
612
  }
@@ -630,6 +717,10 @@ export function typeToJsonSchema(
630
717
  }
631
718
 
632
719
  const schema = fieldSchema(propType, typeHint, ctx, visited);
720
+ if (typeNode) {
721
+ orderEnumByHint(schema, typeNode.getAliasDeclarationTexts().join("\n"));
722
+ applyAliasFormat(schema, typeNode.getAliasFormat());
723
+ }
633
724
  if (schema.anyOf && schema.anyOf[0]?.$ref === resolvableRef().$ref) {
634
725
  // A block-ref field: nullability lives on the wrapper.
635
726
  if (isNullableHint(optional, typeHint)) schema.nullable = true;