@decocms/blocks 8.9.0 → 8.10.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.
Files changed (257) 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/channel.d.ts +98 -0
  6. package/dist/protocol/channel.d.ts.map +1 -0
  7. package/dist/protocol/channel.js +58 -0
  8. package/dist/protocol/channel.js.map +1 -0
  9. package/dist/protocol/client.js +2 -2
  10. package/dist/protocol/client.js.map +1 -1
  11. package/dist/protocol/conformance/blockMetaVectors.json +214 -0
  12. package/dist/protocol/conformance/contentHashFixtures.d.ts +22 -0
  13. package/dist/protocol/conformance/contentHashFixtures.d.ts.map +1 -1
  14. package/dist/protocol/conformance/contentHashFixtures.js +55 -0
  15. package/dist/protocol/conformance/contentHashFixtures.js.map +1 -1
  16. package/dist/protocol/conformance/index.d.ts +2 -1
  17. package/dist/protocol/conformance/index.d.ts.map +1 -1
  18. package/dist/protocol/conformance/index.js +2 -1
  19. package/dist/protocol/conformance/index.js.map +1 -1
  20. package/dist/protocol/conformance/vectors.d.ts +33 -0
  21. package/dist/protocol/conformance/vectors.d.ts.map +1 -0
  22. package/dist/protocol/conformance/vectors.js +3 -0
  23. package/dist/protocol/conformance/vectors.js.map +1 -0
  24. package/dist/protocol/index.d.ts +11 -1
  25. package/dist/protocol/index.d.ts.map +1 -1
  26. package/dist/protocol/index.js +11 -1
  27. package/dist/protocol/index.js.map +1 -1
  28. package/dist/protocol/keys.d.ts +1 -1
  29. package/dist/protocol/keys.js +1 -1
  30. package/dist/v8/background.d.ts +13 -0
  31. package/dist/v8/background.d.ts.map +1 -1
  32. package/dist/v8/background.js +41 -0
  33. package/dist/v8/background.js.map +1 -1
  34. package/dist/v8/blockMeta.d.ts +27 -0
  35. package/dist/v8/blockMeta.d.ts.map +1 -0
  36. package/dist/v8/blockMeta.js +75 -0
  37. package/dist/v8/blockMeta.js.map +1 -0
  38. package/dist/v8/blockStore.d.ts +43 -0
  39. package/dist/v8/blockStore.d.ts.map +1 -0
  40. package/dist/v8/blockStore.js +95 -0
  41. package/dist/v8/blockStore.js.map +1 -0
  42. package/dist/v8/boundedJson.d.ts +5 -0
  43. package/dist/v8/boundedJson.d.ts.map +1 -1
  44. package/dist/v8/boundedJson.js +10 -2
  45. package/dist/v8/boundedJson.js.map +1 -1
  46. package/dist/v8/boundedMap.d.ts +19 -0
  47. package/dist/v8/boundedMap.d.ts.map +1 -0
  48. package/dist/v8/boundedMap.js +52 -0
  49. package/dist/v8/boundedMap.js.map +1 -0
  50. package/dist/v8/builtins/data.d.ts +18 -2
  51. package/dist/v8/builtins/data.d.ts.map +1 -1
  52. package/dist/v8/builtins/data.js +17 -1
  53. package/dist/v8/builtins/data.js.map +1 -1
  54. package/dist/v8/builtins/index.d.ts.map +1 -1
  55. package/dist/v8/builtins/index.js +2 -1
  56. package/dist/v8/builtins/index.js.map +1 -1
  57. package/dist/v8/builtins/legacy.d.ts +6 -3
  58. package/dist/v8/builtins/legacy.d.ts.map +1 -1
  59. package/dist/v8/builtins/legacy.js +6 -3
  60. package/dist/v8/builtins/legacy.js.map +1 -1
  61. package/dist/v8/canonical.d.ts +8 -0
  62. package/dist/v8/canonical.d.ts.map +1 -1
  63. package/dist/v8/canonical.js +15 -0
  64. package/dist/v8/canonical.js.map +1 -1
  65. package/dist/v8/cli/builtins.d.ts.map +1 -1
  66. package/dist/v8/cli/builtins.js +1 -0
  67. package/dist/v8/cli/builtins.js.map +1 -1
  68. package/dist/v8/cli/check/index.d.ts +10 -0
  69. package/dist/v8/cli/check/index.d.ts.map +1 -1
  70. package/dist/v8/cli/check/index.js +91 -7
  71. package/dist/v8/cli/check/index.js.map +1 -1
  72. package/dist/v8/cli/content.d.ts +12 -25
  73. package/dist/v8/cli/content.d.ts.map +1 -1
  74. package/dist/v8/cli/content.js +46 -75
  75. package/dist/v8/cli/content.js.map +1 -1
  76. package/dist/v8/cli/index.d.ts +1 -2
  77. package/dist/v8/cli/index.d.ts.map +1 -1
  78. package/dist/v8/cli/index.js +1 -2
  79. package/dist/v8/cli/index.js.map +1 -1
  80. package/dist/v8/cli/remote/commands.d.ts +71 -0
  81. package/dist/v8/cli/remote/commands.d.ts.map +1 -0
  82. package/dist/v8/cli/remote/commands.js +644 -0
  83. package/dist/v8/cli/remote/commands.js.map +1 -0
  84. package/dist/v8/cli/remote/diff.d.ts +15 -0
  85. package/dist/v8/cli/remote/diff.d.ts.map +1 -0
  86. package/dist/v8/cli/remote/diff.js +102 -0
  87. package/dist/v8/cli/remote/diff.js.map +1 -0
  88. package/dist/v8/cli/remote/env.d.ts +35 -0
  89. package/dist/v8/cli/remote/env.d.ts.map +1 -0
  90. package/dist/v8/cli/remote/env.js +84 -0
  91. package/dist/v8/cli/remote/env.js.map +1 -0
  92. package/dist/v8/cli/remote/http.d.ts +149 -0
  93. package/dist/v8/cli/remote/http.d.ts.map +1 -0
  94. package/dist/v8/cli/remote/http.js +381 -0
  95. package/dist/v8/cli/remote/http.js.map +1 -0
  96. package/dist/v8/cli/remote/local.d.ts +90 -0
  97. package/dist/v8/cli/remote/local.d.ts.map +1 -0
  98. package/dist/v8/cli/remote/local.js +309 -0
  99. package/dist/v8/cli/remote/local.js.map +1 -0
  100. package/dist/v8/cli/root.d.ts +29 -0
  101. package/dist/v8/cli/root.d.ts.map +1 -1
  102. package/dist/v8/cli/root.js +28 -0
  103. package/dist/v8/cli/root.js.map +1 -1
  104. package/dist/v8/cli/run.d.ts +11 -1
  105. package/dist/v8/cli/run.d.ts.map +1 -1
  106. package/dist/v8/cli/run.js +281 -124
  107. package/dist/v8/cli/run.js.map +1 -1
  108. package/dist/v8/cli/schema/builtinSchemas.d.ts.map +1 -1
  109. package/dist/v8/cli/schema/builtinSchemas.js +28 -10
  110. package/dist/v8/cli/schema/builtinSchemas.js.map +1 -1
  111. package/dist/v8/cli/schema/generate.js +1 -1
  112. package/dist/v8/cli/schema/generate.js.map +1 -1
  113. package/dist/v8/client.d.ts +9 -9
  114. package/dist/v8/client.d.ts.map +1 -1
  115. package/dist/v8/client.js +138 -50
  116. package/dist/v8/client.js.map +1 -1
  117. package/dist/v8/cms.d.ts +2 -1
  118. package/dist/v8/cms.d.ts.map +1 -1
  119. package/dist/v8/cms.js +55 -46
  120. package/dist/v8/cms.js.map +1 -1
  121. package/dist/v8/content.d.ts +39 -78
  122. package/dist/v8/content.d.ts.map +1 -1
  123. package/dist/v8/content.js +155 -195
  124. package/dist/v8/content.js.map +1 -1
  125. package/dist/v8/contentIndex.d.ts +71 -0
  126. package/dist/v8/contentIndex.d.ts.map +1 -0
  127. package/dist/v8/contentIndex.js +137 -0
  128. package/dist/v8/contentIndex.js.map +1 -0
  129. package/dist/v8/draft.d.ts +7 -7
  130. package/dist/v8/draft.d.ts.map +1 -1
  131. package/dist/v8/draft.js +10 -9
  132. package/dist/v8/draft.js.map +1 -1
  133. package/dist/v8/draftChanges.d.ts +59 -32
  134. package/dist/v8/draftChanges.d.ts.map +1 -1
  135. package/dist/v8/draftChanges.js +139 -75
  136. package/dist/v8/draftChanges.js.map +1 -1
  137. package/dist/v8/errors.d.ts +21 -0
  138. package/dist/v8/errors.d.ts.map +1 -1
  139. package/dist/v8/errors.js +22 -0
  140. package/dist/v8/errors.js.map +1 -1
  141. package/dist/v8/hostedSource.d.ts +57 -0
  142. package/dist/v8/hostedSource.d.ts.map +1 -0
  143. package/dist/v8/hostedSource.js +18 -0
  144. package/dist/v8/hostedSource.js.map +1 -0
  145. package/dist/v8/identity.d.ts +1 -1
  146. package/dist/v8/identity.js +1 -1
  147. package/dist/v8/index.d.ts +1 -0
  148. package/dist/v8/index.d.ts.map +1 -1
  149. package/dist/v8/index.js +1 -0
  150. package/dist/v8/index.js.map +1 -1
  151. package/dist/v8/matchRoute.js +7 -4
  152. package/dist/v8/matchRoute.js.map +1 -1
  153. package/dist/v8/pin.d.ts +34 -0
  154. package/dist/v8/pin.d.ts.map +1 -0
  155. package/dist/v8/pin.js +156 -0
  156. package/dist/v8/pin.js.map +1 -0
  157. package/dist/v8/preview/StudioBridge.d.ts +8 -8
  158. package/dist/v8/preview/StudioBridge.d.ts.map +1 -1
  159. package/dist/v8/preview/StudioBridge.js +8 -10
  160. package/dist/v8/preview/StudioBridge.js.map +1 -1
  161. package/dist/v8/preview/StudioChannel.d.ts +51 -0
  162. package/dist/v8/preview/StudioChannel.d.ts.map +1 -0
  163. package/dist/v8/preview/StudioChannel.js +104 -0
  164. package/dist/v8/preview/StudioChannel.js.map +1 -0
  165. package/dist/v8/preview/index.d.ts +3 -0
  166. package/dist/v8/preview/index.d.ts.map +1 -1
  167. package/dist/v8/preview/index.js +3 -0
  168. package/dist/v8/preview/index.js.map +1 -1
  169. package/dist/v8/remoteLoader.d.ts +42 -5
  170. package/dist/v8/remoteLoader.d.ts.map +1 -1
  171. package/dist/v8/remoteLoader.js +317 -259
  172. package/dist/v8/remoteLoader.js.map +1 -1
  173. package/dist/v8/resolver.d.ts +22 -8
  174. package/dist/v8/resolver.d.ts.map +1 -1
  175. package/dist/v8/resolver.js +37 -32
  176. package/dist/v8/resolver.js.map +1 -1
  177. package/dist/v8/revisionId.d.ts +11 -0
  178. package/dist/v8/revisionId.d.ts.map +1 -0
  179. package/dist/v8/revisionId.js +13 -0
  180. package/dist/v8/revisionId.js.map +1 -0
  181. package/dist/v8/settings.d.ts +6 -6
  182. package/dist/v8/settings.d.ts.map +1 -1
  183. package/dist/v8/settings.js +8 -7
  184. package/dist/v8/settings.js.map +1 -1
  185. package/dist/v8/telemetry.d.ts +4 -2
  186. package/dist/v8/telemetry.d.ts.map +1 -1
  187. package/dist/v8/telemetry.js +2 -2
  188. package/dist/v8/telemetry.js.map +1 -1
  189. package/dist/v8/types.d.ts +52 -40
  190. package/dist/v8/types.d.ts.map +1 -1
  191. package/dist/v8/variants.d.ts +7 -2
  192. package/dist/v8/variants.d.ts.map +1 -1
  193. package/dist/v8/variants.js +21 -24
  194. package/dist/v8/variants.js.map +1 -1
  195. package/dist/v8/vite/index.d.ts +2 -2
  196. package/dist/v8/vite/index.js +1 -1
  197. package/dist/v8/vite/index.js.map +1 -1
  198. package/package.json +1 -1
  199. package/src/index.ts +2 -0
  200. package/src/protocol/channel.ts +127 -0
  201. package/src/protocol/client.ts +2 -2
  202. package/src/protocol/conformance/blockMetaVectors.json +214 -0
  203. package/src/protocol/conformance/contentHashFixtures.ts +74 -0
  204. package/src/protocol/conformance/index.ts +9 -1
  205. package/src/protocol/conformance/vectors.ts +36 -0
  206. package/src/protocol/index.ts +32 -0
  207. package/src/protocol/keys.ts +1 -1
  208. package/src/v8/background.ts +42 -0
  209. package/src/v8/blockMeta.ts +100 -0
  210. package/src/v8/blockStore.ts +124 -0
  211. package/src/v8/boundedJson.ts +20 -2
  212. package/src/v8/boundedMap.ts +53 -0
  213. package/src/v8/builtins/data.ts +26 -2
  214. package/src/v8/builtins/index.ts +2 -1
  215. package/src/v8/builtins/legacy.ts +6 -3
  216. package/src/v8/canonical.ts +15 -0
  217. package/src/v8/cli/builtins.ts +1 -0
  218. package/src/v8/cli/check/index.ts +97 -7
  219. package/src/v8/cli/content.ts +49 -91
  220. package/src/v8/cli/index.ts +1 -2
  221. package/src/v8/cli/remote/commands.ts +834 -0
  222. package/src/v8/cli/remote/diff.ts +100 -0
  223. package/src/v8/cli/remote/env.ts +107 -0
  224. package/src/v8/cli/remote/http.ts +484 -0
  225. package/src/v8/cli/remote/local.ts +343 -0
  226. package/src/v8/cli/root.ts +40 -0
  227. package/src/v8/cli/run.ts +333 -136
  228. package/src/v8/cli/schema/builtinSchemas.ts +29 -10
  229. package/src/v8/cli/schema/generate.ts +1 -1
  230. package/src/v8/client.ts +162 -60
  231. package/src/v8/cms.ts +62 -53
  232. package/src/v8/content.ts +179 -229
  233. package/src/v8/contentIndex.ts +183 -0
  234. package/src/v8/draft.ts +15 -14
  235. package/src/v8/draftChanges.ts +151 -85
  236. package/src/v8/errors.ts +37 -0
  237. package/src/v8/hostedSource.ts +67 -0
  238. package/src/v8/identity.ts +1 -1
  239. package/src/v8/index.ts +1 -0
  240. package/src/v8/matchRoute.ts +7 -4
  241. package/src/v8/pin.ts +176 -0
  242. package/src/v8/preview/StudioBridge.ts +8 -10
  243. package/src/v8/preview/StudioChannel.ts +116 -0
  244. package/src/v8/preview/index.ts +3 -0
  245. package/src/v8/remoteLoader.ts +350 -286
  246. package/src/v8/resolver.ts +56 -33
  247. package/src/v8/revisionId.ts +14 -0
  248. package/src/v8/settings.ts +10 -9
  249. package/src/v8/telemetry.ts +3 -3
  250. package/src/v8/types.ts +52 -40
  251. package/src/v8/variants.ts +30 -26
  252. package/src/v8/vite/index.ts +3 -3
  253. package/dist/v8/cli/serve/server.d.ts +0 -29
  254. package/dist/v8/cli/serve/server.d.ts.map +0 -1
  255. package/dist/v8/cli/serve/server.js +0 -296
  256. package/dist/v8/cli/serve/server.js.map +0 -1
  257. package/src/v8/cli/serve/server.ts +0 -348
