@decocms/blocks 8.0.0 → 8.1.0-next.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 (175) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +39 -3
  3. package/src/cms/applySectionConventions.ts +26 -2
  4. package/src/cms/blockSource.ts +37 -0
  5. package/src/cms/client.ts +5 -0
  6. package/src/cms/deferredTrigger.ts +58 -0
  7. package/src/cms/draftSource.ts +171 -57
  8. package/src/cms/index.ts +32 -3
  9. package/src/cms/loader.ts +318 -59
  10. package/src/cms/registry.ts +22 -0
  11. package/src/cms/renderJson.ts +179 -0
  12. package/src/cms/resolve.ts +396 -95
  13. package/src/cms/schema.ts +9 -5
  14. package/src/cms/sectionLoaders.ts +106 -56
  15. package/src/hooks/Image.tsx +70 -6
  16. package/src/hooks/LiveControls.tsx +30 -8
  17. package/src/hooks/Stats.tsx +134 -0
  18. package/src/hooks/index.ts +5 -0
  19. package/src/hooks/useLoadMore.ts +100 -0
  20. package/src/index.ts +37 -0
  21. package/src/middleware/observability.ts +173 -16
  22. package/src/preview/DraftPreviewBadge.tsx +306 -0
  23. package/src/preview/decoMark.ts +11 -0
  24. package/src/preview/index.ts +8 -0
  25. package/src/protocol/assets.ts +124 -0
  26. package/src/protocol/canonical.ts +7 -0
  27. package/src/protocol/ciphertext.ts +6 -0
  28. package/src/protocol/client.ts +170 -0
  29. package/src/protocol/conformance/cases/assets.ts +81 -0
  30. package/src/protocol/conformance/cases/guards.ts +314 -0
  31. package/src/protocol/conformance/cases/reads.ts +168 -0
  32. package/src/protocol/conformance/cases/types.ts +9 -0
  33. package/src/protocol/conformance/cases/wire.ts +138 -0
  34. package/src/protocol/conformance/cases/writes.ts +345 -0
  35. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  36. package/src/protocol/conformance/context.ts +222 -0
  37. package/src/protocol/conformance/index.ts +140 -0
  38. package/src/protocol/errors.ts +142 -0
  39. package/src/protocol/index.ts +39 -0
  40. package/src/protocol/keys.ts +279 -0
  41. package/src/protocol/params.ts +67 -0
  42. package/src/protocol/secrets.ts +231 -0
  43. package/src/protocol/server/assets.ts +119 -0
  44. package/src/protocol/server/auth.ts +49 -0
  45. package/src/protocol/server/bodyCache.ts +84 -0
  46. package/src/protocol/server/content.ts +175 -0
  47. package/src/protocol/server/core.ts +112 -0
  48. package/src/protocol/server/handler.ts +102 -0
  49. package/src/protocol/server/http.ts +139 -0
  50. package/src/protocol/server/index.ts +11 -0
  51. package/src/protocol/server/methods/apply.ts +341 -0
  52. package/src/protocol/server/methods/read.ts +156 -0
  53. package/src/protocol/server/rpc.ts +136 -0
  54. package/src/protocol/storage/fs/hash.ts +21 -0
  55. package/src/protocol/storage/fs/index.ts +338 -0
  56. package/src/protocol/storage/fs/lock.ts +68 -0
  57. package/src/protocol/storage/fs/transaction.ts +183 -0
  58. package/src/protocol/storage/fs/unsupported.ts +15 -0
  59. package/src/protocol/storage/memory.ts +238 -0
  60. package/src/protocol/storage.ts +182 -0
  61. package/src/protocol/types.ts +172 -0
  62. package/src/sdk/abTesting.ts +60 -3
  63. package/src/sdk/analytics.ts +72 -2
  64. package/src/sdk/cacheHeaders.ts +210 -10
  65. package/src/sdk/cacheStorage.ts +287 -0
  66. package/src/sdk/cachedLoader.ts +143 -90
  67. package/src/sdk/crypto.ts +16 -2
  68. package/src/sdk/deepOmit.ts +52 -0
  69. package/src/sdk/encoding.ts +2 -5
  70. package/src/sdk/experiments.ts +314 -0
  71. package/src/sdk/fetchCache.ts +269 -0
  72. package/src/sdk/fetchTimeout.ts +58 -0
  73. package/src/sdk/flags.ts +38 -8
  74. package/src/sdk/index.ts +7 -0
  75. package/src/sdk/instrumentedFetch.ts +25 -2
  76. package/src/sdk/nonce.ts +46 -0
  77. package/src/sdk/normalizeUrls.ts +2 -2
  78. package/src/sdk/observability.ts +8 -1
  79. package/src/sdk/otel.ts +131 -25
  80. package/src/sdk/otelHttpLog.ts +4 -4
  81. package/src/sdk/otelHttpMeter.ts +39 -13
  82. package/src/sdk/otelHttpTracer.ts +4 -4
  83. package/src/sdk/redirects.ts +113 -5
  84. package/src/sdk/responseCache.ts +82 -0
  85. package/src/sdk/urlUtils.ts +49 -0
  86. package/src/sdk/useSuggestions.ts +1 -1
  87. package/src/v8/analytics.ts +50 -0
  88. package/src/v8/background.ts +107 -0
  89. package/src/v8/builtins/data.ts +23 -0
  90. package/src/v8/builtins/index.ts +26 -0
  91. package/src/v8/builtins/lazy.ts +23 -0
  92. package/src/v8/builtins/legacy.ts +65 -0
  93. package/src/v8/builtins/matchers.ts +31 -0
  94. package/src/v8/builtins/multivariate.ts +25 -0
  95. package/src/v8/builtins/secret.ts +82 -0
  96. package/src/v8/canonical.ts +117 -0
  97. package/src/v8/ciphertext.ts +158 -0
  98. package/src/v8/cli/builtins.ts +20 -0
  99. package/src/v8/cli/check/index.ts +774 -0
  100. package/src/v8/cli/check/messages.ts +168 -0
  101. package/src/v8/cli/content.ts +287 -0
  102. package/src/v8/cli/index.ts +17 -0
  103. package/src/v8/cli/log.ts +18 -0
  104. package/src/v8/cli/main.ts +12 -0
  105. package/src/v8/cli/root.ts +66 -0
  106. package/src/v8/cli/run.ts +236 -0
  107. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  108. package/src/v8/cli/schema/generate.ts +507 -0
  109. package/src/v8/cli/schema/index.ts +63 -0
  110. package/src/v8/cli/schema/tsProgram.ts +497 -0
  111. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  112. package/src/v8/cli/serve/server.ts +303 -0
  113. package/src/v8/cli/watch.ts +86 -0
  114. package/src/v8/client.ts +147 -0
  115. package/src/v8/cms.ts +237 -0
  116. package/src/v8/content.ts +195 -0
  117. package/src/v8/draft.ts +136 -0
  118. package/src/v8/errors.ts +59 -0
  119. package/src/v8/fetch.ts +152 -0
  120. package/src/v8/identity.ts +65 -0
  121. package/src/v8/index.ts +39 -0
  122. package/src/v8/json.ts +74 -0
  123. package/src/v8/matchRoute.ts +204 -0
  124. package/src/v8/remoteLoader.ts +282 -0
  125. package/src/v8/resolver.ts +278 -0
  126. package/src/v8/secrets.ts +17 -0
  127. package/src/v8/telemetry.ts +533 -0
  128. package/src/v8/types.ts +240 -0
  129. package/src/cms/blockSource.test.ts +0 -76
  130. package/src/cms/client.browserBundle.test.ts +0 -44
  131. package/src/cms/draftSource.test.ts +0 -343
  132. package/src/cms/layoutCacheRace.test.ts +0 -181
  133. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  134. package/src/cms/loader.test.ts +0 -200
  135. package/src/cms/registry.test.ts +0 -110
  136. package/src/cms/resolve.test.ts +0 -980
  137. package/src/cms/schema.test.ts +0 -356
  138. package/src/cms/sectionLoaderContext.test.ts +0 -111
  139. package/src/cms/sectionLoaders.test.ts +0 -533
  140. package/src/cms/sectionMixins.test.ts +0 -167
  141. package/src/cms/stickyFlags.test.ts +0 -117
  142. package/src/flags/flags.test.ts +0 -148
  143. package/src/hooks/Image.test.ts +0 -100
  144. package/src/hooks/RenderSection.test.tsx +0 -81
  145. package/src/matchers/builtins.test.ts +0 -318
  146. package/src/matchers/override.test.ts +0 -205
  147. package/src/middleware/hydrationContext.test.ts +0 -61
  148. package/src/middleware/observability.test.ts +0 -242
  149. package/src/middleware/validateSection.test.ts +0 -147
  150. package/src/sdk/abTesting.test.ts +0 -326
  151. package/src/sdk/cacheHeaders.test.ts +0 -115
  152. package/src/sdk/cachedLoader.test.ts +0 -122
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/cn.test.ts +0 -34
  155. package/src/sdk/composite.test.ts +0 -121
  156. package/src/sdk/cookie.test.ts +0 -108
  157. package/src/sdk/encoding.test.ts +0 -71
  158. package/src/sdk/env.test.ts +0 -33
  159. package/src/sdk/flags.test.ts +0 -91
  160. package/src/sdk/http.test.ts +0 -71
  161. package/src/sdk/inflightTimeout.test.ts +0 -35
  162. package/src/sdk/instrumentedFetch.test.ts +0 -559
  163. package/src/sdk/invoke.test.ts +0 -115
  164. package/src/sdk/logger.test.ts +0 -432
  165. package/src/sdk/otel.test.ts +0 -526
  166. package/src/sdk/otelAdapters.test.ts +0 -89
  167. package/src/sdk/otelHttpLog.test.ts +0 -457
  168. package/src/sdk/otelHttpMeter.test.ts +0 -292
  169. package/src/sdk/otelHttpTracer.test.ts +0 -474
  170. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  171. package/src/sdk/urlRedaction.test.ts +0 -73
  172. package/src/sdk/useDevice.test.ts +0 -130
  173. package/src/sdk/useScript.test.ts +0 -128
  174. package/src/sdk/useSuggestions.test.ts +0 -230
  175. package/tsconfig.json +0 -7
