@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
package/bin/deco.js ADDED
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ // The `deco` command (spec: internals › How the CLI ships). A small JavaScript
3
+ // file that loads the CLI's TypeScript sources: Bun runs them as they are;
4
+ // under Node, tsx's loader is registered first.
5
+ const entry = new URL("../src/v8/cli/main.ts", import.meta.url);
6
+
7
+ if (typeof globalThis.Bun !== "undefined") {
8
+ await import(entry.href);
9
+ } else {
10
+ const { register } = await import("tsx/esm/api");
11
+ register();
12
+ await import(entry.href);
13
+ }
package/package.json CHANGED
@@ -1,114 +1,64 @@
1
1
  {
2
2
  "name": "@decocms/blocks",
3
- "version": "8.0.0",
3
+ "version": "8.1.0-next.1",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24"
7
7
  },
8
- "description": "Deco framework-agnostic core: CMS block resolution, section registry, matchers, portable SDK utilities",
8
+ "description": "Deco CMS: content resolution, built-in blocks, the deco CLI and the content protocol",
9
9
  "repository": {
10
10
  "type": "git",
11
11
  "url": "https://github.com/decocms/blocks.git",
12
12
  "directory": "packages/blocks"
13
13
  },
14
14
  "main": "./src/index.ts",
15
+ "files": [
16
+ "bin",
17
+ "src",
18
+ "!src/**/*.test.ts",
19
+ "!src/**/*.test.tsx",
20
+ "!src/**/__tests__",
21
+ "!src/**/__fixtures__",
22
+ "!src/**/__conformance__",
23
+ "!src/v8/testFixtures.ts"
24
+ ],
25
+ "bin": {
26
+ "deco": "./bin/deco.js"
27
+ },
15
28
  "exports": {
16
29
  ".": "./src/index.ts",
17
- "./cms": "./src/cms/index.ts",
18
- "./cms/client": "./src/cms/client.ts",
19
- "./cms/loadDecofileDirectory": "./src/cms/loadDecofileDirectory.ts",
20
- "./hooks": "./src/hooks/index.ts",
21
- "./types": "./src/types/index.ts",
22
- "./types/widgets": "./src/types/widgets.ts",
23
- "./setup": "./src/setup.ts",
24
- "./matchers/builtins": "./src/matchers/builtins.ts",
25
- "./matchers/posthog": "./src/matchers/posthog.ts",
26
- "./matchers/override": "./src/matchers/override.ts",
27
- "./flags/audience": "./src/flags/audience.ts",
28
- "./flags/everyone": "./src/flags/everyone.ts",
29
- "./flags/flag": "./src/flags/flag.ts",
30
- "./flags/types": "./src/flags/types.ts",
31
- "./flags/multivariate": "./src/flags/multivariate.ts",
32
- "./flags/multivariate/image": "./src/flags/multivariate/image.ts",
33
- "./flags/multivariate/message": "./src/flags/multivariate/message.ts",
34
- "./flags/multivariate/page": "./src/flags/multivariate/page.ts",
35
- "./flags/multivariate/section": "./src/flags/multivariate/section.ts",
36
- "./middleware": "./src/middleware/index.ts",
37
- "./middleware/healthMetrics": "./src/middleware/healthMetrics.ts",
38
- "./middleware/hydrationContext": "./src/middleware/hydrationContext.ts",
39
- "./middleware/observability": "./src/middleware/observability.ts",
40
- "./middleware/validateSection": "./src/middleware/validateSection.ts",
41
- "./sdk": "./src/sdk/index.ts",
42
- "./sdk/abTesting": "./src/sdk/abTesting.ts",
43
- "./sdk/analytics": "./src/sdk/analytics.ts",
44
- "./sdk/cachedLoader": "./src/sdk/cachedLoader.ts",
45
- "./sdk/cacheHeaders": "./src/sdk/cacheHeaders.ts",
46
- "./sdk/clx": "./src/sdk/clx.ts",
47
- "./sdk/cn": "./src/sdk/cn.ts",
48
- "./sdk/composite": "./src/sdk/composite.ts",
49
- "./sdk/cookie": "./src/sdk/cookie.ts",
50
- "./sdk/crypto": "./src/sdk/crypto.ts",
51
- "./sdk/csp": "./src/sdk/csp.ts",
52
- "./sdk/detectDevice": "./src/sdk/detectDevice.ts",
53
- "./sdk/djb2": "./src/sdk/djb2.ts",
54
- "./sdk/encoding": "./src/sdk/encoding.ts",
55
- "./sdk/env": "./src/sdk/env.ts",
56
- "./sdk/flags": "./src/sdk/flags.ts",
57
- "./sdk/http": "./src/sdk/http.ts",
58
- "./sdk/instrumentedFetch": "./src/sdk/instrumentedFetch.ts",
59
- "./sdk/invoke": "./src/sdk/invoke.ts",
60
- "./sdk/logger": "./src/sdk/logger.ts",
61
- "./sdk/mergeCacheControl": "./src/sdk/mergeCacheControl.ts",
62
- "./sdk/normalizeUrls": "./src/sdk/normalizeUrls.ts",
63
- "./sdk/observability": "./src/sdk/observability.ts",
64
- "./sdk/otel": "./src/sdk/otel.ts",
65
- "./sdk/otelAdapters": "./src/sdk/otelAdapters.ts",
66
- "./sdk/otelAdapters/clickhouseCollector": "./src/sdk/otelAdapters/clickhouseCollector.ts",
67
- "./sdk/otelHttpLog": "./src/sdk/otelHttpLog.ts",
68
- "./sdk/otelHttpMeter": "./src/sdk/otelHttpMeter.ts",
69
- "./sdk/otelHttpTracer": "./src/sdk/otelHttpTracer.ts",
70
- "./sdk/redirects": "./src/sdk/redirects.ts",
71
- "./sdk/requestContext": "./src/sdk/requestContext.ts",
72
- "./sdk/requestContextStorage": {
73
- "workerd": "./src/sdk/requestContextStorage.ts",
74
- "node": "./src/sdk/requestContextStorage.ts",
75
- "browser": "./src/sdk/requestContextStorage.browser.ts",
76
- "default": "./src/sdk/requestContextStorage.ts"
30
+ "./analytics": "./src/v8/analytics.ts",
31
+ "./cli": "./src/v8/cli/index.ts",
32
+ "./fetch": "./src/v8/fetch.ts",
33
+ "./secrets": "./src/v8/secrets.ts",
34
+ "./protocol": "./src/protocol/index.ts",
35
+ "./protocol/keys": "./src/protocol/keys.ts",
36
+ "./protocol/server": "./src/protocol/server/index.ts",
37
+ "./protocol/storage/fs": {
38
+ "node": "./src/protocol/storage/fs/index.ts",
39
+ "default": "./src/protocol/storage/fs/unsupported.ts"
77
40
  },
78
- "./sdk/retry": "./src/sdk/retry.ts",
79
- "./sdk/serverTimings": "./src/sdk/serverTimings.ts",
80
- "./sdk/signal": "./src/sdk/signal.ts",
81
- "./sdk/sitemap": "./src/sdk/sitemap.ts",
82
- "./sdk/urlUtils": "./src/sdk/urlUtils.ts",
83
- "./sdk/useDevice": "./src/sdk/useDevice.ts",
84
- "./sdk/useId": "./src/sdk/useId.ts",
85
- "./sdk/useScript": "./src/sdk/useScript.ts",
86
- "./sdk/useSuggestions": "./src/sdk/useSuggestions.ts",
87
- "./sdk/wrapCaughtErrors": "./src/sdk/wrapCaughtErrors.ts"
41
+ "./protocol/conformance": "./src/protocol/conformance/index.ts"
88
42
  },
89
43
  "scripts": {
90
44
  "build": "tsc",
91
45
  "test": "vitest run --root ../.. packages/blocks/",
92
- "typecheck": "tsc --noEmit",
93
- "lint:unused": "knip"
46
+ "typecheck": "tsc --noEmit"
94
47
  },
95
48
  "dependencies": {
96
- "@opentelemetry/api": "^1.9.1",
97
- "@opentelemetry/semantic-conventions": "^1.41.1",
98
- "@tanstack/store": "^0.9.1",
99
- "clsx": "^2.1.1",
100
- "fast-json-patch": "^3.1.0",
101
- "tailwind-merge": "^3.3.1"
49
+ "ajv": "^8.20.0",
50
+ "tsx": "^4.22.5",
51
+ "zod": "^4.4.3"
102
52
  },
103
53
  "peerDependencies": {
104
54
  "react": "^19.0.0",
105
- "react-dom": "^19.0.0"
55
+ "typescript": "^5.0.0"
106
56
  },
107
57
  "devDependencies": {
108
58
  "@types/react": "^19.0.0",
109
59
  "@types/react-dom": "^19.0.0",
110
60
  "esbuild": "^0.27.3",
111
- "knip": "^5.86.0",
61
+ "react-dom": "^19.0.0",
112
62
  "typescript": "^5.9.0"
113
63
  },
114
64
  "publishConfig": {
package/src/index.ts CHANGED
@@ -1,8 +1,35 @@
1
- // @decocms/blocks — framework-agnostic core
2
- export * from "./cms/index";
3
- export * from "./hooks/index";
4
- export * from "./middleware/index";
5
- // Observability surface — logger + instrumentWorker live behind their own
6
- // granular imports too (see `@decocms/blocks/sdk/logger`, `.../observability`).
7
- export { type Logger, type LogLevel, logger, setLogLevel } from "./sdk/logger";
8
- export * from "./types/index";
1
+ // @decocms/blocks: the v8 runtime API. The CLI, protocol and helpers live on
2
+ // their own subpaths (`/cli`, `/protocol`, `/fetch`, `/analytics`, `/secrets`).
3
+ export {
4
+ type Analytics,
5
+ type Block,
6
+ type BlockFunction,
7
+ type Blocks,
8
+ type Client,
9
+ type CMS,
10
+ type CMSError,
11
+ createCMS,
12
+ DRAFT_COOKIE,
13
+ type DraftPointer,
14
+ draftCookie,
15
+ draftPointer,
16
+ formatDraftPointer,
17
+ type Lazy,
18
+ type ListOptions,
19
+ type Loader,
20
+ type Match,
21
+ matchRoute,
22
+ type Page,
23
+ parseDraftPointer,
24
+ type Redirect,
25
+ type Result,
26
+ type Route,
27
+ remoteLoader,
28
+ resetForTests,
29
+ type Secret,
30
+ type Seo,
31
+ type Snapshot,
32
+ type Telemetry,
33
+ type TelemetryConfig,
34
+ type Variant,
35
+ } from "./v8/index";
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Asset-upload naming rules shared by the asset handler and the storages.
3
+ * Browser-safe.
4
+ */
5
+
6
+ /**
7
+ * Every content type the asset endpoint accepts, with the file extensions a
8
+ * file of that type may have (the first is the one appended to a name
9
+ * without an extension). The stored file's extension decides the type it's
10
+ * served with, so an upload can never pick one the browser would run, such
11
+ * as `.html` or `.js`.
12
+ */
13
+ export const ASSET_TYPES: Readonly<Record<string, readonly string[]>> = {
14
+ "image/png": [".png"],
15
+ "image/jpeg": [".jpg", ".jpeg"],
16
+ "image/webp": [".webp"],
17
+ "image/avif": [".avif"],
18
+ "image/gif": [".gif"],
19
+ "image/x-icon": [".ico"],
20
+ "image/vnd.microsoft.icon": [".ico"],
21
+ "video/mp4": [".mp4"],
22
+ "video/webm": [".webm"],
23
+ "font/woff2": [".woff2"],
24
+ "font/woff": [".woff"],
25
+ "font/ttf": [".ttf"],
26
+ "font/otf": [".otf"],
27
+ "application/font-woff": [".woff"],
28
+ "application/x-font-ttf": [".ttf"],
29
+ "application/vnd.ms-fontobject": [".eot"],
30
+ "application/pdf": [".pdf"],
31
+ };
32
+
33
+ /**
34
+ * SVG can carry scripts, so it runs on the site's origin like HTML would.
35
+ * Accepted only with `allowSvg`.
36
+ */
37
+ export const SVG_ASSET_TYPE = { "image/svg+xml": [".svg"] } as const;
38
+
39
+ export interface AssetTypeOptions {
40
+ /** Accept `image/svg+xml` uploads (default false: SVG can carry scripts). */
41
+ allowSvg?: boolean;
42
+ }
43
+
44
+ const mediaType = (contentType: string | null) =>
45
+ contentType ? contentType.split(";")[0]!.trim().toLowerCase() : "";
46
+
47
+ /** The extensions an upload of `contentType` may have; `null` when the type isn't accepted. */
48
+ export function assetExtensions(
49
+ contentType: string | null,
50
+ options: AssetTypeOptions = {},
51
+ ): readonly string[] | null {
52
+ const type = mediaType(contentType);
53
+ if (Object.hasOwn(ASSET_TYPES, type)) return ASSET_TYPES[type] ?? null;
54
+ if (options.allowSvg && type === "image/svg+xml") return SVG_ASSET_TYPE[type] ?? null;
55
+ return null;
56
+ }
57
+
58
+ /** True when the asset endpoint accepts `contentType`. */
59
+ export function isAcceptedAssetType(
60
+ contentType: string | null,
61
+ options: AssetTypeOptions = {},
62
+ ): boolean {
63
+ return assetExtensions(contentType, options) !== null;
64
+ }
65
+
66
+ /**
67
+ * Fits a sanitized file name to its content type: a name without an
68
+ * extension gets the type's, and the extension is lowercased. Returns `null`
69
+ * when the name's extension doesn't match the type (`evil.html` sent as
70
+ * `image/png`), or the type isn't accepted.
71
+ */
72
+ export function assetNameForType(
73
+ name: string,
74
+ contentType: string | null,
75
+ options: AssetTypeOptions = {},
76
+ ): string | null {
77
+ const extensions = assetExtensions(contentType, options);
78
+ if (!extensions) return null;
79
+ const dot = name.lastIndexOf(".");
80
+ if (dot <= 0) return `${name}${extensions[0]}`;
81
+ const extension = name.slice(dot).toLowerCase();
82
+ return extensions.includes(extension) ? name.slice(0, dot) + extension : null;
83
+ }
84
+
85
+ /**
86
+ * Normalizes an upload's file name: its last path segment, lowercased
87
+ * extension, with anything but letters, digits, `.`, `_` and `-` replaced.
88
+ * Returns `null` when nothing usable is left.
89
+ */
90
+ export function sanitizeAssetName(raw: string): string | null {
91
+ let name: string;
92
+ try {
93
+ name = decodeURIComponent(raw);
94
+ } catch {
95
+ name = raw;
96
+ }
97
+ name = name.split(/[\\/]/).pop() ?? "";
98
+ name = name
99
+ .normalize("NFKD")
100
+ .replace(/[̀-ͯ]/g, "")
101
+ .replace(/[^A-Za-z0-9._-]+/g, "-")
102
+ .replace(/-{2,}/g, "-")
103
+ .replace(/^[.-]+/, "")
104
+ .replace(/-+(\.|$)/g, "$1");
105
+ if (!name || name === "." || name === "..") return null;
106
+ if (name.length > 200) {
107
+ const dot = name.lastIndexOf(".");
108
+ const ext = dot > 0 ? name.slice(dot).slice(0, 16) : "";
109
+ name = name.slice(0, 200 - ext.length) + ext;
110
+ }
111
+ return name;
112
+ }
113
+
114
+ /**
115
+ * The name to try when `name` is taken: a short random suffix before the
116
+ * extension, such as `banner-3f9a2c.jpg`.
117
+ */
118
+ export function suffixedAssetName(name: string): string {
119
+ const suffix = Array.from(crypto.getRandomValues(new Uint8Array(3)), (b) =>
120
+ b.toString(16).padStart(2, "0"),
121
+ ).join("");
122
+ const dot = name.lastIndexOf(".");
123
+ return dot > 0 ? `${name.slice(0, dot)}-${suffix}${name.slice(dot)}` : `${name}-${suffix}`;
124
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Canonical JSON and content hashing. The implementation is a dependency-free
3
+ * leaf module of the SDK (`src/v8/canonical.ts`), because the runtime checks
4
+ * content revisions too; the protocol re-exports it so the CLI, the server
5
+ * and the site editor share one definition.
6
+ */
7
+ export * from "../v8/canonical";
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The secret ciphertext format. The implementation is a dependency-free leaf
3
+ * module of the SDK (`src/v8/ciphertext.ts`), where the `secret` built-in
4
+ * decrypts it; the protocol re-exports it for its secret guard.
5
+ */
6
+ export * from "../v8/ciphertext";
@@ -0,0 +1,170 @@
1
+ /**
2
+ * A small content-protocol client: one method per protocol method, plus
3
+ * batches. Uses `fetch`, so it runs in browsers, on Workers and on Node.
4
+ */
5
+ import { ContentProtocolError, ErrorCode, type RpcErrorObject } from "./errors";
6
+ import {
7
+ type DescribeResult,
8
+ type MethodName,
9
+ type Methods,
10
+ PROTOCOL_NAME,
11
+ PROTOCOL_VERSION,
12
+ type RpcId,
13
+ } from "./types";
14
+
15
+ export interface ContentClientOptions {
16
+ /** The endpoint URL, such as `http://127.0.0.1:4545/rpc`. */
17
+ endpoint: string | URL;
18
+ /** Sent as `Authorization: Bearer <token>`. */
19
+ token?: string;
20
+ /** Extra headers on every request. */
21
+ headers?: Record<string, string>;
22
+ /** A fetch implementation (defaults to the global one). */
23
+ fetch?: (input: Request) => Promise<Response>;
24
+ }
25
+
26
+ /** One call of a batch. */
27
+ export type BatchCall = {
28
+ [M in MethodName]: { method: M; params?: Methods[M]["params"] };
29
+ }[MethodName];
30
+
31
+ /** The outcome of one batch call: its result or its error. */
32
+ export type BatchOutcome =
33
+ | { ok: true; result: unknown }
34
+ | { ok: false; error: ContentProtocolError };
35
+
36
+ export interface ContentClient {
37
+ /** Throws Unsupported when the endpoint speaks another protocol or major version. */
38
+ describe(): Promise<Methods["describe"]["result"]>;
39
+ schemaGet(params?: Methods["schema.get"]["params"]): Promise<Methods["schema.get"]["result"]>;
40
+ blocksList(params?: Methods["blocks.list"]["params"]): Promise<Methods["blocks.list"]["result"]>;
41
+ blocksApply(
42
+ params: Methods["blocks.apply"]["params"],
43
+ ): Promise<Methods["blocks.apply"]["result"]>;
44
+ /** Calls one method by name. Throws `ContentProtocolError` on an error response. */
45
+ call<M extends MethodName>(
46
+ method: M,
47
+ params?: Methods[M]["params"],
48
+ ): Promise<Methods[M]["result"]>;
49
+ /** Runs several calls in one request; outcomes come back in order. */
50
+ batch(calls: BatchCall[]): Promise<BatchOutcome[]>;
51
+ }
52
+
53
+ type WireResponse = { id: RpcId | null; result?: unknown; error?: RpcErrorObject };
54
+
55
+ /**
56
+ * Decodes a JSON response body, gunzipping it when a custom fetch (such as an
57
+ * in-process handler) handed back the raw gzip bytes.
58
+ */
59
+ export async function readResponseJson(response: Response): Promise<unknown> {
60
+ let bytes = new Uint8Array(await response.arrayBuffer());
61
+ if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
62
+ const stream = new Blob([bytes as BlobPart])
63
+ .stream()
64
+ .pipeThrough(
65
+ new DecompressionStream("gzip") as unknown as ReadableWritablePair<Uint8Array, Uint8Array>,
66
+ );
67
+ bytes = new Uint8Array(await new Response(stream).arrayBuffer());
68
+ }
69
+ return JSON.parse(new TextDecoder().decode(bytes));
70
+ }
71
+
72
+ /**
73
+ * Refuses an endpoint this client can't speak to: another protocol, or
74
+ * another major version (minors only add, so any minor is fine).
75
+ */
76
+ export function assertSupportedEndpoint(description: DescribeResult): DescribeResult {
77
+ const { protocol, version } = (description ?? {}) as Partial<DescribeResult>;
78
+ if (protocol !== PROTOCOL_NAME) {
79
+ throw new ContentProtocolError(
80
+ ErrorCode.Unsupported,
81
+ `the endpoint speaks ${JSON.stringify(protocol)}, not ${PROTOCOL_NAME}`,
82
+ );
83
+ }
84
+ if (version?.major !== PROTOCOL_VERSION.major) {
85
+ throw new ContentProtocolError(
86
+ ErrorCode.Unsupported,
87
+ `the endpoint speaks ${PROTOCOL_NAME} ${String(version?.major)}.x; this client speaks ${PROTOCOL_VERSION.major}.x`,
88
+ );
89
+ }
90
+ return description;
91
+ }
92
+
93
+ export function createContentClient(options: ContentClientOptions): ContentClient {
94
+ const doFetch = options.fetch ?? ((request: Request) => fetch(request));
95
+ let nextId = 1;
96
+
97
+ async function post(body: unknown): Promise<unknown> {
98
+ const headers: Record<string, string> = {
99
+ "content-type": "application/json",
100
+ accept: "application/json",
101
+ ...options.headers,
102
+ };
103
+ if (options.token !== undefined) headers.authorization = `Bearer ${options.token}`;
104
+ const response = await doFetch(
105
+ new Request(options.endpoint, { method: "POST", headers, body: JSON.stringify(body) }),
106
+ );
107
+ let payload: unknown;
108
+ try {
109
+ payload = await readResponseJson(response);
110
+ } catch {
111
+ throw new ContentProtocolError(
112
+ ErrorCode.Unavailable,
113
+ `the endpoint answered HTTP ${response.status} without a JSON-RPC body`,
114
+ );
115
+ }
116
+ if (!response.ok || (!Array.isArray(payload) && (payload as WireResponse)?.id === null)) {
117
+ const error = (payload as WireResponse)?.error;
118
+ if (error) throw ContentProtocolError.from(error);
119
+ throw new ContentProtocolError(
120
+ ErrorCode.Unavailable,
121
+ `the endpoint answered HTTP ${response.status}`,
122
+ );
123
+ }
124
+ return payload;
125
+ }
126
+
127
+ const call = async <M extends MethodName>(method: M, params?: Methods[M]["params"]) => {
128
+ const id = nextId++;
129
+ const response = (await post({
130
+ jsonrpc: "2.0",
131
+ id,
132
+ method,
133
+ params: params ?? {},
134
+ })) as WireResponse;
135
+ if (response.error) throw ContentProtocolError.from(response.error);
136
+ return response.result as Methods[M]["result"];
137
+ };
138
+
139
+ return {
140
+ call,
141
+ describe: async () => assertSupportedEndpoint(await call("describe")),
142
+ schemaGet: (params) => call("schema.get", params),
143
+ blocksList: (params) => call("blocks.list", params),
144
+ blocksApply: (params) => call("blocks.apply", params),
145
+ async batch(calls) {
146
+ const ids = calls.map(() => nextId++);
147
+ const responses = (await post(
148
+ calls.map((c, i) => ({
149
+ jsonrpc: "2.0",
150
+ id: ids[i],
151
+ method: c.method,
152
+ params: c.params ?? {},
153
+ })),
154
+ )) as WireResponse[];
155
+ const byId = new Map(responses.map((r) => [r.id, r]));
156
+ return ids.map((id): BatchOutcome => {
157
+ const response = byId.get(id);
158
+ if (!response) {
159
+ return {
160
+ ok: false,
161
+ error: new ContentProtocolError(ErrorCode.InternalError, "no response for this call"),
162
+ };
163
+ }
164
+ return response.error
165
+ ? { ok: false, error: ContentProtocolError.from(response.error) }
166
+ : { ok: true, result: response.result };
167
+ });
168
+ },
169
+ };
170
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Uploads beside the protocol: `PUT /assets/<name>`. These cases run only
3
+ * when the harness passes `assetsEndpoint`.
4
+ */
5
+ import { ErrorCode } from "../../errors";
6
+ import { assert, assertEqual, type ConformanceContext, rawErrorCode } from "../context";
7
+ import type { ConformanceCase } from "./types";
8
+
9
+ /** The smallest PNG header: enough bytes for an upload, never executed. */
10
+ const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
11
+
12
+ async function uploadsAccepted(ctx: ConformanceContext) {
13
+ if (ctx.options.assetsEndpoint === undefined) return ctx.skip("no assetsEndpoint");
14
+ const d = await ctx.describe();
15
+ if (d.readOnly || d.assets === null) return ctx.skip("the endpoint doesn't accept uploads");
16
+ return d;
17
+ }
18
+
19
+ const pathOf = (body: unknown) => (body as { path?: unknown } | null)?.path;
20
+
21
+ export const assetCases: ConformanceCase[] = [
22
+ {
23
+ id: "assets/upload",
24
+ title:
25
+ "an upload answers 201 with /assets/<name>; a taken name gets a suffix, never an overwrite",
26
+ async run(ctx) {
27
+ await uploadsAccepted(ctx);
28
+ const name = `${ctx.prefix}-banner.png`;
29
+ const first = await ctx.upload(name, PNG, "image/png");
30
+ assertEqual(first.status, 201, "HTTP status");
31
+ assertEqual(pathOf(first.body), `/assets/${name}`, "the stored path");
32
+ const second = await ctx.upload(name, PNG, "image/png");
33
+ assertEqual(second.status, 201, "HTTP status of the second upload");
34
+ const path = pathOf(second.body);
35
+ assert(
36
+ typeof path === "string" && path.startsWith("/assets/") && path !== `/assets/${name}`,
37
+ `a taken name gets another name, got ${String(path)}`,
38
+ );
39
+ assert(path.endsWith(".png"), "the suffix goes before the extension");
40
+ },
41
+ },
42
+ {
43
+ id: "assets/content-types",
44
+ title: "uploads refuse non-media types, SVG and an extension that doesn't match the type (415)",
45
+ async run(ctx) {
46
+ await uploadsAccepted(ctx);
47
+ const script = "<script>alert(document.cookie)</script>";
48
+ const refused: Array<[name: string, type: string]> = [
49
+ [`${ctx.prefix}-page.html`, "text/html"],
50
+ [`${ctx.prefix}-evil.html`, "image/png"],
51
+ [`${ctx.prefix}-evil.js`, "image/jpeg"],
52
+ [`${ctx.prefix}-logo.svg`, "image/svg+xml"],
53
+ [`${ctx.prefix}-data.json`, "application/json"],
54
+ ];
55
+ for (const [name, type] of refused) {
56
+ const response = await ctx.upload(name, script, type);
57
+ assertEqual(response.status, 415, `HTTP status of ${name} as ${type}`);
58
+ assertEqual(rawErrorCode(response.body), ErrorCode.InvalidRequest, "the error code");
59
+ }
60
+ },
61
+ },
62
+ {
63
+ id: "assets/read-only",
64
+ title: "an endpoint without uploads refuses them",
65
+ async run(ctx) {
66
+ if (ctx.options.assetsEndpoint === undefined) return ctx.skip("no assetsEndpoint");
67
+ const d = await ctx.describe();
68
+ if (!d.readOnly && d.assets !== null) return ctx.skip("the endpoint accepts uploads");
69
+ const response = await ctx.upload(`${ctx.prefix}-x.png`, PNG, "image/png");
70
+ assert(
71
+ response.status === 403 || response.status === 404,
72
+ `HTTP ${response.status} (expected 403 or 404)`,
73
+ );
74
+ const code = rawErrorCode(response.body);
75
+ assert(
76
+ code === ErrorCode.ReadOnly || code === ErrorCode.Unsupported,
77
+ `error ${String(code)} (expected ReadOnly or Unsupported)`,
78
+ );
79
+ },
80
+ },
81
+ ];