@@ -0,0 +1,343 @@
1
+ /**
2
+ * The local files of the remote commands (spec: cli › Local files):
3
+ *
4
+ * - The site is `DECO_SITE` (the environment, else the folder's own config;
5
+ * see `resolveSite`), not a file of its own.
6
+ * - `.deco/blocks/`, git-ignored: one file per block, filled by `deco pull`.
7
+ * - `.deco/pull.json`, git-ignored: what was pulled, per block its content
8
+ * hash (for `deco diff` and the dirty check) and the draft-relative
9
+ * precondition `deco push` sends as `ifMatch`.
10
+ */
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+ import { blockVersion } from "../../../protocol/canonical.ts";
14
+ import { blockFileName, isBlockFileName, serializeBlock } from "../../../protocol/keys.ts";
15
+ import { TOMBSTONE_VERSION } from "../../../protocol/storage.ts";
16
+ import { readSavedBlocks, type SavedBlocks, writeIfChanged } from "../content.ts";
17
+ import { CliError, type DecoPaths, usageError } from "../root.ts";
18
+
19
+ /**
20
+ * Where the remote commands look for `DECO_SITE` after the process
21
+ * environment, in this order, each in the folder that contains `.deco/`:
22
+ * the first one that sets it wins.
23
+ */
24
+ export const SITE_SOURCES = [
25
+ ".env",
26
+ ".dev.vars",
27
+ "wrangler.jsonc",
28
+ "wrangler.json",
29
+ "wrangler.toml",
30
+ ] as const;
31
+
32
+ const SITE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
33
+
34
+ /** The value a dotenv-style file (`.env`, `.dev.vars`) gives `key`, the last one winning. */
35
+ export function dotenvValue(text: string, key: string): string | undefined {
36
+ let value: string | undefined;
37
+ for (const line of text.split(/\r?\n/)) {
38
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
39
+ if (!match || match[1] !== key) continue;
40
+ const raw = match[2]!;
41
+ const quoted = /^(["'])(.*?)\1/.exec(raw);
42
+ value = quoted ? quoted[2]! : raw.replace(/\s+#.*$/, "").trim();
43
+ }
44
+ return value;
45
+ }
46
+
47
+ /**
48
+ * JSONC (`wrangler.jsonc`) as JSON: `//` and `/* *\/` comments and trailing
49
+ * commas removed, string contents untouched.
50
+ */
51
+ export function stripJsonc(text: string): string {
52
+ // Copies a string literal from text[i] (its opening quote) and returns the index after it.
53
+ const literal = (src: string, i: number, into: string[]): number => {
54
+ let j = i + 1;
55
+ while (j < src.length && src[j] !== '"') j += src[j] === "\\" ? 2 : 1;
56
+ into.push(src.slice(i, j + 1));
57
+ return j + 1;
58
+ };
59
+ const noComments: string[] = [];
60
+ for (let i = 0; i < text.length; ) {
61
+ if (text[i] === '"') i = literal(text, i, noComments);
62
+ else if (text.startsWith("//", i)) {
63
+ while (i < text.length && text[i] !== "\n") i++;
64
+ } else if (text.startsWith("/*", i)) {
65
+ const close = text.indexOf("*/", i + 2);
66
+ i = close === -1 ? text.length : close + 2;
67
+ noComments.push(" ");
68
+ } else noComments.push(text[i++]!);
69
+ }
70
+ const plain = noComments.join("");
71
+ const out: string[] = [];
72
+ for (let i = 0; i < plain.length; ) {
73
+ if (plain[i] === '"') i = literal(plain, i, out);
74
+ else if (plain[i] === ",") {
75
+ let j = i + 1;
76
+ while (j < plain.length && /\s/.test(plain[j]!)) j++;
77
+ if (plain[j] !== "}" && plain[j] !== "]") out.push(",");
78
+ i++;
79
+ } else out.push(plain[i++]!);
80
+ }
81
+ return out.join("");
82
+ }
83
+
84
+ /** `vars.DECO_SITE` of a `wrangler.toml`: in its `[vars]` table or a top-level inline `vars = {…}`. */
85
+ export function wranglerTomlVar(text: string, key: string): string | undefined {
86
+ const string = `(?:"((?:[^"\\\\]|\\\\.)*)"|'([^']*)')`;
87
+ let table: string | null = null;
88
+ for (const line of text.split(/\r?\n/)) {
89
+ const header = /^\s*\[\s*([^\]]+?)\s*\]\s*(?:#.*)?$/.exec(line);
90
+ if (header) {
91
+ table = header[1]!;
92
+ continue;
93
+ }
94
+ if (table === "vars") {
95
+ const match = new RegExp(`^\\s*${key}\\s*=\\s*${string}`).exec(line);
96
+ if (match) return match[1] ?? match[2];
97
+ } else if (table === null) {
98
+ const inline = /^\s*vars\s*=\s*\{(.*)\}/.exec(line);
99
+ const match = inline && new RegExp(`(?:^|,)\\s*${key}\\s*=\\s*${string}`).exec(inline[1]!);
100
+ if (match) return match[1] ?? match[2];
101
+ }
102
+ }
103
+ return undefined;
104
+ }
105
+
106
+ function siteFrom(file: string, text: string): string | undefined {
107
+ if (file === ".env" || file === ".dev.vars") return dotenvValue(text, "DECO_SITE");
108
+ if (file === "wrangler.toml") return wranglerTomlVar(text, "DECO_SITE");
109
+ let body: unknown;
110
+ try {
111
+ body = JSON.parse(file === "wrangler.jsonc" ? stripJsonc(text) : text);
112
+ } catch (error) {
113
+ throw new CliError(`${file}: invalid JSON: ${(error as Error).message}`, {
114
+ code: "invalid_config",
115
+ });
116
+ }
117
+ const vars = (body as { vars?: unknown } | null)?.vars;
118
+ const value =
119
+ typeof vars === "object" && vars !== null
120
+ ? (vars as Record<string, unknown>).DECO_SITE
121
+ : undefined;
122
+ return typeof value === "string" ? value : undefined;
123
+ }
124
+
125
+ /**
126
+ * The Studio site the remote commands talk to: `DECO_SITE` from the process
127
+ * environment, else from the folder's own config (`SITE_SOURCES`, in order).
128
+ * Studio finds the site's organization; the CLI never names one. No
129
+ * `DECO_SITE` anywhere is a usage error (64).
130
+ */
131
+ export function resolveSite(
132
+ paths: DecoPaths,
133
+ env: Record<string, string | undefined>,
134
+ ): { site: string; from: string } {
135
+ const found = findSite(paths, env);
136
+ if (!found) {
137
+ throw usageError(
138
+ `no Studio site: set DECO_SITE in the environment, or in ${paths.root}'s .env, .dev.vars, ` +
139
+ "or vars.DECO_SITE of wrangler.jsonc, wrangler.json or wrangler.toml (looked in that order)",
140
+ );
141
+ }
142
+ if (!SITE_RE.test(found.site)) {
143
+ throw usageError(`DECO_SITE (from ${found.from}) isn't a site name: "${found.site}"`);
144
+ }
145
+ return found;
146
+ }
147
+
148
+ /**
149
+ * `DECO_SITE` as `resolveSite` looks for it, unchecked; `null` when it is set
150
+ * nowhere (a site whose content is its git-backed `.deco/blocks`).
151
+ */
152
+ export function findSite(
153
+ paths: DecoPaths,
154
+ env: Record<string, string | undefined>,
155
+ ): { site: string; from: string } | null {
156
+ let found: { site: string; from: string } | undefined;
157
+ const fromEnv = env.DECO_SITE?.trim();
158
+ if (fromEnv) found = { site: fromEnv, from: "the environment" };
159
+ for (const file of SITE_SOURCES) {
160
+ if (found) break;
161
+ let text: string;
162
+ try {
163
+ text = fs.readFileSync(path.join(paths.root, file), "utf8");
164
+ } catch (error) {
165
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
166
+ throw new CliError(`${file}: ${(error as Error).message}`, { code: "invalid_config" });
167
+ }
168
+ const value = siteFrom(file, text)?.trim();
169
+ if (value) found = { site: value, from: file };
170
+ }
171
+ return found ?? null;
172
+ }
173
+
174
+ export interface PullEntry {
175
+ /** `blockVersion` of the pulled value; `null` when the pull holds no such block. */
176
+ hash: string | null;
177
+ /** The precondition, relative to `draft`: its version, the tombstone, or `null`. */
178
+ ifMatch: string | null;
179
+ }
180
+
181
+ export interface PullState {
182
+ format: 1;
183
+ /** The pulled draft, or `null` for production. */
184
+ draft: string | null;
185
+ /** The live revision when it was pulled (`null` before a first publish). */
186
+ revision: string | null;
187
+ pulledAt: string;
188
+ blocks: Record<string, PullEntry>;
189
+ }
190
+
191
+ export function readPull(paths: DecoPaths): PullState | null {
192
+ let text: string;
193
+ try {
194
+ text = fs.readFileSync(paths.pull, "utf8");
195
+ } catch (error) {
196
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
197
+ throw error;
198
+ }
199
+ let body: any;
200
+ try {
201
+ body = JSON.parse(text);
202
+ } catch (error) {
203
+ throw new CliError(
204
+ `.deco/pull.json: invalid JSON (${(error as Error).message}); run deco pull`,
205
+ );
206
+ }
207
+ if (body?.format !== 1 || typeof body.blocks !== "object" || body.blocks === null) {
208
+ throw new CliError(".deco/pull.json isn't one deco pull wrote; run deco pull");
209
+ }
210
+ const blocks: Record<string, PullEntry> = Object.create(null);
211
+ for (const [name, entry] of Object.entries(body.blocks as Record<string, any>)) {
212
+ blocks[name] = { hash: entry?.hash ?? null, ifMatch: entry?.ifMatch ?? null };
213
+ }
214
+ return {
215
+ format: 1,
216
+ draft: typeof body.draft === "string" ? body.draft : null,
217
+ revision: typeof body.revision === "string" ? body.revision : null,
218
+ pulledAt: String(body.pulledAt ?? ""),
219
+ blocks,
220
+ };
221
+ }
222
+
223
+ export function writePull(paths: DecoPaths, state: PullState): void {
224
+ const blocks: Record<string, PullEntry> = {};
225
+ for (const name of Object.keys(state.blocks).sort()) blocks[name] = state.blocks[name]!;
226
+ writeIfChanged(paths.pull, `${JSON.stringify({ ...state, blocks }, null, 2)}\n`);
227
+ }
228
+
229
+ /**
230
+ * Read `.deco/blocks` for a remote command. A file that isn't a valid block
231
+ * stops it: nothing is sent or overwritten from a folder that can't be read.
232
+ */
233
+ export function readLocal(paths: DecoPaths): SavedBlocks {
234
+ const saved = readSavedBlocks(paths.blocks);
235
+ const errors = saved.diagnostics.filter((d) => d.severity === "error");
236
+ if (errors.length > 0) {
237
+ throw new CliError(errors.map((d) => `.deco/blocks/${d.file}: ${d.message}`).join("\n"), {
238
+ code: "invalid_local_block",
239
+ });
240
+ }
241
+ return saved;
242
+ }
243
+
244
+ export type LocalStatus = "changed" | "new" | "deleted";
245
+
246
+ export interface LocalChange {
247
+ name: string;
248
+ status: LocalStatus;
249
+ /** The local value (absent for a deletion). */
250
+ block?: Record<string, unknown>;
251
+ /** Its hash (absent for a deletion). */
252
+ hash?: string;
253
+ }
254
+
255
+ /**
256
+ * What the folder changes against pull.json, in name order: **changed** when
257
+ * a file's hash differs from the recorded one, **new** when a file has no
258
+ * entry (or the entry's hash is `null`), **deleted** when an entry has a hash
259
+ * and no file remains. No pull.json makes every file new.
260
+ */
261
+ export async function localChanges(
262
+ saved: SavedBlocks,
263
+ pull: PullState | null,
264
+ ): Promise<LocalChange[]> {
265
+ const recorded = pull?.blocks ?? Object.create(null);
266
+ const changes: LocalChange[] = [];
267
+ const names = new Set([...Object.keys(saved.blocks), ...Object.keys(recorded)]);
268
+ for (const name of [...names].sort()) {
269
+ const entry = Object.hasOwn(recorded, name) ? recorded[name] : undefined;
270
+ if (Object.hasOwn(saved.blocks, name)) {
271
+ const block = saved.blocks[name]!;
272
+ const hash = await blockVersion(block);
273
+ if (!entry || entry.hash === null) changes.push({ name, status: "new", block, hash });
274
+ else if (entry.hash !== hash) changes.push({ name, status: "changed", block, hash });
275
+ } else if (entry && entry.hash !== null) {
276
+ changes.push({ name, status: "deleted" });
277
+ }
278
+ }
279
+ return changes;
280
+ }
281
+
282
+ /**
283
+ * Make `.deco/blocks` hold exactly `blocks`: write each (only when its text
284
+ * changed) and remove every other block file, other spellings included.
285
+ */
286
+ export function mirrorBlocks(paths: DecoPaths, blocks: Record<string, unknown>): void {
287
+ fs.mkdirSync(paths.blocks, { recursive: true });
288
+ const keep = new Set<string>();
289
+ for (const name of Object.keys(blocks)) {
290
+ const file = blockFileName(name);
291
+ keep.add(file);
292
+ writeIfChanged(path.join(paths.blocks, file), serializeBlock(blocks[name]));
293
+ }
294
+ for (const dirent of fs.readdirSync(paths.blocks, { withFileTypes: true })) {
295
+ if (!dirent.isFile() || !isBlockFileName(dirent.name) || keep.has(dirent.name)) continue;
296
+ fs.rmSync(path.join(paths.blocks, dirent.name));
297
+ }
298
+ }
299
+
300
+ /** Write one block's file, or remove every file of that name (`block` undefined). */
301
+ export function writeLocalBlock(
302
+ paths: DecoPaths,
303
+ saved: SavedBlocks,
304
+ name: string,
305
+ block: unknown,
306
+ ): void {
307
+ const file = blockFileName(name);
308
+ const current = Object.hasOwn(saved.files, name) ? saved.files[name] : undefined;
309
+ if (current && current !== file) fs.rmSync(path.join(paths.blocks, current), { force: true });
310
+ if (block === undefined) {
311
+ fs.rmSync(path.join(paths.blocks, file), { force: true });
312
+ return;
313
+ }
314
+ writeIfChanged(path.join(paths.blocks, file), serializeBlock(block));
315
+ }
316
+
317
+ /** The precondition of a name relative to a draft (spec: write protocol). */
318
+ export async function draftVersion(
319
+ draft: { set: Record<string, unknown>; delete: string[] },
320
+ name: string,
321
+ ): Promise<string | null> {
322
+ if (Object.hasOwn(draft.set, name)) return blockVersion(draft.set[name]);
323
+ if (draft.delete.includes(name)) return TOMBSTONE_VERSION;
324
+ return null;
325
+ }
326
+
327
+ /** A missing `--draft` where one is required. */
328
+ export function requireDraftName(value: unknown, command: string): string {
329
+ if (typeof value !== "string" || value === "") {
330
+ throw usageError(`deco ${command} needs --draft=<name>`);
331
+ }
332
+ return checkDraftName(value);
333
+ }
334
+
335
+ /** A draft name: today's branch rule, at most 255 characters. */
336
+ export function checkDraftName(value: string): string {
337
+ if (value.length > 255 || !/^[A-Za-z0-9][A-Za-z0-9/._-]*$/.test(value)) {
338
+ throw usageError(
339
+ `"${value}" isn't a draft name: letters, digits, and / . _ - after the first, at most 255`,
340
+ );
341
+ }
342
+ return value;
343
+ }
@@ -1,9 +1,46 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
 
4
+ /** Exit codes (spec: cli › Exit codes). */
5
+ export const EXIT = {
6
+ ok: 0,
7
+ /** `deco check` found problems, or any other failure not below. */
8
+ failed: 1,
9
+ conflict: 2,
10
+ auth: 3,
11
+ network: 4,
12
+ /** A save answered Unavailable, or a publish ran out of attempts: run again. */
13
+ busy: 5,
14
+ usage: 64,
15
+ } as const;
16
+
17
+ export interface CliErrorOptions {
18
+ /** The exit code (default 1). */
19
+ exitCode?: number;
20
+ /** A snake_case code for `--json` (default `failed`). */
21
+ code?: string;
22
+ /** Extra fields for the `--json` envelope. */
23
+ details?: Record<string, unknown>;
24
+ }
25
+
4
26
  /** An error the CLI prints as a single line, without a stack trace. */
5
27
  export class CliError extends Error {
6
28
  override name = "CliError";
29
+ readonly exitCode: number;
30
+ readonly code: string;
31
+ readonly details: Record<string, unknown> | undefined;
32
+
33
+ constructor(message: string, options: CliErrorOptions = {}) {
34
+ super(message);
35
+ this.exitCode = options.exitCode ?? EXIT.failed;
36
+ this.code = options.code ?? (this.exitCode === EXIT.usage ? "usage" : "failed");
37
+ this.details = options.details;
38
+ }
39
+ }
40
+
41
+ /** A usage error (exit 64). */
42
+ export function usageError(message: string): CliError {
43
+ return new CliError(message, { exitCode: EXIT.usage, code: "usage" });
7
44
  }
8
45
 
9
46
  function isDirectory(p: string): boolean {
@@ -48,7 +85,10 @@ export function decoPaths(root: string) {
48
85
  blocks: path.join(deco, "blocks"),
49
86
  schema: path.join(deco, "schema.gen.json"),
50
87
  legacySchema: path.join(deco, "meta.gen.json"),
88
+ /** The content module, `.deco/blocks.gen.ts`, for content without a site. */
51
89
  content: path.join(deco, "blocks.gen.ts"),
90
+ /** What `deco pull` wrote, git-ignored: the base of `deco diff` and `deco push`. */
91
+ pull: path.join(deco, "pull.json"),
52
92
  blockMapCandidates: [path.join(deco, "index.ts"), path.join(deco, "index.tsx")],
53
93
  };
54
94
  }