@@ -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
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * `@decocms/blocks/protocol/conformance`: a black-box test suite any
3
+ * content-protocol endpoint runs over HTTP, which is how the filesystem
4
+ * storage, the site editor's GitHub backend and any other backend are kept to
5
+ * the same contract.
6
+ *
7
+ * Run it with any test runner:
8
+ *
9
+ * ```ts
10
+ * import { describe, it } from "vitest";
11
+ * import { defineConformanceSuite } from "@decocms/blocks/protocol/conformance";
12
+ *
13
+ * defineConformanceSuite({ describe, it }, { endpoint: "http://127.0.0.1:4545/rpc", token });
14
+ * ```
15
+ *
16
+ * or collect a report with `runConformance(options)`. The suite writes only
17
+ * names under its own prefix and deletes them after each case (uploads, which
18
+ * the protocol can't delete, stay in the asset folder). Cases that
19
+ * don't apply to an endpoint (a read-only one, one without request keys)
20
+ * skip themselves. Browser-safe: it only needs `fetch`.
21
+ */
22
+ import { assetCases } from "./cases/assets";
23
+ import { guardCases } from "./cases/guards";
24
+ import { readCases } from "./cases/reads";
25
+ import type { ConformanceCase } from "./cases/types";
26
+ import { wireCases } from "./cases/wire";
27
+ import { writeCases } from "./cases/writes";
28
+ import { ConformanceContext, type ConformanceOptions, SkipCase } from "./context";
29
+
30
+ export type { ConformanceCase } from "./cases/types";
31
+ export { type ContentHashFixture, contentHashFixtures } from "./contentHashFixtures";
32
+ export type { ConformanceOptions } from "./context";
33
+
34
+ /** Every conformance case, in the order they run. */
35
+ export const conformanceCases: readonly ConformanceCase[] = [
36
+ ...wireCases,
37
+ ...readCases,
38
+ ...writeCases,
39
+ ...guardCases,
40
+ ...assetCases,
41
+ ];
42
+
43
+ function defaultPrefix(): string {
44
+ return `conformance-${Math.random().toString(36).slice(2, 8)}`;
45
+ }
46
+
47
+ export interface CaseOutcome {
48
+ id: string;
49
+ title: string;
50
+ status: "passed" | "failed" | "skipped";
51
+ /** Why it failed or was skipped. */
52
+ message?: string;
53
+ }
54
+
55
+ /** Runs one case with its own names, cleaning them up afterwards. */
56
+ async function runCase(
57
+ testCase: ConformanceCase,
58
+ options: ConformanceOptions,
59
+ prefix: string,
60
+ ): Promise<CaseOutcome> {
61
+ const ctx = new ConformanceContext(options, prefix);
62
+ try {
63
+ await testCase.run(ctx);
64
+ return { id: testCase.id, title: testCase.title, status: "passed" };
65
+ } catch (error) {
66
+ if (error instanceof SkipCase) {
67
+ return { id: testCase.id, title: testCase.title, status: "skipped", message: error.message };
68
+ }
69
+ return {
70
+ id: testCase.id,
71
+ title: testCase.title,
72
+ status: "failed",
73
+ message: error instanceof Error ? error.message : String(error),
74
+ };
75
+ } finally {
76
+ await ctx.cleanup();
77
+ }
78
+ }
79
+
80
+ export interface ConformanceReport {
81
+ passed: number;
82
+ failed: number;
83
+ skipped: number;
84
+ outcomes: CaseOutcome[];
85
+ }
86
+
87
+ /** Runs every case (or the ones `filter` keeps) in order and reports the outcomes. */
88
+ export async function runConformance(
89
+ options: ConformanceOptions,
90
+ filter: (testCase: ConformanceCase) => boolean = () => true,
91
+ ): Promise<ConformanceReport> {
92
+ const prefix = options.namePrefix ?? defaultPrefix();
93
+ const outcomes: CaseOutcome[] = [];
94
+ let index = 0;
95
+ for (const testCase of conformanceCases.filter(filter)) {
96
+ outcomes.push(await runCase(testCase, options, `${prefix}-${++index}`));
97
+ }
98
+ const count = (status: CaseOutcome["status"]) =>
99
+ outcomes.filter((o) => o.status === status).length;
100
+ return { passed: count("passed"), failed: count("failed"), skipped: count("skipped"), outcomes };
101
+ }
102
+
103
+ /** The parts of a test runner the suite registers itself with (vitest, jest, node:test, bun:test). */
104
+ export interface TestRegistrar {
105
+ describe(name: string, body: () => void): void;
106
+ it(
107
+ name: string,
108
+ body: (context?: { skip?: (note?: string) => void }) => Promise<void>,
109
+ timeout?: number,
110
+ ): void;
111
+ }
112
+
113
+ /** Registers one test per conformance case with a test runner. */
114
+ export function defineConformanceSuite(
115
+ runner: TestRegistrar,
116
+ options: ConformanceOptions | (() => ConformanceOptions),
117
+ suiteName = "content protocol conformance",
118
+ filter: (testCase: ConformanceCase) => boolean = () => true,
119
+ ): void {
120
+ const resolve = typeof options === "function" ? options : () => options;
121
+ const prefix = defaultPrefix();
122
+ runner.describe(suiteName, () => {
123
+ conformanceCases.filter(filter).forEach((testCase, index) => {
124
+ runner.it(
125
+ `${testCase.id}: ${testCase.title}`,
126
+ async (context) => {
127
+ const resolved = resolve();
128
+ const outcome = await runCase(
129
+ testCase,
130
+ resolved,
131
+ `${resolved.namePrefix ?? prefix}-${index + 1}`,
132
+ );
133
+ if (outcome.status === "failed") throw new Error(outcome.message);
134
+ if (outcome.status === "skipped") context?.skip?.(outcome.message);
135
+ },
136
+ 60_000,
137
+ );
138
+ });
139
+ });
140
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Content-protocol errors. Every failure travels as a JSON-RPC 2.0 `error`
3
+ * object (HTTP 200), except a missing or invalid bearer token (401) and a body
4
+ * over the size limit (413), which apply to the whole batch.
5
+ */
6
+
7
+ export const ErrorCode = {
8
+ // Standard JSON-RPC 2.0 codes.
9
+ ParseError: -32700,
10
+ InvalidRequest: -32600,
11
+ MethodNotFound: -32601,
12
+ InvalidParams: -32602,
13
+ InternalError: -32603,
14
+ // Content-protocol codes.
15
+ NotFound: -32001,
16
+ Conflict: -32002,
17
+ InvalidBlock: -32003,
18
+ ReadOnly: -32005,
19
+ Unsupported: -32006,
20
+ LimitExceeded: -32007,
21
+ Unavailable: -32008,
22
+ Unauthorized: -32010,
23
+ Forbidden: -32011,
24
+ } as const;
25
+
26
+ export type ErrorCodeName = keyof typeof ErrorCode;
27
+ export type ErrorCodeValue = (typeof ErrorCode)[ErrorCodeName];
28
+
29
+ /** The JSON-RPC `error` object. */
30
+ export interface RpcErrorObject {
31
+ code: number;
32
+ message: string;
33
+ data?: unknown;
34
+ }
35
+
36
+ /** One entry's failed `ifMatch` guard. */
37
+ export interface VersionMismatch {
38
+ expected: string | null;
39
+ actual: string | null;
40
+ }
41
+
42
+ /** `error.data` of a Conflict (-32002). */
43
+ export interface ConflictData {
44
+ entries?: Record<string, VersionMismatch>;
45
+ schema?: { expected: string; actual: string | null };
46
+ }
47
+
48
+ /** One rule a `blocks.apply` breaks. */
49
+ export interface BlockViolation {
50
+ /** The entry name the violation is about. */
51
+ name: string;
52
+ /** A JSON Pointer inside the entry, when the violation is about one value. */
53
+ pointer?: string;
54
+ rule: string;
55
+ message: string;
56
+ }
57
+
58
+ /** `error.data` of an InvalidBlock (-32003). */
59
+ export interface InvalidBlockData {
60
+ violations: BlockViolation[];
61
+ }
62
+
63
+ /** `error.data` of an Unavailable (-32008). */
64
+ export interface UnavailableData {
65
+ retryAfterMs?: number;
66
+ }
67
+
68
+ /**
69
+ * An error a method fails with. The server turns it into the JSON-RPC
70
+ * `error` object; the client throws it back.
71
+ */
72
+ export class ContentProtocolError extends Error {
73
+ readonly code: number;
74
+ readonly data: unknown;
75
+
76
+ constructor(code: number, message: string, data?: unknown) {
77
+ super(message);
78
+ this.name = "ContentProtocolError";
79
+ this.code = code;
80
+ this.data = data;
81
+ }
82
+
83
+ toJSON(): RpcErrorObject {
84
+ return this.data === undefined
85
+ ? { code: this.code, message: this.message }
86
+ : { code: this.code, message: this.message, data: this.data };
87
+ }
88
+
89
+ static from(error: RpcErrorObject): ContentProtocolError {
90
+ return new ContentProtocolError(error.code, error.message, error.data);
91
+ }
92
+ }
93
+
94
+ export const notFound = (message: string) => new ContentProtocolError(ErrorCode.NotFound, message);
95
+
96
+ export const conflict = (data: ConflictData) =>
97
+ new ContentProtocolError(ErrorCode.Conflict, "a precondition failed", data);
98
+
99
+ export const invalidBlock = (violations: BlockViolation[]) =>
100
+ new ContentProtocolError(
101
+ ErrorCode.InvalidBlock,
102
+ violations.length === 1
103
+ ? `invalid block "${violations[0]!.name}": ${violations[0]!.message}`
104
+ : `${violations.length} invalid blocks`,
105
+ { violations } satisfies InvalidBlockData,
106
+ );
107
+
108
+ export const readOnly = () =>
109
+ new ContentProtocolError(ErrorCode.ReadOnly, "this endpoint is read-only");
110
+
111
+ export const unsupported = (message: string) =>
112
+ new ContentProtocolError(ErrorCode.Unsupported, message);
113
+
114
+ export const limitExceeded = (message: string, data?: Record<string, unknown>) =>
115
+ new ContentProtocolError(ErrorCode.LimitExceeded, message, data);
116
+
117
+ export const unavailable = (message: string, retryAfterMs?: number) =>
118
+ new ContentProtocolError(
119
+ ErrorCode.Unavailable,
120
+ message,
121
+ retryAfterMs === undefined ? undefined : ({ retryAfterMs } satisfies UnavailableData),
122
+ );
123
+
124
+ export const invalidParams = (message: string, data?: unknown) =>
125
+ new ContentProtocolError(ErrorCode.InvalidParams, message, data);
126
+
127
+ export const invalidRequest = (message: string) =>
128
+ new ContentProtocolError(ErrorCode.InvalidRequest, message);
129
+
130
+ export const methodNotFound = (method: string) =>
131
+ new ContentProtocolError(ErrorCode.MethodNotFound, `unknown method "${method}"`);
132
+
133
+ export const parseError = () => new ContentProtocolError(ErrorCode.ParseError, "invalid JSON");
134
+
135
+ export const internalError = () =>
136
+ new ContentProtocolError(ErrorCode.InternalError, "internal error");
137
+
138
+ export const unauthorized = () =>
139
+ new ContentProtocolError(ErrorCode.Unauthorized, "missing or invalid bearer token");
140
+
141
+ export const forbidden = () =>
142
+ new ContentProtocolError(ErrorCode.Forbidden, "not allowed for this project");
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `@decocms/blocks/protocol`: the content protocol's method types, errors,
3
+ * client and file-name rule. Browser-safe.
4
+ *
5
+ * The protocol is how the site editor reads and writes saved blocks without
6
+ * running a site's code: JSON-RPC 2.0 over one HTTP endpoint with four
7
+ * methods — `describe`, `schema.get`, `blocks.list` and `blocks.apply`.
8
+ *
9
+ * Subpaths:
10
+ * - `@decocms/blocks/protocol/keys` — the file-name rule (also re-exported here)
11
+ * - `@decocms/blocks/protocol/server` — `createContentHandler(storage)`
12
+ * - `@decocms/blocks/protocol/storage/fs` — the filesystem storage (Node only)
13
+ * - `@decocms/blocks/protocol/conformance` — a black-box test suite over HTTP
14
+ *
15
+ * The SDK's runtime never imports the protocol, so it never reaches an app
16
+ * bundle. The canonical hash it re-exports is the SDK's own dependency-free
17
+ * leaf module (see ./canonical.ts).
18
+ */
19
+ export {
20
+ APPLY_DIGEST_DOMAIN,
21
+ applyRequestDigest,
22
+ CanonicalJsonError,
23
+ CONTENT_HASH_FORMAT,
24
+ canonicalJson,
25
+ computeContentRevision,
26
+ sha256Hex,
27
+ } from "./canonical";
28
+ export {
29
+ assertSupportedEndpoint,
30
+ type BatchCall,
31
+ type BatchOutcome,
32
+ type ContentClient,
33
+ type ContentClientOptions,
34
+ createContentClient,
35
+ } from "./client";
36
+ export * from "./errors";
37
+ export * from "./keys";
38
+ export * from "./storage";
39
+ export * from "./types";