@decocms/blocks 8.9.0 → 8.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (257) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/index.js.map +1 -1
  5. package/dist/protocol/channel.d.ts +98 -0
  6. package/dist/protocol/channel.d.ts.map +1 -0
  7. package/dist/protocol/channel.js +58 -0
  8. package/dist/protocol/channel.js.map +1 -0
  9. package/dist/protocol/client.js +2 -2
  10. package/dist/protocol/client.js.map +1 -1
  11. package/dist/protocol/conformance/blockMetaVectors.json +214 -0
  12. package/dist/protocol/conformance/contentHashFixtures.d.ts +22 -0
  13. package/dist/protocol/conformance/contentHashFixtures.d.ts.map +1 -1
  14. package/dist/protocol/conformance/contentHashFixtures.js +55 -0
  15. package/dist/protocol/conformance/contentHashFixtures.js.map +1 -1
  16. package/dist/protocol/conformance/index.d.ts +2 -1
  17. package/dist/protocol/conformance/index.d.ts.map +1 -1
  18. package/dist/protocol/conformance/index.js +2 -1
  19. package/dist/protocol/conformance/index.js.map +1 -1
  20. package/dist/protocol/conformance/vectors.d.ts +33 -0
  21. package/dist/protocol/conformance/vectors.d.ts.map +1 -0
  22. package/dist/protocol/conformance/vectors.js +3 -0
  23. package/dist/protocol/conformance/vectors.js.map +1 -0
  24. package/dist/protocol/index.d.ts +11 -1
  25. package/dist/protocol/index.d.ts.map +1 -1
  26. package/dist/protocol/index.js +11 -1
  27. package/dist/protocol/index.js.map +1 -1
  28. package/dist/protocol/keys.d.ts +1 -1
  29. package/dist/protocol/keys.js +1 -1
  30. package/dist/v8/background.d.ts +13 -0
  31. package/dist/v8/background.d.ts.map +1 -1
  32. package/dist/v8/background.js +41 -0
  33. package/dist/v8/background.js.map +1 -1
  34. package/dist/v8/blockMeta.d.ts +27 -0
  35. package/dist/v8/blockMeta.d.ts.map +1 -0
  36. package/dist/v8/blockMeta.js +75 -0
  37. package/dist/v8/blockMeta.js.map +1 -0
  38. package/dist/v8/blockStore.d.ts +43 -0
  39. package/dist/v8/blockStore.d.ts.map +1 -0
  40. package/dist/v8/blockStore.js +95 -0
  41. package/dist/v8/blockStore.js.map +1 -0
  42. package/dist/v8/boundedJson.d.ts +5 -0
  43. package/dist/v8/boundedJson.d.ts.map +1 -1
  44. package/dist/v8/boundedJson.js +10 -2
  45. package/dist/v8/boundedJson.js.map +1 -1
  46. package/dist/v8/boundedMap.d.ts +19 -0
  47. package/dist/v8/boundedMap.d.ts.map +1 -0
  48. package/dist/v8/boundedMap.js +52 -0
  49. package/dist/v8/boundedMap.js.map +1 -0
  50. package/dist/v8/builtins/data.d.ts +18 -2
  51. package/dist/v8/builtins/data.d.ts.map +1 -1
  52. package/dist/v8/builtins/data.js +17 -1
  53. package/dist/v8/builtins/data.js.map +1 -1
  54. package/dist/v8/builtins/index.d.ts.map +1 -1
  55. package/dist/v8/builtins/index.js +2 -1
  56. package/dist/v8/builtins/index.js.map +1 -1
  57. package/dist/v8/builtins/legacy.d.ts +6 -3
  58. package/dist/v8/builtins/legacy.d.ts.map +1 -1
  59. package/dist/v8/builtins/legacy.js +6 -3
  60. package/dist/v8/builtins/legacy.js.map +1 -1
  61. package/dist/v8/canonical.d.ts +8 -0
  62. package/dist/v8/canonical.d.ts.map +1 -1
  63. package/dist/v8/canonical.js +15 -0
  64. package/dist/v8/canonical.js.map +1 -1
  65. package/dist/v8/cli/builtins.d.ts.map +1 -1
  66. package/dist/v8/cli/builtins.js +1 -0
  67. package/dist/v8/cli/builtins.js.map +1 -1
  68. package/dist/v8/cli/check/index.d.ts +10 -0
  69. package/dist/v8/cli/check/index.d.ts.map +1 -1
  70. package/dist/v8/cli/check/index.js +91 -7
  71. package/dist/v8/cli/check/index.js.map +1 -1
  72. package/dist/v8/cli/content.d.ts +12 -25
  73. package/dist/v8/cli/content.d.ts.map +1 -1
  74. package/dist/v8/cli/content.js +46 -75
  75. package/dist/v8/cli/content.js.map +1 -1
  76. package/dist/v8/cli/index.d.ts +1 -2
  77. package/dist/v8/cli/index.d.ts.map +1 -1
  78. package/dist/v8/cli/index.js +1 -2
  79. package/dist/v8/cli/index.js.map +1 -1
  80. package/dist/v8/cli/remote/commands.d.ts +71 -0
  81. package/dist/v8/cli/remote/commands.d.ts.map +1 -0
  82. package/dist/v8/cli/remote/commands.js +644 -0
  83. package/dist/v8/cli/remote/commands.js.map +1 -0
  84. package/dist/v8/cli/remote/diff.d.ts +15 -0
  85. package/dist/v8/cli/remote/diff.d.ts.map +1 -0
  86. package/dist/v8/cli/remote/diff.js +102 -0
  87. package/dist/v8/cli/remote/diff.js.map +1 -0
  88. package/dist/v8/cli/remote/env.d.ts +35 -0
  89. package/dist/v8/cli/remote/env.d.ts.map +1 -0
  90. package/dist/v8/cli/remote/env.js +84 -0
  91. package/dist/v8/cli/remote/env.js.map +1 -0
  92. package/dist/v8/cli/remote/http.d.ts +149 -0
  93. package/dist/v8/cli/remote/http.d.ts.map +1 -0
  94. package/dist/v8/cli/remote/http.js +381 -0
  95. package/dist/v8/cli/remote/http.js.map +1 -0
  96. package/dist/v8/cli/remote/local.d.ts +90 -0
  97. package/dist/v8/cli/remote/local.d.ts.map +1 -0
  98. package/dist/v8/cli/remote/local.js +309 -0
  99. package/dist/v8/cli/remote/local.js.map +1 -0
  100. package/dist/v8/cli/root.d.ts +29 -0
  101. package/dist/v8/cli/root.d.ts.map +1 -1
  102. package/dist/v8/cli/root.js +28 -0
  103. package/dist/v8/cli/root.js.map +1 -1
  104. package/dist/v8/cli/run.d.ts +11 -1
  105. package/dist/v8/cli/run.d.ts.map +1 -1
  106. package/dist/v8/cli/run.js +281 -124
  107. package/dist/v8/cli/run.js.map +1 -1
  108. package/dist/v8/cli/schema/builtinSchemas.d.ts.map +1 -1
  109. package/dist/v8/cli/schema/builtinSchemas.js +28 -10
  110. package/dist/v8/cli/schema/builtinSchemas.js.map +1 -1
  111. package/dist/v8/cli/schema/generate.js +1 -1
  112. package/dist/v8/cli/schema/generate.js.map +1 -1
  113. package/dist/v8/client.d.ts +9 -9
  114. package/dist/v8/client.d.ts.map +1 -1
  115. package/dist/v8/client.js +138 -50
  116. package/dist/v8/client.js.map +1 -1
  117. package/dist/v8/cms.d.ts +2 -1
  118. package/dist/v8/cms.d.ts.map +1 -1
  119. package/dist/v8/cms.js +55 -46
  120. package/dist/v8/cms.js.map +1 -1
  121. package/dist/v8/content.d.ts +39 -78
  122. package/dist/v8/content.d.ts.map +1 -1
  123. package/dist/v8/content.js +155 -195
  124. package/dist/v8/content.js.map +1 -1
  125. package/dist/v8/contentIndex.d.ts +71 -0
  126. package/dist/v8/contentIndex.d.ts.map +1 -0
  127. package/dist/v8/contentIndex.js +137 -0
  128. package/dist/v8/contentIndex.js.map +1 -0
  129. package/dist/v8/draft.d.ts +7 -7
  130. package/dist/v8/draft.d.ts.map +1 -1
  131. package/dist/v8/draft.js +10 -9
  132. package/dist/v8/draft.js.map +1 -1
  133. package/dist/v8/draftChanges.d.ts +59 -32
  134. package/dist/v8/draftChanges.d.ts.map +1 -1
  135. package/dist/v8/draftChanges.js +139 -75
  136. package/dist/v8/draftChanges.js.map +1 -1
  137. package/dist/v8/errors.d.ts +21 -0
  138. package/dist/v8/errors.d.ts.map +1 -1
  139. package/dist/v8/errors.js +22 -0
  140. package/dist/v8/errors.js.map +1 -1
  141. package/dist/v8/hostedSource.d.ts +57 -0
  142. package/dist/v8/hostedSource.d.ts.map +1 -0
  143. package/dist/v8/hostedSource.js +18 -0
  144. package/dist/v8/hostedSource.js.map +1 -0
  145. package/dist/v8/identity.d.ts +1 -1
  146. package/dist/v8/identity.js +1 -1
  147. package/dist/v8/index.d.ts +1 -0
  148. package/dist/v8/index.d.ts.map +1 -1
  149. package/dist/v8/index.js +1 -0
  150. package/dist/v8/index.js.map +1 -1
  151. package/dist/v8/matchRoute.js +7 -4
  152. package/dist/v8/matchRoute.js.map +1 -1
  153. package/dist/v8/pin.d.ts +34 -0
  154. package/dist/v8/pin.d.ts.map +1 -0
  155. package/dist/v8/pin.js +156 -0
  156. package/dist/v8/pin.js.map +1 -0
  157. package/dist/v8/preview/StudioBridge.d.ts +8 -8
  158. package/dist/v8/preview/StudioBridge.d.ts.map +1 -1
  159. package/dist/v8/preview/StudioBridge.js +8 -10
  160. package/dist/v8/preview/StudioBridge.js.map +1 -1
  161. package/dist/v8/preview/StudioChannel.d.ts +51 -0
  162. package/dist/v8/preview/StudioChannel.d.ts.map +1 -0
  163. package/dist/v8/preview/StudioChannel.js +104 -0
  164. package/dist/v8/preview/StudioChannel.js.map +1 -0
  165. package/dist/v8/preview/index.d.ts +3 -0
  166. package/dist/v8/preview/index.d.ts.map +1 -1
  167. package/dist/v8/preview/index.js +3 -0
  168. package/dist/v8/preview/index.js.map +1 -1
  169. package/dist/v8/remoteLoader.d.ts +42 -5
  170. package/dist/v8/remoteLoader.d.ts.map +1 -1
  171. package/dist/v8/remoteLoader.js +317 -259
  172. package/dist/v8/remoteLoader.js.map +1 -1
  173. package/dist/v8/resolver.d.ts +22 -8
  174. package/dist/v8/resolver.d.ts.map +1 -1
  175. package/dist/v8/resolver.js +37 -32
  176. package/dist/v8/resolver.js.map +1 -1
  177. package/dist/v8/revisionId.d.ts +11 -0
  178. package/dist/v8/revisionId.d.ts.map +1 -0
  179. package/dist/v8/revisionId.js +13 -0
  180. package/dist/v8/revisionId.js.map +1 -0
  181. package/dist/v8/settings.d.ts +6 -6
  182. package/dist/v8/settings.d.ts.map +1 -1
  183. package/dist/v8/settings.js +8 -7
  184. package/dist/v8/settings.js.map +1 -1
  185. package/dist/v8/telemetry.d.ts +4 -2
  186. package/dist/v8/telemetry.d.ts.map +1 -1
  187. package/dist/v8/telemetry.js +2 -2
  188. package/dist/v8/telemetry.js.map +1 -1
  189. package/dist/v8/types.d.ts +52 -40
  190. package/dist/v8/types.d.ts.map +1 -1
  191. package/dist/v8/variants.d.ts +7 -2
  192. package/dist/v8/variants.d.ts.map +1 -1
  193. package/dist/v8/variants.js +21 -24
  194. package/dist/v8/variants.js.map +1 -1
  195. package/dist/v8/vite/index.d.ts +2 -2
  196. package/dist/v8/vite/index.js +1 -1
  197. package/dist/v8/vite/index.js.map +1 -1
  198. package/package.json +1 -1
  199. package/src/index.ts +2 -0
  200. package/src/protocol/channel.ts +127 -0
  201. package/src/protocol/client.ts +2 -2
  202. package/src/protocol/conformance/blockMetaVectors.json +214 -0
  203. package/src/protocol/conformance/contentHashFixtures.ts +74 -0
  204. package/src/protocol/conformance/index.ts +9 -1
  205. package/src/protocol/conformance/vectors.ts +36 -0
  206. package/src/protocol/index.ts +32 -0
  207. package/src/protocol/keys.ts +1 -1
  208. package/src/v8/background.ts +42 -0
  209. package/src/v8/blockMeta.ts +100 -0
  210. package/src/v8/blockStore.ts +124 -0
  211. package/src/v8/boundedJson.ts +20 -2
  212. package/src/v8/boundedMap.ts +53 -0
  213. package/src/v8/builtins/data.ts +26 -2
  214. package/src/v8/builtins/index.ts +2 -1
  215. package/src/v8/builtins/legacy.ts +6 -3
  216. package/src/v8/canonical.ts +15 -0
  217. package/src/v8/cli/builtins.ts +1 -0
  218. package/src/v8/cli/check/index.ts +97 -7
  219. package/src/v8/cli/content.ts +49 -91
  220. package/src/v8/cli/index.ts +1 -2
  221. package/src/v8/cli/remote/commands.ts +834 -0
  222. package/src/v8/cli/remote/diff.ts +100 -0
  223. package/src/v8/cli/remote/env.ts +107 -0
  224. package/src/v8/cli/remote/http.ts +484 -0
  225. package/src/v8/cli/remote/local.ts +343 -0
  226. package/src/v8/cli/root.ts +40 -0
  227. package/src/v8/cli/run.ts +333 -136
  228. package/src/v8/cli/schema/builtinSchemas.ts +29 -10
  229. package/src/v8/cli/schema/generate.ts +1 -1
  230. package/src/v8/client.ts +162 -60
  231. package/src/v8/cms.ts +62 -53
  232. package/src/v8/content.ts +179 -229
  233. package/src/v8/contentIndex.ts +183 -0
  234. package/src/v8/draft.ts +15 -14
  235. package/src/v8/draftChanges.ts +151 -85
  236. package/src/v8/errors.ts +37 -0
  237. package/src/v8/hostedSource.ts +67 -0
  238. package/src/v8/identity.ts +1 -1
  239. package/src/v8/index.ts +1 -0
  240. package/src/v8/matchRoute.ts +7 -4
  241. package/src/v8/pin.ts +176 -0
  242. package/src/v8/preview/StudioBridge.ts +8 -10
  243. package/src/v8/preview/StudioChannel.ts +116 -0
  244. package/src/v8/preview/index.ts +3 -0
  245. package/src/v8/remoteLoader.ts +350 -286
  246. package/src/v8/resolver.ts +56 -33
  247. package/src/v8/revisionId.ts +14 -0
  248. package/src/v8/settings.ts +10 -9
  249. package/src/v8/telemetry.ts +3 -3
  250. package/src/v8/types.ts +52 -40
  251. package/src/v8/variants.ts +30 -26
  252. package/src/v8/vite/index.ts +3 -3
  253. package/dist/v8/cli/serve/server.d.ts +0 -29
  254. package/dist/v8/cli/serve/server.d.ts.map +0 -1
  255. package/dist/v8/cli/serve/server.js +0 -296
  256. package/dist/v8/cli/serve/server.js.map +0 -1
  257. package/src/v8/cli/serve/server.ts +0 -348
