@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,345 @@
1
+ /**
2
+ * `blocks.apply`: atomic set and delete, set precedence, validation, the
3
+ * file-name rule and preconditions.
4
+ */
5
+ import { ErrorCode, type InvalidBlockData } from "../../errors";
6
+ import type { BlocksListResult } from "../../types";
7
+ import { assert, assertEqual, type ConformanceContext, expectError } from "../context";
8
+ import type { ConformanceCase } from "./types";
9
+
10
+ type FullList = Extract<BlocksListResult, { notModified: false }>;
11
+
12
+ async function list(ctx: ConformanceContext): Promise<FullList> {
13
+ const result = await ctx.client.blocksList();
14
+ assert(!result.notModified, "an unconditional list returns the map");
15
+ return result;
16
+ }
17
+
18
+ async function writable(ctx: ConformanceContext) {
19
+ const d = await ctx.describe();
20
+ if (d.readOnly) return ctx.skip("read-only endpoint");
21
+ return d;
22
+ }
23
+
24
+ function violations(error: { data: unknown }): InvalidBlockData["violations"] {
25
+ const data = error.data as InvalidBlockData | undefined;
26
+ assert(Array.isArray(data?.violations), "InvalidBlock carries data.violations");
27
+ return data!.violations;
28
+ }
29
+
30
+ export const writeCases: ConformanceCase[] = [
31
+ {
32
+ id: "apply/create-and-read",
33
+ title: "a write returns versions and a revision that blocks.list then reports",
34
+ async run(ctx) {
35
+ await writable(ctx);
36
+ const name = ctx.name("create");
37
+ const value = { __resolveType: "hero", title: "Olá — 世界", items: [1, { a: null }] };
38
+ const result = await ctx.client.blocksApply({ set: { [name]: value } });
39
+ assert(typeof result.revision === "string", "a revision");
40
+ assert(typeof result.versions[name] === "string", "a version for the entry");
41
+ const after = await list(ctx);
42
+ assertEqual(after.blocks[name], value, "the stored entry");
43
+ assertEqual(after.versions[name], result.versions[name], "the listed version");
44
+ assertEqual(after.revision, result.revision, "the listed revision");
45
+ const poll = await ctx.client.blocksList({ ifNoneMatch: result.revision });
46
+ assert(poll.notModified, "polling with the returned revision is 'not modified'");
47
+ },
48
+ },
49
+ {
50
+ id: "apply/atomic-set-delete",
51
+ title: "set and delete land together",
52
+ async run(ctx) {
53
+ await writable(ctx);
54
+ const [a, b, c] = [ctx.name("a"), ctx.name("b"), ctx.name("c")];
55
+ await ctx.client.blocksApply({ set: { [a]: { v: 1 }, [b]: { v: 2 } } });
56
+ const result = await ctx.client.blocksApply({ set: { [c]: { v: 3 } }, delete: [a] });
57
+ assertEqual(result.versions[a], null, "a deleted entry's version is null");
58
+ const after = await list(ctx);
59
+ assert(!(a in after.blocks), "the deleted entry is gone");
60
+ assertEqual(after.blocks[b], { v: 2 }, "the untouched entry stays");
61
+ assertEqual(after.blocks[c], { v: 3 }, "the new entry exists");
62
+ },
63
+ },
64
+ {
65
+ id: "apply/set-wins",
66
+ title: "set wins when a name is in both set and delete",
67
+ async run(ctx) {
68
+ await writable(ctx);
69
+ const name = ctx.name("both");
70
+ const result = await ctx.client.blocksApply({
71
+ set: { [name]: { kept: true } },
72
+ delete: [name],
73
+ });
74
+ assert(typeof result.versions[name] === "string", "the entry has a version");
75
+ assertEqual((await list(ctx)).blocks[name], { kept: true }, "the entry exists");
76
+ },
77
+ },
78
+ {
79
+ id: "apply/delete-missing",
80
+ title: "deleting a missing name counts as deleted",
81
+ async run(ctx) {
82
+ await writable(ctx);
83
+ const name = ctx.name("missing");
84
+ const result = await ctx.client.blocksApply({ delete: [name] });
85
+ assertEqual(result.versions, { [name]: null }, "versions");
86
+ },
87
+ },
88
+ {
89
+ id: "apply/whole-entry-replace",
90
+ title: "set replaces the whole entry (no merge)",
91
+ async run(ctx) {
92
+ await writable(ctx);
93
+ const name = ctx.name("replace");
94
+ await ctx.client.blocksApply({ set: { [name]: { a: 1, b: 2 } } });
95
+ await ctx.client.blocksApply({ set: { [name]: { b: 3 } } });
96
+ assertEqual((await list(ctx)).blocks[name], { b: 3 }, "the entry");
97
+ },
98
+ },
99
+ {
100
+ id: "apply/all-or-nothing-validation",
101
+ title: "every violation is reported at once and nothing is written",
102
+ async run(ctx) {
103
+ await writable(ctx);
104
+ const good = ctx.name("good");
105
+ const error = await expectError(
106
+ ctx.client.blocksApply({
107
+ set: {
108
+ [good]: { ok: true },
109
+ [ctx.name("array")]: [] as never,
110
+ [ctx.name("null")]: null as never,
111
+ },
112
+ }),
113
+ ErrorCode.InvalidBlock,
114
+ "invalid values",
115
+ );
116
+ assertEqual(violations(error).length, 2, "one violation per invalid entry");
117
+ assert(!(good in (await list(ctx)).blocks), "the valid entry wasn't written");
118
+ },
119
+ },
120
+ {
121
+ id: "apply/name-rules",
122
+ title: "names the site editor can't save are refused",
123
+ async run(ctx) {
124
+ await writable(ctx);
125
+ const p = ctx.prefix;
126
+ const bad = [
127
+ "",
128
+ `${p}\\x`,
129
+ `${p}..x`,
130
+ "CON",
131
+ "con.backup",
132
+ "__proto__",
133
+ `${p}-mod.ts`,
134
+ `${p}-mod.tsx`,
135
+ `.${p}-hidden`,
136
+ ".",
137
+ ];
138
+ bad.push(`${p}-${"é".repeat(60)}`); // 360 encoded bytes
139
+ for (const name of bad) {
140
+ const error = await expectError(
141
+ ctx.client.blocksApply({ set: { [name]: { x: 1 } } }),
142
+ ErrorCode.InvalidBlock,
143
+ `the name ${JSON.stringify(name)}`,
144
+ );
145
+ assert(
146
+ violations(error).some((v) => v.name === name),
147
+ `a violation names ${JSON.stringify(name)}`,
148
+ );
149
+ }
150
+ // A name ending in a source extension can still be deleted.
151
+ const result = await ctx.client.blocksApply({ delete: [`${p}-mod.ts`] });
152
+ assertEqual(result.versions, { [`${p}-mod.ts`]: null }, "deleting a .ts name");
153
+ },
154
+ },
155
+ {
156
+ id: "apply/case-collision",
157
+ title: "a new name that differs from another entry's only in letter case is refused",
158
+ async run(ctx) {
159
+ await writable(ctx);
160
+ const name = ctx.name("CaseName");
161
+ await ctx.client.blocksApply({ set: { [name]: { v: 1 } } });
162
+ await expectError(
163
+ ctx.client.blocksApply({ set: { [name.toLowerCase()]: { v: 2 } } }),
164
+ ErrorCode.InvalidBlock,
165
+ "a case variant",
166
+ );
167
+ await ctx.client.blocksApply({ set: { [name]: { v: 3 } } });
168
+ assertEqual((await list(ctx)).blocks[name], { v: 3 }, "updating the existing name");
169
+ },
170
+ },
171
+ {
172
+ id: "apply/spellings",
173
+ title:
174
+ "two spellings of one name are one entry: guards see either, and a write keeps only the written spelling",
175
+ async run(ctx) {
176
+ await writable(ctx);
177
+ const encoded = `${ctx.prefix}-Home%20Page`;
178
+ const literal = `${ctx.prefix}-Home Page`;
179
+ ctx.track(encoded);
180
+ ctx.track(literal);
181
+ await expectError(
182
+ ctx.client.blocksApply({ set: { [encoded]: { v: 1 }, [literal]: { v: 2 } } }),
183
+ ErrorCode.InvalidBlock,
184
+ "both spellings in one write",
185
+ );
186
+ const created = await ctx.client.blocksApply({ set: { [encoded]: { v: 1 } } });
187
+ // Create-only under another spelling: the entry exists, so the guard fails.
188
+ const error = await expectError(
189
+ ctx.client.blocksApply({ set: { [literal]: { v: 2 } }, ifMatch: { [literal]: null } }),
190
+ ErrorCode.Conflict,
191
+ "create-only on another spelling of an existing entry",
192
+ );
193
+ assertEqual(
194
+ (error.data as { entries?: unknown }).entries,
195
+ { [literal]: { expected: null, actual: created.versions[encoded] } },
196
+ "the conflict reports the existing spelling's version",
197
+ );
198
+ assertEqual((await list(ctx)).blocks[encoded], { v: 1 }, "nothing was deleted");
199
+ // A guard on one spelling holds for the other.
200
+ const written = await ctx.client.blocksApply({
201
+ set: { [literal]: { v: 2 } },
202
+ ifMatch: { [literal]: created.versions[encoded]! },
203
+ });
204
+ assertEqual(
205
+ written.versions[encoded],
206
+ null,
207
+ "the result reports the deleted spelling as gone, so a client's map drops it",
208
+ );
209
+ assert(typeof written.versions[literal] === "string", "the written spelling has a version");
210
+ const after = await list(ctx);
211
+ assertEqual(after.blocks[literal], { v: 2 }, "the written spelling");
212
+ assert(!(encoded in after.blocks), "the other spelling was deleted in the same commit");
213
+ assert(
214
+ !after.diagnostics.some((d) => d.name === literal || d.name === encoded),
215
+ "no shadowed spelling is left",
216
+ );
217
+ },
218
+ },
219
+ {
220
+ id: "apply/if-match",
221
+ title: "ifMatch guards a write; a failed guard writes nothing and reports versions",
222
+ async run(ctx) {
223
+ await writable(ctx);
224
+ const name = ctx.name("guarded");
225
+ const other = ctx.name("other");
226
+ const created = await ctx.client.blocksApply({
227
+ set: { [name]: { v: 1 } },
228
+ ifMatch: { [name]: null },
229
+ });
230
+ const v1 = created.versions[name]!;
231
+ const error = await expectError(
232
+ ctx.client.blocksApply({
233
+ set: { [name]: { v: 2 }, [other]: { v: 2 } },
234
+ ifMatch: { [name]: `${v1}x` },
235
+ }),
236
+ ErrorCode.Conflict,
237
+ "a stale version",
238
+ );
239
+ assertEqual(
240
+ (error.data as { entries?: unknown }).entries,
241
+ { [name]: { expected: `${v1}x`, actual: v1 } },
242
+ "the conflict's versions",
243
+ );
244
+ const after = await list(ctx);
245
+ assertEqual(after.blocks[name], { v: 1 }, "the guarded entry is unchanged");
246
+ assert(!(other in after.blocks), "nothing else was written");
247
+ await expectError(
248
+ ctx.client.blocksApply({ set: { [name]: { v: 3 } }, ifMatch: { [name]: null } }),
249
+ ErrorCode.Conflict,
250
+ "create-only on an existing entry",
251
+ );
252
+ const updated = await ctx.client.blocksApply({
253
+ set: { [name]: { v: 4 } },
254
+ ifMatch: { [name]: v1 },
255
+ });
256
+ assert(updated.versions[name] !== v1, "a matching version writes");
257
+ },
258
+ },
259
+ {
260
+ id: "apply/rename-recipe",
261
+ title: "renaming is a set plus a delete, create-only on the new name",
262
+ async run(ctx) {
263
+ await writable(ctx);
264
+ const from = ctx.name("from");
265
+ const to = ctx.name("to");
266
+ const created = await ctx.client.blocksApply({ set: { [from]: { v: 1 } } });
267
+ await ctx.client.blocksApply({
268
+ set: { [to]: { v: 1 } },
269
+ delete: [from],
270
+ ifMatch: { [to]: null, [from]: created.versions[from]! },
271
+ });
272
+ const after = await list(ctx);
273
+ assert(!(from in after.blocks) && to in after.blocks, "the entry moved");
274
+ },
275
+ },
276
+ {
277
+ id: "apply/schema-precondition",
278
+ title: "ifSchemaMatch rejects a write when the schema changed",
279
+ async run(ctx) {
280
+ const d = await writable(ctx);
281
+ const name = ctx.name("schema-guarded");
282
+ if (!d.writes.schemaPreconditions) {
283
+ await expectError(
284
+ ctx.client.blocksApply({ set: { [name]: {} }, ifSchemaMatch: "x" }),
285
+ ErrorCode.Unsupported,
286
+ "an unadvertised guard",
287
+ );
288
+ return;
289
+ }
290
+ if (ctx.options.hasSchema === false) return ctx.skip("no schema");
291
+ const { version } = await ctx.client.schemaGet();
292
+ const error = await expectError(
293
+ ctx.client.blocksApply({ set: { [name]: {} }, ifSchemaMatch: `${version}-old` }),
294
+ ErrorCode.Conflict,
295
+ "a stale schema version",
296
+ );
297
+ assertEqual(
298
+ (error.data as { schema?: unknown }).schema,
299
+ { expected: `${version}-old`, actual: version },
300
+ "the conflict's schema versions",
301
+ );
302
+ assert(!(name in (await list(ctx)).blocks), "nothing was written");
303
+ await ctx.client.blocksApply({ set: { [name]: {} }, ifSchemaMatch: version });
304
+ },
305
+ },
306
+ {
307
+ id: "apply/unknown-params",
308
+ title: "an unknown parameter is refused, so an unknown guard never becomes an unguarded write",
309
+ async run(ctx) {
310
+ await writable(ctx);
311
+ const name = ctx.name("unknown-param");
312
+ await expectError(
313
+ ctx.client.call("blocks.apply", { set: { [name]: {} }, ifUnmodifiedSince: "x" } as never),
314
+ ErrorCode.InvalidParams,
315
+ "an unknown guard",
316
+ );
317
+ assert(!(name in (await list(ctx)).blocks), "nothing was written");
318
+ },
319
+ },
320
+ {
321
+ id: "apply/read-only",
322
+ title: "a write to a read-only endpoint is ReadOnly",
323
+ async run(ctx) {
324
+ const d = await ctx.describe();
325
+ if (!d.readOnly) return ctx.skip("the endpoint accepts writes");
326
+ await expectError(ctx.client.blocksApply({ delete: ["x"] }), ErrorCode.ReadOnly, "a write");
327
+ },
328
+ },
329
+ {
330
+ id: "apply/last-writer-wins",
331
+ title: "without guards, the later of two writes wins",
332
+ async run(ctx) {
333
+ await writable(ctx);
334
+ const name = ctx.name("lww");
335
+ await Promise.all([
336
+ ctx.client.blocksApply({ set: { [name]: { from: "a" } } }),
337
+ ctx.client.blocksApply({ set: { [name]: { from: "b" } } }),
338
+ ]);
339
+ const value = (await list(ctx)).blocks[name] as { from: string };
340
+ assert(value.from === "a" || value.from === "b", "one of the writes is stored whole");
341
+ await ctx.client.blocksApply({ set: { [name]: { from: "c" } } });
342
+ assertEqual((await list(ctx)).blocks[name], { from: "c" }, "the latest write");
343
+ },
344
+ },
345
+ ];
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Golden fixtures for canonical content hashing: every implementation that
3
+ * computes a content revision (the CLI, the release materializer, the site
4
+ * editor's backend) checks it produces these exact bytes and hashes.
5
+ *
6
+ * ```ts
7
+ * import { contentHashFixtures } from "@decocms/blocks/protocol/conformance";
8
+ * for (const f of contentHashFixtures) expect(await myRevision(f.blocks)).toBe(f.revision);
9
+ * ```
10
+ */
11
+
12
+ export interface ContentHashFixture {
13
+ id: string;
14
+ title: string;
15
+ /** The `blocks` map: entry name to entry. */
16
+ blocks: Record<string, unknown>;
17
+ /** Its canonical JSON. */
18
+ canonical: string;
19
+ /** SHA-256 of the canonical JSON's UTF-8 bytes, lowercase hex. */
20
+ revision: string;
21
+ }
22
+
23
+ export const contentHashFixtures: readonly ContentHashFixture[] = [
24
+ {
25
+ id: "empty",
26
+ title: "an empty map",
27
+ blocks: {},
28
+ canonical: "{}",
29
+ revision: "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
30
+ },
31
+ {
32
+ id: "key-order",
33
+ title:
34
+ "keys sorted recursively in code-unit order, numeric-looking keys included; arrays keep their order",
35
+ blocks: { b: { z: 1, a: 2 }, a: [3, 1, 2], B: true, "10": "ten", "2": "two", "": null },
36
+ canonical: '{"":null,"10":"ten","2":"two","B":true,"a":[3,1,2],"b":{"a":2,"z":1}}',
37
+ revision: "e10ffc5fe1399986d69ff6a5c326d3eca5a4c6ff4134504d2e169676e1155e52",
38
+ },
39
+ {
40
+ id: "strings",
41
+ title: "JSON string escaping: control characters escaped, non-ASCII and line separators as is",
42
+ blocks: {
43
+ s: {
44
+ text: "Ol\u00e1 \u2014 \u4e16\u754c \ud83d\ude00",
45
+ quote: '"\\/',
46
+ control: "\u0000\u001f\n\t",
47
+ separators: "\u2028\u2029",
48
+ },
49
+ },
50
+ canonical:
51
+ '{"s":{"control":"\\u0000\\u001f\\n\\t","quote":"\\"\\\\/","separators":"\u2028\u2029","text":"Ol\u00e1 \u2014 \u4e16\u754c \ud83d\ude00"}}',
52
+ revision: "3dbb4dd183b625c383b703df94c2d12ae6271cad0ee7e63c51cf1bfda18c799c",
53
+ },
54
+ {
55
+ id: "numbers",
56
+ title: "JSON number encoding, negative zero as zero",
57
+ blocks: {
58
+ n: { zero: -0, int: 42, neg: -7, frac: 0.1, big: 1e21, small: 1e-7, max: 9007199254740991 },
59
+ },
60
+ canonical:
61
+ '{"n":{"big":1e+21,"frac":0.1,"int":42,"max":9007199254740991,"neg":-7,"small":1e-7,"zero":0}}',
62
+ revision: "783d90091668991414259155fb6b37ae5f09afc80a3aea62405fbe515bac535c",
63
+ },
64
+ {
65
+ id: "page",
66
+ title: "a small site",
67
+ blocks: {
68
+ "pages-Home": {
69
+ __resolveType: "page",
70
+ path: "/",
71
+ sections: [{ __resolveType: "hero", title: "Hi" }],
72
+ },
73
+ Header: { __resolveType: "header", links: [] },
74
+ },
75
+ canonical:
76
+ '{"Header":{"__resolveType":"header","links":[]},"pages-Home":{"__resolveType":"page","path":"/","sections":[{"__resolveType":"hero","title":"Hi"}]}}',
77
+ revision: "6913c5e6aa28f441d3b0102177b372e4fb7c08bc09bdd8698df85e597282ac96",
78
+ },
79
+ ];
@@ -0,0 +1,222 @@
1
+ /**
2
+ * What every conformance case gets: a client, raw HTTP access, the endpoint's
3
+ * `describe`, unique names and assertion helpers.
4
+ */
5
+ import { canonicalJson } from "../canonical";
6
+ import { type ContentClient, createContentClient, readResponseJson } from "../client";
7
+ import { ContentProtocolError } from "../errors";
8
+ import type { DescribeResult } from "../types";
9
+
10
+ export interface ConformanceOptions {
11
+ /** The endpoint URL, such as `http://127.0.0.1:4545/rpc`. */
12
+ endpoint: string | URL;
13
+ /** The bearer token the endpoint expects, if any. */
14
+ token?: string;
15
+ /** Extra headers on every request (an auth cookie, a tenant header). */
16
+ headers?: Record<string, string>;
17
+ /** A fetch implementation (defaults to the global one); use it to call a handler in process. */
18
+ fetch?: (request: Request) => Promise<Response>;
19
+ /**
20
+ * A block type in the endpoint's schema with a `Secret` field, so the
21
+ * secret guard can be checked. Leave out to skip those cases.
22
+ */
23
+ secretField?: { blockType: string; field: string };
24
+ /** The `.deco/secrets.pub` content the endpoint should report, if the harness wrote one. */
25
+ secretsPublicKey?: string;
26
+ /** Whether the endpoint has a schema (default true). `false` checks NotFound instead. */
27
+ hasSchema?: boolean;
28
+ /**
29
+ * The endpoint serves a schema larger than its `limits.maxSchemaBytes`, so
30
+ * reading it and writes that depend on it must be LimitExceeded. Run such
31
+ * an endpoint with only the `limits/schema-bytes` case (pass a filter to
32
+ * `runConformance` or `defineConformanceSuite`): every other case expects
33
+ * a schema it can read.
34
+ */
35
+ schemaOverLimit?: boolean;
36
+ /**
37
+ * The URL prefix uploads are served under (`PUT <assetsEndpoint><name>`),
38
+ * such as `http://127.0.0.1:4545/assets/`. Leave out to skip the upload cases.
39
+ */
40
+ assetsEndpoint?: string | URL;
41
+ /**
42
+ * Restarts the server, keeping its durable state, to check that request-key
43
+ * receipts survive a restart. Leave out to skip that case.
44
+ */
45
+ restart?: () => Promise<void>;
46
+ /** Credentials of another tenant on the same storage, to check receipt isolation. */
47
+ otherTenant?: { token?: string; headers?: Record<string, string> };
48
+ /** Prefix of every name the suite creates (default `conformance-<random>`). */
49
+ namePrefix?: string;
50
+ }
51
+
52
+ /** Thrown by `ctx.skip()`: the case doesn't apply to this endpoint. */
53
+ export class SkipCase extends Error {
54
+ constructor(reason: string) {
55
+ super(reason);
56
+ this.name = "SkipCase";
57
+ }
58
+ }
59
+
60
+ export class ConformanceFailure extends Error {
61
+ constructor(message: string) {
62
+ super(message);
63
+ this.name = "ConformanceFailure";
64
+ }
65
+ }
66
+
67
+ export interface RawResponse {
68
+ status: number;
69
+ headers: Headers;
70
+ body: unknown;
71
+ }
72
+
73
+ export class ConformanceContext {
74
+ readonly client: ContentClient;
75
+ private counter = 0;
76
+ private readonly created = new Set<string>();
77
+ private describeResult: DescribeResult | undefined;
78
+
79
+ constructor(
80
+ readonly options: ConformanceOptions,
81
+ readonly prefix: string,
82
+ ) {
83
+ this.client = createContentClient(options);
84
+ }
85
+
86
+ /** A client with other credentials (for tenant isolation). */
87
+ clientFor(credentials: { token?: string; headers?: Record<string, string> }): ContentClient {
88
+ return createContentClient({ ...this.options, ...credentials });
89
+ }
90
+
91
+ async describe(): Promise<DescribeResult> {
92
+ this.describeResult ??= await this.client.describe();
93
+ return this.describeResult;
94
+ }
95
+
96
+ /** A fresh name the suite owns; it's deleted when the case ends. */
97
+ name(label = "entry"): string {
98
+ const name = `${this.prefix}-${label}-${++this.counter}`;
99
+ this.created.add(name);
100
+ return name;
101
+ }
102
+
103
+ /** Marks a name the case created by other means for cleanup. */
104
+ track(name: string): void {
105
+ this.created.add(name);
106
+ }
107
+
108
+ /** Deletes every name the case created. */
109
+ async cleanup(): Promise<void> {
110
+ if (this.created.size === 0) return;
111
+ const names = [...this.created];
112
+ this.created.clear();
113
+ const description = await this.describe();
114
+ if (description.readOnly) return;
115
+ for (let i = 0; i < names.length; i += description.limits.maxOpsPerApply) {
116
+ await this.client
117
+ .blocksApply({ delete: names.slice(i, i + description.limits.maxOpsPerApply) })
118
+ .catch(() => {});
119
+ }
120
+ }
121
+
122
+ skip(reason: string): never {
123
+ throw new SkipCase(reason);
124
+ }
125
+
126
+ /** Posts a raw body to the endpoint and decodes the JSON answer. */
127
+ async raw(
128
+ body: string | Uint8Array,
129
+ init: { method?: string; headers?: Record<string, string> } = {},
130
+ ): Promise<RawResponse> {
131
+ const headers: Record<string, string> = {
132
+ "content-type": "application/json",
133
+ ...this.options.headers,
134
+ ...init.headers,
135
+ };
136
+ if (this.options.token !== undefined && !("authorization" in headers)) {
137
+ headers.authorization = `Bearer ${this.options.token}`;
138
+ }
139
+ for (const [key, value] of Object.entries(headers)) if (value === "") delete headers[key];
140
+ const method = init.method ?? "POST";
141
+ const doFetch = this.options.fetch ?? ((request: Request) => fetch(request));
142
+ const response = await doFetch(
143
+ new Request(this.options.endpoint, {
144
+ method,
145
+ headers,
146
+ body: method === "GET" || method === "HEAD" ? undefined : (body as BodyInit),
147
+ }),
148
+ );
149
+ let parsed: unknown = null;
150
+ try {
151
+ parsed = await readResponseJson(response);
152
+ } catch {
153
+ parsed = null;
154
+ }
155
+ return { status: response.status, headers: response.headers, body: parsed };
156
+ }
157
+
158
+ /** Uploads `body` as `PUT <assetsEndpoint><name>`, with the endpoint's credentials. */
159
+ async upload(name: string, body: Uint8Array | string, contentType: string): Promise<RawResponse> {
160
+ const base = this.options.assetsEndpoint;
161
+ if (base === undefined) return this.skip("no assetsEndpoint");
162
+ const headers: Record<string, string> = {
163
+ ...this.options.headers,
164
+ "content-type": contentType,
165
+ };
166
+ if (this.options.token !== undefined) headers.authorization = `Bearer ${this.options.token}`;
167
+ const doFetch = this.options.fetch ?? ((request: Request) => fetch(request));
168
+ const url = new URL(encodeURIComponent(name), new URL(String(base)).href.replace(/\/?$/, "/"));
169
+ const response = await doFetch(
170
+ new Request(url, { method: "PUT", headers, body: body as BodyInit }),
171
+ );
172
+ let parsed: unknown = null;
173
+ try {
174
+ parsed = await readResponseJson(response);
175
+ } catch {
176
+ parsed = null;
177
+ }
178
+ return { status: response.status, headers: response.headers, body: parsed };
179
+ }
180
+
181
+ /** Posts one JSON-RPC payload (an object or a batch) as JSON. */
182
+ rpc(payload: unknown, headers?: Record<string, string>): Promise<RawResponse> {
183
+ return this.raw(JSON.stringify(payload), { headers });
184
+ }
185
+ }
186
+
187
+ export function assert(condition: unknown, message: string): asserts condition {
188
+ if (!condition) throw new ConformanceFailure(message);
189
+ }
190
+
191
+ export function assertEqual(actual: unknown, expected: unknown, message: string): void {
192
+ const a = canonicalJson(actual ?? null);
193
+ const e = canonicalJson(expected ?? null);
194
+ if (a !== e) throw new ConformanceFailure(`${message}\n expected: ${e}\n actual: ${a}`);
195
+ }
196
+
197
+ /** Awaits `promise` and checks it fails with protocol error `code`. */
198
+ export async function expectError(
199
+ promise: Promise<unknown>,
200
+ code: number,
201
+ message: string,
202
+ ): Promise<ContentProtocolError> {
203
+ try {
204
+ await promise;
205
+ } catch (error) {
206
+ if (error instanceof ContentProtocolError) {
207
+ assert(
208
+ error.code === code,
209
+ `${message}: expected error ${code}, got ${error.code} (${error.message})`,
210
+ );
211
+ return error;
212
+ }
213
+ throw error;
214
+ }
215
+ throw new ConformanceFailure(`${message}: expected error ${code}, but the call succeeded`);
216
+ }
217
+
218
+ /** The JSON-RPC error code of a raw response body, if it carries one. */
219
+ export function rawErrorCode(body: unknown): number | undefined {
220
+ const error = (body as { error?: { code?: unknown } } | null)?.error;
221
+ return typeof error?.code === "number" ? error.code : undefined;
222
+ }