@decocms/blocks 8.1.0-next.3 → 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 (97) 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/secrets.d.ts.map +1 -1
  6. package/dist/protocol/secrets.js +9 -2
  7. package/dist/protocol/secrets.js.map +1 -1
  8. package/dist/protocol/server/assets.d.ts +1 -1
  9. package/dist/protocol/server/assets.js +1 -1
  10. package/dist/v8/builtins/data.d.ts +21 -5
  11. package/dist/v8/builtins/data.d.ts.map +1 -1
  12. package/dist/v8/builtins/data.js +47 -6
  13. package/dist/v8/builtins/data.js.map +1 -1
  14. package/dist/v8/builtins/index.d.ts.map +1 -1
  15. package/dist/v8/builtins/index.js +2 -3
  16. package/dist/v8/builtins/index.js.map +1 -1
  17. package/dist/v8/canonical.d.ts +1 -1
  18. package/dist/v8/cli/check/index.d.ts.map +1 -1
  19. package/dist/v8/cli/check/index.js +13 -1
  20. package/dist/v8/cli/check/index.js.map +1 -1
  21. package/dist/v8/cli/index.d.ts +2 -1
  22. package/dist/v8/cli/index.d.ts.map +1 -1
  23. package/dist/v8/cli/index.js +2 -1
  24. package/dist/v8/cli/index.js.map +1 -1
  25. package/dist/v8/cli/run.d.ts.map +1 -1
  26. package/dist/v8/cli/run.js +2 -9
  27. package/dist/v8/cli/run.js.map +1 -1
  28. package/dist/v8/cli/schema/builtinSchemas.d.ts.map +1 -1
  29. package/dist/v8/cli/schema/builtinSchemas.js +48 -28
  30. package/dist/v8/cli/schema/builtinSchemas.js.map +1 -1
  31. package/dist/v8/cli/schema/tsProgram.d.ts +10 -0
  32. package/dist/v8/cli/schema/tsProgram.d.ts.map +1 -1
  33. package/dist/v8/cli/schema/tsProgram.js +31 -0
  34. package/dist/v8/cli/schema/tsProgram.js.map +1 -1
  35. package/dist/v8/cli/schema/typeToSchema.d.ts.map +1 -1
  36. package/dist/v8/cli/schema/typeToSchema.js +15 -1
  37. package/dist/v8/cli/schema/typeToSchema.js.map +1 -1
  38. package/dist/v8/cli/serve/server.d.ts +0 -4
  39. package/dist/v8/cli/serve/server.d.ts.map +1 -1
  40. package/dist/v8/cli/serve/server.js +20 -46
  41. package/dist/v8/cli/serve/server.js.map +1 -1
  42. package/dist/v8/cms.d.ts +5 -2
  43. package/dist/v8/cms.d.ts.map +1 -1
  44. package/dist/v8/cms.js +180 -23
  45. package/dist/v8/cms.js.map +1 -1
  46. package/dist/v8/content.d.ts +14 -0
  47. package/dist/v8/content.d.ts.map +1 -1
  48. package/dist/v8/content.js +28 -0
  49. package/dist/v8/content.js.map +1 -1
  50. package/dist/v8/draft.d.ts +9 -12
  51. package/dist/v8/draft.d.ts.map +1 -1
  52. package/dist/v8/draft.js +8 -4
  53. package/dist/v8/draft.js.map +1 -1
  54. package/dist/v8/hosts.d.ts +55 -0
  55. package/dist/v8/hosts.d.ts.map +1 -0
  56. package/dist/v8/hosts.js +197 -0
  57. package/dist/v8/hosts.js.map +1 -0
  58. package/dist/v8/index.d.ts +4 -3
  59. package/dist/v8/index.d.ts.map +1 -1
  60. package/dist/v8/index.js +3 -2
  61. package/dist/v8/index.js.map +1 -1
  62. package/dist/v8/remoteLoader.d.ts.map +1 -1
  63. package/dist/v8/remoteLoader.js +14 -2
  64. package/dist/v8/remoteLoader.js.map +1 -1
  65. package/dist/v8/settings.d.ts +27 -0
  66. package/dist/v8/settings.d.ts.map +1 -0
  67. package/dist/v8/settings.js +130 -0
  68. package/dist/v8/settings.js.map +1 -0
  69. package/dist/v8/telemetry.d.ts +13 -3
  70. package/dist/v8/telemetry.d.ts.map +1 -1
  71. package/dist/v8/telemetry.js +31 -32
  72. package/dist/v8/telemetry.js.map +1 -1
  73. package/dist/v8/types.d.ts +56 -2
  74. package/dist/v8/types.d.ts.map +1 -1
  75. package/package.json +1 -1
  76. package/src/index.ts +3 -3
  77. package/src/protocol/secrets.ts +10 -2
  78. package/src/protocol/server/assets.ts +1 -1
  79. package/src/v8/builtins/data.ts +56 -7
  80. package/src/v8/builtins/index.ts +2 -3
  81. package/src/v8/canonical.ts +1 -1
  82. package/src/v8/cli/check/index.ts +23 -1
  83. package/src/v8/cli/index.ts +2 -1
  84. package/src/v8/cli/run.ts +3 -8
  85. package/src/v8/cli/schema/builtinSchemas.ts +49 -28
  86. package/src/v8/cli/schema/tsProgram.ts +27 -0
  87. package/src/v8/cli/schema/typeToSchema.ts +18 -1
  88. package/src/v8/cli/serve/server.ts +20 -55
  89. package/src/v8/cms.ts +226 -26
  90. package/src/v8/content.ts +30 -0
  91. package/src/v8/draft.ts +14 -10
  92. package/src/v8/hosts.ts +184 -0
  93. package/src/v8/index.ts +6 -8
  94. package/src/v8/remoteLoader.ts +17 -2
  95. package/src/v8/settings.ts +157 -0
  96. package/src/v8/telemetry.ts +43 -40
  97. package/src/v8/types.ts +48 -2