@@ -0,0 +1,183 @@
1
+ /**
2
+ * The content a request reads, as an index (see /next/hosted-releases-internals):
3
+ * block name → `{ version, meta?, data? }`, the shape of a hosted revision's
4
+ * `index.json`. Routing, the reference walk and existence checks read the
5
+ * index only; bodies come from memory (local content, a draft's own files,
6
+ * the inline `CMS` body) or, by hash, from the hosted block store.
7
+ *
8
+ * Local content (a content module or a custom `Loader`) is turned into an
9
+ * index once per snapshot object, with `blockMeta` over its bodies, so
10
+ * `routes()`, `redirects()` and `prefetch()` behave the same everywhere.
11
+ */
12
+ import { type BlockIndex, blockMeta, type IndexEntry } from "./blockMeta.ts";
13
+ import { REDIRECTS_TYPE } from "./builtins/data.ts";
14
+ import { LEGACY_ALIASES } from "./builtins/legacy.ts";
15
+ import { own } from "./json.ts";
16
+ import type { Route, Snapshot } from "./types.ts";
17
+
18
+ /** Fetches bodies by hash, shared across requests (see ./blockStore.ts). */
19
+ export interface BodySource {
20
+ /** The body for `hash` when this process holds it, without fetching. */
21
+ peek(hash: string): unknown | undefined;
22
+ /** The body for `hash`: held, in flight, or fetched now. Rejects with a `ContentUnavailableError`. */
23
+ get(hash: string, name: string): Promise<unknown>;
24
+ }
25
+
26
+ /** Bodies held by name: never fetched, never shared beyond the content that holds them. */
27
+ export interface HeldBodies {
28
+ has(name: string): boolean;
29
+ get(name: string): unknown;
30
+ }
31
+
32
+ /** One index a request can pin. */
33
+ export interface IndexedContent {
34
+ readonly revision: string;
35
+ /** `latest.json`'s `sequence` (0 for local content). */
36
+ readonly sequence: number;
37
+ /** Name → entry; a null-prototype object, so any name is an entry. */
38
+ readonly blocks: Readonly<BlockIndex>;
39
+ /** The content module's alias table (local content only). */
40
+ readonly aliases?: Readonly<Record<string, string>>;
41
+ /** Bodies in memory by name (local content, a draft's files). */
42
+ readonly held?: HeldBodies;
43
+ /** Where the other bodies come from, by hash; absent when every body is held. */
44
+ readonly source?: BodySource;
45
+ /** A draft overlay: never served on a previous index. */
46
+ readonly draft?: boolean;
47
+ }
48
+
49
+ /** The type an alias points at (the content's own table, then the legacy one), or the type itself. */
50
+ export function canonicalType(content: IndexedContent, type: string): string {
51
+ return (
52
+ own(content.aliases as Record<string, string> | undefined, type) ??
53
+ own(LEGACY_ALIASES, type) ??
54
+ type
55
+ );
56
+ }
57
+
58
+ export function hasEntry(content: IndexedContent, name: string): boolean {
59
+ return Object.hasOwn(content.blocks, name);
60
+ }
61
+
62
+ export function entryOf(content: IndexedContent, name: string): IndexEntry | undefined {
63
+ return Object.hasOwn(content.blocks, name) ? content.blocks[name] : undefined;
64
+ }
65
+
66
+ /** Whether a body comes from memory, never a fetch: held by name, or inline. */
67
+ export function bodyInMemory(content: IndexedContent, name: string): boolean {
68
+ if (content.held?.has(name)) return true;
69
+ const entry = entryOf(content, name);
70
+ return entry !== undefined && entry.data !== undefined;
71
+ }
72
+
73
+ /** Names sorted in code-unit order (the order of every listing, the same on every server). */
74
+ export function byCodeUnit(a: string, b: string): number {
75
+ return a < b ? -1 : a > b ? 1 : 0;
76
+ }
77
+
78
+ /** The type of a page, after alias mapping. */
79
+ const PAGE = "page";
80
+
81
+ export { REDIRECTS_TYPE };
82
+
83
+ interface Derived {
84
+ names: string[];
85
+ routes: Route[];
86
+ redirects: string | null;
87
+ }
88
+
89
+ const derived = new WeakMap<IndexedContent, Derived>();
90
+
91
+ /** Sorted names, routes and the redirects block's name, computed once per index object. */
92
+ function derive(content: IndexedContent): Derived {
93
+ let found = derived.get(content);
94
+ if (found !== undefined) return found;
95
+ const names = Object.keys(content.blocks).sort(byCodeUnit);
96
+ const routes: Route[] = [];
97
+ let redirects: string | null = null;
98
+ for (const name of names) {
99
+ const meta = content.blocks[name]?.meta;
100
+ if (meta?.type === undefined) continue;
101
+ const type = canonicalType(content, meta.type);
102
+ if (type === PAGE && typeof meta.path === "string") routes.push({ name, path: meta.path });
103
+ else if (type === REDIRECTS_TYPE && redirects === null) redirects = name;
104
+ }
105
+ found = { names, routes, redirects };
106
+ derived.set(content, found);
107
+ return found;
108
+ }
109
+
110
+ /** Every name, in code-unit order. */
111
+ export function namesOf(content: IndexedContent): readonly string[] {
112
+ return derive(content).names;
113
+ }
114
+
115
+ /**
116
+ * `{ name, path }` of every page entry (its `meta.type` maps to `page` and it
117
+ * has a `meta.path`), in code-unit order of name, so the same page wins a path
118
+ * conflict whatever the index's key order. The same array for the same index,
119
+ * so `matchRoute`'s per-array trie cache is the per-revision trie.
120
+ */
121
+ export function routesOf(content: IndexedContent): Route[] {
122
+ return derive(content).routes;
123
+ }
124
+
125
+ /** The redirects block: the first `redirects`-typed entry in code-unit name order, or `null`. */
126
+ export function redirectsBlockOf(content: IndexedContent): string | null {
127
+ return derive(content).redirects;
128
+ }
129
+
130
+ /** Names of entries whose type maps to `type`, in code-unit order. */
131
+ export function namesOfType(content: IndexedContent, type: string): string[] {
132
+ const wanted = canonicalType(content, type);
133
+ return namesOf(content).filter((name) => {
134
+ const t = content.blocks[name]?.meta?.type;
135
+ return t !== undefined && canonicalType(content, t) === wanted;
136
+ });
137
+ }
138
+
139
+ /**
140
+ * The walk: `roots` plus every name reachable through `meta.refs`, names the
141
+ * index doesn't have skipped.
142
+ */
143
+ export function walk(content: IndexedContent, roots: readonly string[]): string[] {
144
+ const seen = new Set<string>();
145
+ const queue = roots.filter((name) => hasEntry(content, name));
146
+ for (let i = 0; i < queue.length; i++) {
147
+ const name = queue[i]!;
148
+ if (seen.has(name)) continue;
149
+ seen.add(name);
150
+ for (const ref of content.blocks[name]?.meta?.refs ?? []) {
151
+ if (!seen.has(ref) && hasEntry(content, ref)) queue.push(ref);
152
+ }
153
+ }
154
+ return [...seen];
155
+ }
156
+
157
+ /** Local content as an index: once per snapshot object. */
158
+ const local = new WeakMap<Snapshot, IndexedContent>();
159
+
160
+ export function localIndex(snapshot: Snapshot): IndexedContent {
161
+ let found = local.get(snapshot);
162
+ if (found !== undefined) return found;
163
+ const bodies = snapshot.blocks;
164
+ const names = new Set(Object.keys(bodies));
165
+ const blocks = Object.create(null) as BlockIndex;
166
+ for (const name of names) {
167
+ const meta = blockMeta(bodies[name], names);
168
+ // Local bodies are held, so no hash is needed (or computed).
169
+ blocks[name] = Object.keys(meta).length > 0 ? { version: "", meta } : { version: "" };
170
+ }
171
+ found = {
172
+ revision: snapshot.revision,
173
+ sequence: 0,
174
+ blocks,
175
+ held: {
176
+ has: (name) => Object.hasOwn(bodies, name),
177
+ get: (name) => (Object.hasOwn(bodies, name) ? bodies[name] : undefined),
178
+ },
179
+ };
180
+ if (snapshot.aliases !== undefined) (found as { aliases?: unknown }).aliases = snapshot.aliases;
181
+ local.set(snapshot, found);
182
+ return found;
183
+ }
package/src/v8/draft.ts CHANGED
@@ -2,11 +2,11 @@
2
2
  * Draft pointers (see /next/api-reference#draft-pointers): the string
3
3
  * `<host[:port]><path[?query]>@<version>` that names a draft, and what
4
4
  * `cms.readVersion` and `cms.draftCookie` read and write to carry one (or a
5
- * published release's commit SHA) from a `?__draft=` link into a cookie. The
5
+ * published release's revision id) from a `?__draft=` link into a cookie. The
6
6
  * host check against the preview hosts is the CMS's: these read the request
7
7
  * only.
8
8
  *
9
- * A version is a draft pointer or a release's commit SHA, nothing else. A
9
+ * A version is a draft pointer or a release's revision id, nothing else. A
10
10
  * pointer's query may force variants, which are part of the draft it names:
11
11
  *
12
12
  * - `__variant=<block>@<path>=<index>`: a variant the preview forces, one per
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * A Studio preview link carries more than the version: the moment it shows
16
16
  * and the tests and campaigns it switches on or off. They ride in the same
17
- * query (a pointer's, or after a SHA: `<sha>?__at=…&__test=…`), and
17
+ * query (a pointer's, or after a revision id: `<id>?__at=…&__test=…`), and
18
18
  * `parseVersion` lifts them out into the client's other options:
19
19
  *
20
20
  * - `__at=<ISO date-time with offset>`: the client's `date`.
@@ -24,6 +24,7 @@
24
24
  * Each value is URL-encoded.
25
25
  */
26
26
  import type { Assignments } from "./experiments.ts";
27
+ import { REVISION_ID_RE } from "./revisionId.ts";
27
28
  import type { DraftPointer, ForcedVariant, RequestLike, RequestVersion } from "./types.ts";
28
29
 
29
30
  /** The draft cookie's name. Not exported from the package: reading it directly would skip the host check. */
@@ -49,27 +50,27 @@ const PREVIEW_PARAMS = [AT_PARAM, TEST_PARAM, CAMPAIGN_PARAM];
49
50
  /** An ISO 8601 date-time with its offset (`Z` or `±hh:mm`): the moment a preview shows. */
50
51
  const AT_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})$/;
51
52
  const INDEX_RE = /^(0|[1-9][0-9]{0,3})$/;
52
- /** A published release: its git commit SHA (SHA-1, 40 lowercase hex). */
53
- const REVISION_RE = /^[0-9a-f]{40}$/;
53
+ /** A published release: its revision id (`<inv>-<uuidv7>`, see ./revisionId.ts). */
54
+ const REVISION_RE = REVISION_ID_RE;
54
55
 
55
- /** A version, read: a published release (by its commit SHA) or a draft. */
56
- type ClientVersion = { kind: "revision"; sha: string } | { kind: "draft"; pointer: DraftPointer };
56
+ /** A version, read: a published release (by its revision id) or a draft. */
57
+ type ClientVersion = { kind: "revision"; id: string } | { kind: "draft"; pointer: DraftPointer };
57
58
 
58
59
  /**
59
- * What `cms.client({ version })` reads: a published release's commit SHA (40
60
- * lowercase hex, nothing after it) or a draft pointer. `null` for anything
60
+ * What `cms.client({ version })` reads: a published release's revision id
61
+ * (nothing after it) or a draft pointer. `null` for anything
61
62
  * else, a preview link's `__at`, `__test` or `__campaign` included: those
62
63
  * are the client's `date`, `experiments` and `campaigns` (`parseVersion`).
63
64
  */
64
65
  export function parseClientVersion(value: string): ClientVersion | null {
65
- if (REVISION_RE.test(value)) return { kind: "revision", sha: value };
66
+ if (REVISION_RE.test(value)) return { kind: "revision", id: value };
66
67
  const pointer = parseDraftPointer(value);
67
68
  return pointer === null ? null : { kind: "draft", pointer };
68
69
  }
69
70
 
70
71
  /**
71
72
  * A Studio link's value (what `?__draft=` and the draft cookie carry): the
72
- * version, a draft pointer or a published release's commit SHA, and the
73
+ * version, a draft pointer or a published release's revision id, and the
73
74
  * preview's moment and switched tests and campaigns, lifted out of its query
74
75
  * as the client's `date`, `experiments` and `campaigns`. `null` for a value
75
76
  * that is neither, or whose preview parameters don't parse (a second `__at`,
@@ -84,7 +85,7 @@ export function parseVersion(value: string | null | undefined): RequestVersion |
84
85
  if (REVISION_RE.test(head === -1 ? value : value.slice(0, head))) {
85
86
  if (head === -1) return { version: value };
86
87
  const preview = liftPreview(value.slice(head + 1));
87
- // After a SHA, only the preview's own parameters.
88
+ // After a revision id, only the preview's own parameters.
88
89
  if (preview === null || preview.kept.length > 0) return null;
89
90
  return { version: value.slice(0, head), ...preview.options };
90
91
  }
@@ -296,7 +297,7 @@ function normalizeIPv6Host(authority: string): string | null {
296
297
 
297
298
  /**
298
299
  * The version a request carries (a draft pointer, or a published release's
299
- * commit SHA) with its preview's date, tests and campaigns (`parseVersion`):
300
+ * revision id) with its preview's date, tests and campaigns (`parseVersion`):
300
301
  * `?__draft=` from the URL first, then the `__deco_draft`
301
302
  * cookie. `null` when neither is present, or when the URL says
302
303
  * `?__draft=off`. A value that doesn't parse is ignored, as if it were
@@ -313,7 +314,7 @@ export function readVersion(request: RequestLike): RequestVersion | null {
313
314
 
314
315
  /**
315
316
  * The `Set-Cookie` value for a request whose URL carries `?__draft=`: one that
316
- * stores the version (a draft pointer or a release's commit SHA), or one that expires the cookie when the value is `off`
317
+ * stores the version (a draft pointer or a release's revision id), or one that expires the cookie when the value is `off`
317
318
  * (how the site editor ends a preview). `null` on every other request, and for
318
319
  * a pointer that doesn't parse, so garbage never lands in the cookie.
319
320
  *
@@ -1,43 +1,50 @@
1
1
  /**
2
- * Draft changes (see /next/content-delivery#draft-previews): what a draft
3
- * pointer's address answers, and how the CMS layers it over production.
2
+ * Draft previews (see /next/content-delivery#draft-previews): what a draft
3
+ * pointer names, how the SDK reads it and how a draft is laid over production.
4
4
  *
5
5
  * - The pointer's host must fall under one of the draft hosts (the same rule
6
6
  * as v7's preview API domains): by default `*.decocms.com` (Studio, the
7
7
  * delivery CDN, `local.studio.decocms.com`) and the loopback hosts;
8
8
  * `createCMS({ preview: { draftHosts } })` replaces the list. Any other host
9
9
  * is refused before anything is fetched.
10
- * - `GET <scheme>://<host><path>?v=<version>`: the scheme comes from the
11
- * domain that admitted the host, never from the pointer: plain `http` only
12
- * for loopback hosts. The pointer's `__variant` parameters are already gone (the parser
13
- * lifts them out), no cookies or credentials are sent, and redirects aren't
14
- * followed (a response that was redirected anyway is refused).
15
- * - Every read revalidates: with a body this process already holds, it sends
16
- * `If-None-Match` with that body's ETag, and a `304` reuses the body. Only
17
- * a 200 or that 304 is accepted, within 10 s; a 200 is up to 16 MiB, shaped
18
- * exactly `{ set: { <name>: <block JSON> }, delete: [<name>…] }` with `set`
19
- * and `delete` disjoint.
10
+ * - The pointer's path is a draft folder's index,
11
+ * `/sites/<site>/drafts/<slug>/index.json` (`{ names: [...] }`, the names
12
+ * the draft holds); a path that doesn't end in `/index.json` fails. Its
13
+ * version is opaque (it changes with every save, so the preview reloads).
14
+ * - A draft read is one wave: the draft index, then every file it names
15
+ * (`<folder><file>`, the file being the name's `encodeURIComponent` plus
16
+ * `.json`, `index` written `%69ndex.json`), in parallel, plain GETs with no
17
+ * `If-None-Match` (nothing read from `drafts/` is kept across requests; the
18
+ * CDN revalidates every read with storage). The scheme comes from the domain
19
+ * that admitted the host, never from the pointer: plain `http` only for
20
+ * loopback hosts. No cookies or credentials are sent, and redirects aren't
21
+ * followed (a response that was redirected anyway is refused). Each read has
22
+ * 10 s and up to 16 MiB.
23
+ * - A file is `{ operation: "set", data }` (the block), `{ operation:
24
+ * "delete" }` or `{ operation: "published" }` (a marker publish leaves). A
25
+ * missing file (404) or a `published` marker means the name isn't in the
26
+ * draft: the file is the truth, never the draft index. A file that doesn't
27
+ * parse fails the read.
28
+ * - The overlay replaces a published entry with each `set` (its `meta` from
29
+ * `blockMeta`, its body held by the request) and removes each `delete`.
20
30
  */
31
+
32
+ import { type BlockIndex, blockMeta, type IndexEntry } from "./blockMeta.ts";
21
33
  import { readBoundedJson, timeoutSignal } from "./boundedJson.ts";
22
- import { isPlainObject } from "./json.ts";
23
- import type { DraftPointer, Snapshot } from "./types.ts";
34
+ import type { HeldBodies, IndexedContent } from "./contentIndex.ts";
35
+ import { isPlainObject, type JsonObject } from "./json.ts";
36
+ import type { DraftPointer } from "./types.ts";
24
37
 
25
- /** The version a pointer has when it names no draft: `deco serve`'s working tree. */
38
+ /** The version a pointer has when it names no draft: the release itself, with nothing fetched. */
26
39
  export const LOCAL_VERSION = "local";
27
40
 
28
41
  const TIMEOUT_MS = 10_000;
29
42
  const MAX_BYTES = 16 * 1024 * 1024;
43
+ /** The draft index's file in a draft folder. */
44
+ const DRAFT_INDEX = "index.json";
30
45
 
31
- /** What a draft changed compared with production: whole blocks, and deletions. */
32
- export interface DraftChanges {
33
- set: Record<string, unknown>;
34
- delete: string[];
35
- }
36
-
37
- /** A draft read: new changes (and their ETag), or `304`, the held body is current. */
38
- export type DraftRead =
39
- | { status: 200; changes: DraftChanges; etag: string | null }
40
- | { status: 304 };
46
+ /** What a draft holds for one name: the whole block, or its deletion. */
47
+ export type DraftState = { operation: "set"; data: JsonObject } | { operation: "delete" };
41
48
 
42
49
  /**
43
50
  * The domains a draft pointer's host may fall under, the defaults v7 shipped.
@@ -106,41 +113,93 @@ function isLoopbackDomain(domain: string): boolean {
106
113
  );
107
114
  }
108
115
 
116
+ /** The file a block's draft lives in, inside the draft folder; `index` can't be the draft index. */
117
+ export function draftFileName(name: string): string {
118
+ return name === "index" ? "%69ndex.json" : `${encodeURIComponent(name)}.json`;
119
+ }
120
+
109
121
  /**
110
- * The URL the SDK fetches for a pointer: the origin its host is admitted
111
- * under, the version as `v`. `null` when no draft host admits the host.
122
+ * The draft folder's URL for a pointer (ending in `/`), from the origin its
123
+ * host is admitted under. `null` when no draft host admits the host; throws
124
+ * when the path isn't a draft folder's index.
112
125
  */
113
- export function draftChangesUrl(
126
+ export function draftFolderUrl(
114
127
  pointer: DraftPointer,
115
128
  domains: readonly string[] = DEFAULT_DRAFT_HOSTS,
116
129
  ): string | null {
117
130
  const origin = previewApiOrigin(pointer.host, domains);
118
131
  if (origin === null) return null;
119
- const separator = pointer.path.includes("?") ? "&" : "?";
120
- return `${origin}${pointer.path}${separator}v=${encodeURIComponent(pointer.version)}`;
132
+ const q = pointer.path.indexOf("?");
133
+ const path = q === -1 ? pointer.path : pointer.path.slice(0, q);
134
+ if (!path.endsWith(`/${DRAFT_INDEX}`)) {
135
+ throw new Error("draft pointer: not a draft folder (the path must end in /index.json)");
136
+ }
137
+ return `${origin}${path.slice(0, -DRAFT_INDEX.length)}`;
121
138
  }
122
139
 
123
140
  /**
124
- * Reads a draft's changes, revalidating `etag` (the ETag of the body the
125
- * caller holds) when given. Rejects on a host no draft host admits
126
- * (without fetching), on a `304` to a request that sent no ETag, and on any
127
- * other failure.
141
+ * Reads a draft: its index, then every file it names, in one parallel wave.
142
+ * Resolves with the names the draft sets or deletes. Rejects on a host no
143
+ * draft host admits (without fetching), a path that isn't a draft folder, and
144
+ * any failure but a missing file.
128
145
  */
129
- export async function fetchDraftChanges(
146
+ export async function fetchDraft(
130
147
  pointer: DraftPointer,
131
- options: { domains?: readonly string[]; etag?: string | null } = {},
132
- ): Promise<DraftRead> {
133
- const url = draftChangesUrl(pointer, options.domains);
134
- if (url === null) {
148
+ options: { domains?: readonly string[] } = {},
149
+ ): Promise<Map<string, DraftState>> {
150
+ const folder = draftFolderUrl(pointer, options.domains);
151
+ if (folder === null) {
135
152
  throw new Error(
136
153
  `draft pointer names "${pointer.host}", which isn't under a draft host ` +
137
154
  "(createCMS({ preview: { draftHosts } })); nothing was fetched",
138
155
  );
139
156
  }
140
- const headers: Record<string, string> = { accept: "application/json" };
141
- if (options.etag) headers["if-none-match"] = options.etag;
157
+ const index = await getJson(`${folder}${DRAFT_INDEX}`, "draft index");
158
+ if (index === undefined) throw new Error("draft index: HTTP 404");
159
+ const names = draftIndexNames(index);
160
+ const files = await Promise.all(
161
+ names.map((name) =>
162
+ getJson(`${folder}${encodeURIComponent(draftFileName(name))}`, `draft file "${name}"`),
163
+ ),
164
+ );
165
+ const states = new Map<string, DraftState>();
166
+ names.forEach((name, i) => {
167
+ const state = parseDraftFile(files[i], name);
168
+ if (state !== null) states.set(name, state);
169
+ });
170
+ return states;
171
+ }
172
+
173
+ /** `{ names: [...] }`: the strings, deduped, in their order. */
174
+ function draftIndexNames(body: unknown): string[] {
175
+ if (!isPlainObject(body) || !Array.isArray(body.names)) {
176
+ throw new Error("draft index: expected { names: [...] }");
177
+ }
178
+ return [...new Set(body.names.filter((name): name is string => typeof name === "string"))];
179
+ }
180
+
181
+ /** A draft file: what it holds, or `null` for a missing file or a `published` marker. */
182
+ export function parseDraftFile(body: unknown, name: string): DraftState | null {
183
+ if (body === undefined) return null;
184
+ const invalid = () => new Error(`draft file "${name}": unexpected format`);
185
+ if (!isPlainObject(body)) throw invalid();
186
+ switch (body.operation) {
187
+ case "set":
188
+ if (!isPlainObject(body.data)) throw invalid();
189
+ return { operation: "set", data: body.data };
190
+ case "delete":
191
+ return { operation: "delete" };
192
+ case "published":
193
+ return null;
194
+ default:
195
+ throw invalid();
196
+ }
197
+ }
198
+
199
+ /** GETs a draft object: its JSON, or `undefined` for a 404. */
200
+ async function getJson(url: string, label: string): Promise<unknown> {
142
201
  const response = await fetch(url, {
143
- headers,
202
+ headers: { accept: "application/json" },
144
203
  redirect: "manual",
145
204
  signal: timeoutSignal(TIMEOUT_MS),
146
205
  });
@@ -151,58 +210,65 @@ export async function fetchDraftChanges(
151
210
  (response.url && new URL(response.url).origin !== new URL(url).origin)
152
211
  ) {
153
212
  await response.body?.cancel();
154
- throw new Error("draft changes: the pointer's address redirected; nothing was read");
213
+ throw new Error(`${label}: the pointer's address redirected; nothing was read`);
155
214
  }
156
- if (response.status === 304 && options.etag) {
215
+ if (response.status === 404) {
157
216
  await response.body?.cancel();
158
- return { status: 304 };
217
+ return undefined;
159
218
  }
160
219
  if (response.status !== 200) {
161
220
  await response.body?.cancel();
162
- throw new Error(`draft changes: HTTP ${response.status}`);
221
+ throw new Error(`${label}: HTTP ${response.status}`);
163
222
  }
164
- const etag = response.headers.get("etag");
165
- const changes = parseDraftChanges(await readBoundedJson(response, "draft changes", MAX_BYTES));
166
- return { status: 200, changes, etag };
167
- }
168
-
169
- /** Validates a draft changes response; throws on any unexpected shape. */
170
- export function parseDraftChanges(body: unknown): DraftChanges {
171
- const invalid = (why: string) => new Error(`draft changes: ${why}`);
172
- if (!isPlainObject(body)) throw invalid("expected an object");
173
- if (Object.keys(body).some((key) => key !== "set" && key !== "delete")) {
174
- throw invalid("unexpected field");
175
- }
176
- const { set, delete: deleted } = body;
177
- if (!isPlainObject(set)) throw invalid("set must be an object");
178
- if (!Array.isArray(deleted) || deleted.some((name) => typeof name !== "string")) {
179
- throw invalid("delete must be a list of names");
180
- }
181
- if (deleted.some((name) => Object.hasOwn(set, name))) throw invalid("set and delete overlap");
182
- return body as unknown as DraftChanges;
223
+ return readBoundedJson(response, label, MAX_BYTES);
183
224
  }
184
225
 
185
226
  /**
186
- * The draft as a snapshot: production's entries, with the changed ones
187
- * replaced whole and the deleted ones gone. A shallow copy: every unchanged
188
- * entry is production's own object, and production is never mutated. Its
189
- * revision, `<base revision>~<view>`, is an opaque identity of the pair,
190
- * never a release's; `view` names the draft body (its ETag), so each save
191
- * re-keys what's cached by revision.
227
+ * The draft over `base`: each `set` replaces (or adds) the entry, with its
228
+ * `meta` from `blockMeta` over the overlaid names and its body held by this
229
+ * content only; each `delete` removes the entry. Production is never mutated.
230
+ * Its revision, `<base revision>~<view>`, is an opaque identity of the pair,
231
+ * never a release's.
192
232
  */
193
- export function layerDraft(base: Snapshot, changes: DraftChanges, view: string): Snapshot {
194
- const blocks: Record<string, unknown> = { ...base.blocks };
195
- for (const name of changes.delete) delete blocks[name];
196
- for (const [name, entry] of Object.entries(changes.set)) {
197
- // defineProperty, so an entry named "__proto__" stays an entry.
198
- Object.defineProperty(blocks, name, {
199
- value: entry,
200
- enumerable: true,
201
- writable: true,
202
- configurable: true,
203
- });
233
+ export function overlayDraft(
234
+ base: IndexedContent,
235
+ states: ReadonlyMap<string, DraftState>,
236
+ view: string,
237
+ ): IndexedContent {
238
+ const names = new Set(Object.keys(base.blocks));
239
+ const bodies = new Map<string, unknown>();
240
+ for (const [name, state] of states) {
241
+ if (state.operation === "delete") names.delete(name);
242
+ else {
243
+ names.add(name);
244
+ bodies.set(name, state.data);
245
+ }
246
+ }
247
+ const blocks = Object.create(null) as BlockIndex;
248
+ for (const name of names) {
249
+ if (bodies.has(name)) {
250
+ const meta = blockMeta(bodies.get(name), names);
251
+ const entry: IndexEntry = { version: "" };
252
+ if (Object.keys(meta).length > 0) entry.meta = meta;
253
+ blocks[name] = entry;
254
+ } else {
255
+ blocks[name] = base.blocks[name] as IndexEntry;
256
+ }
204
257
  }
205
- const layered: Snapshot = { revision: `${base.revision}~${view}`, blocks };
206
- if (base.aliases !== undefined) layered.aliases = base.aliases;
207
- return layered;
258
+ const baseHeld = base.held;
259
+ const held: HeldBodies = {
260
+ has: (name) => bodies.has(name) || (!states.has(name) && baseHeld?.has(name) === true),
261
+ get: (name) =>
262
+ bodies.has(name) ? bodies.get(name) : states.has(name) ? undefined : baseHeld?.get(name),
263
+ };
264
+ const content: IndexedContent = {
265
+ revision: `${base.revision}~${view}`,
266
+ sequence: base.sequence,
267
+ blocks,
268
+ held,
269
+ draft: true,
270
+ };
271
+ if (base.aliases !== undefined) (content as { aliases?: unknown }).aliases = base.aliases;
272
+ if (base.source !== undefined) (content as { source?: unknown }).source = base.source;
273
+ return content;
208
274
  }
package/src/v8/errors.ts CHANGED
@@ -19,6 +19,34 @@ export class ResolutionError extends Error implements CMSError {
19
19
  }
20
20
  }
21
21
 
22
+ /** Why the content couldn't be read from the delivery CDN (`ContentUnavailableError.reason`). */
23
+ export type ContentUnavailableReason = "timeout" | "network" | "http" | "format";
24
+
25
+ /**
26
+ * The content couldn't be read from the delivery CDN: a fetch ran out of its
27
+ * 10 s (`"timeout"`), failed (`"network"`), was answered with an HTTP error
28
+ * (`"http"`, with `status`; a site that has published nothing yet is a 404),
29
+ * or the body wasn't a release (`"format"`: malformed, or too large). It is
30
+ * the `cause` of the `LOADER_FAILED` error a client reports (`resolve` and
31
+ * `list` answer it, `revision()` rejects with it), so a site can tell it
32
+ * apart and choose what to render: a 503, a fallback, a retry.
33
+ */
34
+ export class ContentUnavailableError extends Error {
35
+ readonly reason: ContentUnavailableReason;
36
+ readonly status?: number;
37
+
38
+ constructor(
39
+ reason: ContentUnavailableReason,
40
+ message: string,
41
+ options: { status?: number; cause?: unknown } = {},
42
+ ) {
43
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
44
+ this.name = "ContentUnavailableError";
45
+ this.reason = reason;
46
+ if (options.status !== undefined) this.status = options.status;
47
+ }
48
+ }
49
+
22
50
  export function isResolutionError(value: unknown): value is ResolutionError {
23
51
  return value instanceof ResolutionError;
24
52
  }
@@ -49,6 +77,15 @@ export const errors = {
49
77
  blockFailed: (type: string, path: (string | number)[], cause: unknown) =>
50
78
  new ResolutionError("BLOCK_FAILED", `block "${type}" failed: ${describe(cause)}`, path, cause),
51
79
 
80
+ /** A saved block whose body couldn't be fetched: its section fails, not the page. */
81
+ blockUnavailable: (name: string, path: (string | number)[], cause: unknown) =>
82
+ new ResolutionError(
83
+ "LOADER_FAILED",
84
+ `the saved block "${name}" couldn't be fetched: ${describe(cause)}`,
85
+ path,
86
+ cause,
87
+ ),
88
+
52
89
  loaderFailed: (message: string, cause?: unknown) =>
53
90
  new ResolutionError(
54
91
  "LOADER_FAILED",