package/src/index.ts CHANGED
@@ -8,11 +8,10 @@ export {
8
8
  type Client,
9
9
  type CMS,
10
10
  type CMSError,
11
+ type CMSSettings,
11
12
  createCMS,
12
- DRAFT_COOKIE,
13
13
  type DraftPointer,
14
- draftCookie,
15
- draftPointer,
14
+ type EffectiveSettings,
16
15
  formatDraftPointer,
17
16
  type Lazy,
18
17
  type ListOptions,
@@ -22,6 +21,7 @@ export {
22
21
  type Page,
23
22
  parseDraftPointer,
24
23
  type Redirect,
24
+ type RequestLike,
25
25
  type Result,
26
26
  type Route,
27
27
  remoteLoader,
@@ -9,7 +9,8 @@
9
9
  * entry must carry a well-formed `ciphertext`, whatever its field.
10
10
  *
11
11
  * The schema marks a `Secret` field with `"format": "secret"` — the contract
12
- * `deco schema` emits for the `Secret` type. Browser-safe.
12
+ * `deco schema` emits for the `Secret` type. A legacy secret loader block
13
+ * (`website/loaders/secret.ts`) is left alone. Browser-safe.
13
14
  */
14
15
  import { parseCiphertext } from "./ciphertext.ts";
15
16
  import type { BlockViolation } from "./errors.ts";
@@ -23,6 +24,12 @@ export const SECRET_FORMAT = "secret";
23
24
 
24
25
  const MULTIVARIATE_TYPES = new Set(["multivariate", "website/flags/multivariate.ts"]);
25
26
  const LAZY_TYPE = "lazy";
27
+ /**
28
+ * The legacy (v7) secret loader. Its `encrypted` prop is a string marked
29
+ * `"format": "secret"` that already holds the site's own ciphertext, so it
30
+ * isn't a `Secret` field; its blocks are migrated, not guarded.
31
+ */
32
+ const LEGACY_SECRET_LOADER = /(^|\/)loaders\/secret\.ts$/;
26
33
  const MAX_DEPTH = 512;
27
34
 
28
35
  type Json = Record<string, unknown>;
@@ -180,7 +187,8 @@ class SecretWalker {
180
187
  'a "secret" block must carry a well-formed "ciphertext" (v1.<wrappedKey>.<iv>.<ciphertext>)',
181
188
  );
182
189
  }
183
- const definition = this.meta ? blockIndex(this.meta).get(type) : undefined;
190
+ const definition =
191
+ this.meta && !LEGACY_SECRET_LOADER.test(type) ? blockIndex(this.meta).get(type) : undefined;
184
192
  this.walkObject(block, definition, pointer, depth);
185
193
  }
186
194
 
@@ -2,7 +2,7 @@
2
2
  * `createAssetHandler(storage)`: uploads beside the content protocol.
3
3
  *
4
4
  * Uploads aren't one of the four methods. The site editor sends each file to
5
- * `PUT /assets/<name>` with the same token as the protocol; on that path the
5
+ * `PUT /assets/<name>` with the same auth as the protocol; on that path the
6
6
  * file's own image, video, font or PDF content type is accepted instead of
7
7
  * JSON, and the name's extension must match it (`banner.html` sent as
8
8
  * `image/png` is refused; a name without an extension gets the type's). SVG
@@ -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
 
@@ -124,7 +124,7 @@ export const DRAFT_OVERLAY_FORMAT = 1;
124
124
  * the complete, cumulative set of a draft's changes, never a patch over an
125
125
  * earlier version. `set` maps each changed entry's name to the block hash of
126
126
  * its JSON; `delete` names the entries the draft removed (tombstones). The two
127
- * are disjoint. There is no base revision: a preview server layers it over the
127
+ * are disjoint. There is no base revision: the server rendering the draft layers it over the
128
128
  * production content it already has.
129
129
  */
130
130
  export interface DraftOverlay {
@@ -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":
@@ -338,6 +338,33 @@ export class TsNode {
338
338
  return texts;
339
339
  }
340
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
+
341
368
  /** Whether `other` is this node or inside it. */
342
369
  contains(other: TsNode): boolean {
343
370
  const a = this.compilerNode;
@@ -231,6 +231,20 @@ function applyWidgetFormat(schema: any, typeHint: string): void {
231
231
  }
232
232
  }
233
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
+
234
248
  // ---------------------------------------------------------------------------
235
249
  // Recognizing the framework's own types
236
250
  // ---------------------------------------------------------------------------
@@ -703,7 +717,10 @@ export function typeToJsonSchema(
703
717
  }
704
718
 
705
719
  const schema = fieldSchema(propType, typeHint, ctx, visited);
706
- if (typeNode) orderEnumByHint(schema, typeNode.getAliasDeclarationTexts().join("\n"));
720
+ if (typeNode) {
721
+ orderEnumByHint(schema, typeNode.getAliasDeclarationTexts().join("\n"));
722
+ applyAliasFormat(schema, typeNode.getAliasFormat());
723
+ }
707
724
  if (schema.anyOf && schema.anyOf[0]?.$ref === resolvableRef().$ref) {
708
725
  // A block-ref field: nullability lives on the wrapper.
709
726
  if (isNullableHint(optional, typeHint)) schema.nullable = true;
@@ -4,17 +4,17 @@
4
4
  *
5
5
  * The content protocol is `@decocms/blocks/protocol`'s `createContentHandler`
6
6
  * (at `/rpc`) and `createAssetHandler` (at `/assets/<name>`) over the
7
- * filesystem storage; they own the bearer token, `Content-Type`, size limits
8
- * and upload rules. This file is the Node HTTP layer and the checks that
9
- * depend on where it runs:
7
+ * filesystem storage; they own `Content-Type`, size limits and upload rules.
8
+ * `deco serve` has no authentication and answers any origin: any website open
9
+ * in the browser can read and write the content through it, so it is meant
10
+ * to run only while editing. This file is the Node HTTP layer:
10
11
  *
11
- * - Listens on 127.0.0.1 unless `--host` says otherwise (with a warning).
12
- * - Browser requests are accepted only from the site editor's origins and
13
- * `--allow-origin`; CORS and Chrome's local-network preflights are answered.
14
- * - Any `Host` other than the server's own address is refused (DNS rebinding).
12
+ * - Listens on 127.0.0.1 unless `--host` says otherwise (with a warning:
13
+ * the network can reach it then).
14
+ * - CORS is answered for any `Origin` (reflected, with `Vary: Origin`), and
15
+ * so are Chrome's Private/Local Network Access preflights.
15
16
  * - Every save regenerates `.deco/blocks.gen.ts`.
16
17
  */
17
- import { randomBytes } from "node:crypto";
18
18
  import fs from "node:fs";
19
19
  import http from "node:http";
20
20
  import type { AddressInfo } from "node:net";
@@ -30,15 +30,8 @@ import { readSavedBlocks, writeContent } from "../content.ts";
30
30
  import { consoleReporter, type Reporter } from "../log.ts";
31
31
  import { CliError, decoPaths, findDecoRoot, packageVersion } from "../root.ts";
32
32
 
33
- /** The site editor's origins: the browser origins allowed by default. */
34
- const STUDIO_ORIGINS = [
35
- "https://studio.decocms.com",
36
- "https://admin.decocms.com",
37
- "https://admin.deco.cx",
38
- ];
39
-
40
33
  /** Where the site editor link points. */
41
- const STUDIO_ORIGIN = STUDIO_ORIGINS[0];
34
+ const STUDIO_ORIGIN = "https://studio.decocms.com";
42
35
 
43
36
  const DEFAULT_PORT = 4545;
44
37
  const DEFAULT_HOST = "127.0.0.1";
@@ -52,19 +45,15 @@ export interface ServeOptions {
52
45
  host?: string;
53
46
  /** The local app the site editor previews: `localhost:8001` or a full loopback URL. */
54
47
  preview?: string;
55
- token?: string;
56
- allowOrigins?: string[];
57
48
  /** The upload folder, relative to the folder that contains `.deco`. */
58
49
  assets?: string;
59
50
  readOnly?: boolean;
60
51
  reporter?: Reporter;
61
- env?: NodeJS.ProcessEnv;
62
52
  }
63
53
 
64
54
  export interface RunningServer {
65
55
  /** The content protocol endpoint, `http://127.0.0.1:4545/rpc`. */
66
56
  endpoint: string;
67
- token: string;
68
57
  siteEditorUrl: string;
69
58
  port: number;
70
59
  close(): Promise<void>;
@@ -111,24 +100,11 @@ function previewUrl(input: string): string {
111
100
  /** Start the server; resolves once it listens. */
112
101
  export async function startServer(options: ServeOptions = {}): Promise<RunningServer> {
113
102
  const reporter = options.reporter ?? consoleReporter;
114
- const env = options.env ?? process.env;
115
103
  const paths = decoPaths(findDecoRoot(options));
116
- const host = options.host ?? DEFAULT_HOST;
104
+ const host = (options.host ?? DEFAULT_HOST).toLowerCase();
117
105
  const requestedPort = options.port ?? DEFAULT_PORT;
118
106
  const readOnly = options.readOnly ?? false;
119
- if (options.token !== undefined && options.token.trim() === "") {
120
- throw new CliError("--token can't be empty: pass a token, or leave it out for a random one");
121
- }
122
- if (options.token === undefined && env.DECO_SERVE_TOKEN?.trim() === "") {
123
- throw new CliError(
124
- "DECO_SERVE_TOKEN can't be empty: set a token, or unset it for a random one",
125
- );
126
- }
127
- const token = options.token ?? env.DECO_SERVE_TOKEN ?? randomBytes(32).toString("base64url");
128
107
  const preview = previewUrl(options.preview ?? defaultPreviewUrl(paths.root));
129
- const allowedOrigins = new Set(
130
- [...STUDIO_ORIGINS, ...(options.allowOrigins ?? [])].map((o) => o.replace(/\/+$/, "")),
131
- );
132
108
 
133
109
  if (!Number.isInteger(requestedPort) || requestedPort < 0 || requestedPort > 65535) {
134
110
  throw new CliError(`--port must be a port number, got ${requestedPort}`);
@@ -161,19 +137,11 @@ export async function startServer(options: ServeOptions = {}): Promise<RunningSe
161
137
  },
162
138
  };
163
139
  const rpc = createContentHandler(storage, {
164
- token,
165
140
  server: { name: "deco-cli", version: packageVersion() },
166
141
  preview: { url: preview },
167
142
  onError: (error) => reporter.warn(String((error as Error)?.message ?? error)),
168
143
  });
169
- const assets = createAssetHandler(storage, { token });
170
-
171
- let port = requestedPort;
172
- const allowedHosts = () => {
173
- const hosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);
174
- if (!LOOPBACK.has(host)) hosts.add(`${host.includes(":") ? `[${host}]` : host}:${port}`);
175
- return hosts;
176
- };
144
+ const assets = createAssetHandler(storage);
177
145
 
178
146
  const server = http.createServer(async (req, res) => {
179
147
  const origin = req.headers.origin;
@@ -184,21 +152,14 @@ export async function startServer(options: ServeOptions = {}): Promise<RunningSe
184
152
  };
185
153
 
186
154
  try {
187
- // DNS rebinding: only our own address.
188
- if (!allowedHosts().has(String(req.headers.host ?? "").toLowerCase())) {
189
- return refuse(403, ErrorCode.Forbidden, "unexpected Host header");
190
- }
191
155
  if (origin !== undefined) {
192
- if (!allowedOrigins.has(origin)) {
193
- return refuse(403, ErrorCode.Forbidden, `origin ${origin} isn't allowed`);
194
- }
195
156
  cors["access-control-allow-origin"] = origin;
196
157
  cors.vary = "Origin";
197
158
  }
198
159
  if (req.method === "OPTIONS") {
199
160
  const preflight: Record<string, string> = {
200
161
  "access-control-allow-methods": "POST, PUT, OPTIONS",
201
- "access-control-allow-headers": "authorization, content-type",
162
+ "access-control-allow-headers": "content-type",
202
163
  "access-control-max-age": "600",
203
164
  };
204
165
  // Chrome's Local Network Access / Private Network Access preflight.
@@ -232,15 +193,20 @@ export async function startServer(options: ServeOptions = {}): Promise<RunningSe
232
193
  );
233
194
  server.listen(requestedPort, host, () => resolve());
234
195
  });
235
- port = (server.address() as AddressInfo).port;
196
+ const port = (server.address() as AddressInfo).port;
236
197
 
237
198
  const displayHost = host.includes(":") ? `[${host}]` : host;
238
199
  const endpoint = `http://${displayHost}:${port}/rpc`;
239
- const siteEditorUrl = `${STUDIO_ORIGIN}/site-editor#endpoint=${encodeURIComponent(endpoint)}&token=${encodeURIComponent(token)}`;
200
+ // The site editor connects only through loopback; a wildcard address
201
+ // listens there too, so its link uses 127.0.0.1.
202
+ const wildcard = host === "0.0.0.0" || host === "::";
203
+ const linkEndpoint = wildcard ? `http://127.0.0.1:${port}/rpc` : endpoint;
204
+ const siteEditorUrl = `${STUDIO_ORIGIN}/site-editor#endpoint=${encodeURIComponent(linkEndpoint)}`;
240
205
 
241
206
  if (!LOOPBACK.has(host)) {
242
207
  reporter.warn(
243
- `warning: listening on ${host}: other machines can reach this server (the token still applies)`,
208
+ `warning: listening on ${host}: other machines on the network can reach this server and read and write the content` +
209
+ (wildcard ? "" : "; the site editor connects only through 127.0.0.1/localhost"),
244
210
  );
245
211
  }
246
212
  const schemaFile = fs.existsSync(paths.schema)
@@ -263,7 +229,6 @@ export async function startServer(options: ServeOptions = {}): Promise<RunningSe
263
229
 
264
230
  return {
265
231
  endpoint,
266
- token,
267
232
  siteEditorUrl,
268
233
  port,
269
234
  close: () =>