@decocms/blocks 8.9.1 → 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
@@ -1,296 +0,0 @@
1
- /**
2
- * `deco serve`: the local server the site editor uses to edit the files on
3
- * this machine (spec: cli › deco serve; content-protocol › The local server).
4
- *
5
- * The content protocol is `@decocms/blocks/protocol`'s `createContentHandler`
6
- * (at `/rpc`) and `createAssetHandler` (at `/assets/<name>`) over the
7
- * filesystem storage; they own `Content-Type`, size limits and upload rules.
8
- * `deco serve` has no authentication and answers any origin: any website open
9
- * in the browser can read and write the content through it, so it is meant
10
- * to run only while editing. This file is the Node HTTP layer:
11
- *
12
- * - Listens on loopback, 127.0.0.1 and ::1 on one port, so
13
- * `http://localhost:<port>` reaches it whichever address the OS gives
14
- * localhost; `--host` listens on that one address instead (with a warning
15
- * beyond loopback: the network can reach it then).
16
- * - CORS is answered for any `Origin` (reflected, with `Vary: Origin`), and
17
- * so are Chrome's Private/Local Network Access preflights.
18
- * - Every save regenerates `.deco/blocks.gen.ts`.
19
- * - It runs only inside the site's git repository: the content's base (what
20
- * the site editor's change list compares with, and what a discard
21
- * restores) is the local git `HEAD`. Outside a git work tree, or without
22
- * git installed, it refuses to start and says what to run.
23
- */
24
- import fs from "node:fs";
25
- import http from "node:http";
26
- import path from "node:path";
27
- import { Readable } from "node:stream";
28
- import { ErrorCode } from "../../../protocol/errors.js";
29
- import { blockNameFromFile } from "../../../protocol/keys.js";
30
- import { createAssetHandler } from "../../../protocol/server/assets.js";
31
- import { createContentHandler } from "../../../protocol/server/index.js";
32
- import { checkGitWorkTree, UNBORN_REVISION } from "../../../protocol/storage/fs/git.js";
33
- import { createFsStorage } from "../../../protocol/storage/fs/index.js";
34
- import { readSavedBlocks, writeContent } from "../content.js";
35
- import { consoleReporter } from "../log.js";
36
- import { CliError, decoPaths, findDecoRoot, packageVersion } from "../root.js";
37
- /** Where the site editor link points. */
38
- const STUDIO_ORIGIN = "https://studio.decocms.com";
39
- const DEFAULT_PORT = 4545;
40
- /** Where it listens without `--host`; ::1 is skipped where IPv6 is unavailable. */
41
- const DEFAULT_HOSTS = ["127.0.0.1", "::1"];
42
- const LOOPBACK = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
43
- /** The app the site editor previews when `--preview` isn't given and no Vite port is set. */
44
- export const DEFAULT_PREVIEW_URL = "http://localhost:5173";
45
- const VITE_CONFIGS = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"];
46
- /**
47
- * `http://localhost:<server.port>` from the app's Vite config, read as text
48
- * (the config is never executed), or `DEFAULT_PREVIEW_URL`.
49
- */
50
- function defaultPreviewUrl(root) {
51
- for (const name of VITE_CONFIGS) {
52
- let source;
53
- try {
54
- source = fs.readFileSync(path.join(root, name), "utf8");
55
- }
56
- catch {
57
- continue;
58
- }
59
- const port = /\bserver\s*:\s*\{[^}]*?\bport\s*:\s*(\d{2,5})\b/.exec(source)?.[1];
60
- return port ? `http://localhost:${port}` : DEFAULT_PREVIEW_URL;
61
- }
62
- return DEFAULT_PREVIEW_URL;
63
- }
64
- /**
65
- * `--preview` as a URL: a bare `host:port` gets `http://`; only http(s) on a
66
- * loopback host, since the site editor loads it in an iframe.
67
- */
68
- function previewUrl(input) {
69
- const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(input) ? input : `http://${input}`;
70
- const url = URL.canParse(withScheme) ? new URL(withScheme) : null;
71
- if (!url || !/^https?:$/.test(url.protocol) || !LOOPBACK.has(url.hostname)) {
72
- throw new CliError(`--preview must be a local address such as localhost:5173 or http://127.0.0.1:3000, got ${input}`);
73
- }
74
- return url.pathname === "/" && !url.search && !url.hash ? url.origin : url.href;
75
- }
76
- /**
77
- * Refuses to serve a folder that isn't inside a git work tree: every source
78
- * of the protocol has a base, and `deco serve`'s is the local `HEAD`.
79
- */
80
- async function requireGitWorkTree(root, git) {
81
- const check = await checkGitWorkTree(root, { git });
82
- if (check.status === "ok")
83
- return;
84
- if (check.status === "missing") {
85
- throw new CliError("deco serve needs git, and it isn't installed here. Install git (https://git-scm.com/downloads), " +
86
- "then run deco serve again inside your site's git repository.");
87
- }
88
- if (check.status === "not-a-repository") {
89
- throw new CliError(`deco serve runs inside your site's git repository, and ${root} isn't in one. ` +
90
- "Run it in the folder where you cloned the site, or run git init there first, then start deco serve again.");
91
- }
92
- throw new CliError(`deco serve couldn't use the git repository at ${root}: ${check.message}`);
93
- }
94
- /** Start the server; resolves once it listens. */
95
- export async function startServer(options = {}) {
96
- const reporter = options.reporter ?? consoleReporter;
97
- const paths = decoPaths(findDecoRoot(options));
98
- const host = options.host?.toLowerCase();
99
- const requestedPort = options.port ?? DEFAULT_PORT;
100
- const readOnly = options.readOnly ?? false;
101
- const preview = previewUrl(options.preview ?? defaultPreviewUrl(paths.root));
102
- if (!Number.isInteger(requestedPort) || requestedPort < 0 || requestedPort > 65535) {
103
- throw new CliError(`--port must be a port number, got ${requestedPort}`);
104
- }
105
- await requireGitWorkTree(paths.root, options.git);
106
- const fsStorage = createFsStorage({
107
- root: paths.root,
108
- readOnly,
109
- assetsDir: options.assets,
110
- git: options.git,
111
- });
112
- const storage = {
113
- ...fsStorage,
114
- async commit(attempt) {
115
- const result = await fsStorage.commit(attempt);
116
- if (result.status !== "committed")
117
- return result;
118
- const names = [...Object.keys(attempt.put), ...attempt.delete].map(blockNameFromFile);
119
- const blocks = `${names.length} block${names.length === 1 ? "" : "s"}: ${names.join(", ")}`;
120
- reporter.info(attempt.reason === "discard" ? `discarded changes to ${blocks}` : `saved ${blocks}`);
121
- // Every save changes the content, so the content module's revision
122
- // changes too (a revision is never reused for different content). An
123
- // unchanged module isn't rewritten, so this costs nothing when it isn't.
124
- try {
125
- await writeContent(paths);
126
- }
127
- catch (error) {
128
- reporter.warn(`couldn't regenerate .deco/blocks.gen.ts: ${error.message}`);
129
- }
130
- return result;
131
- },
132
- async putAsset(name, body) {
133
- const stored = await fsStorage.putAsset(name, body);
134
- reporter.info(`uploaded /assets/${stored.name}`);
135
- return stored;
136
- },
137
- };
138
- const rpc = createContentHandler(storage, {
139
- server: { name: "deco-cli", version: packageVersion() },
140
- preview: { url: preview },
141
- onError: (error) => reporter.warn(String(error?.message ?? error)),
142
- });
143
- const assets = createAssetHandler(storage);
144
- const handle = async (req, res) => {
145
- const origin = req.headers.origin;
146
- const cors = {};
147
- const refuse = (status, code, message) => {
148
- res.writeHead(status, { "content-type": "application/json", ...cors });
149
- res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code, message } }));
150
- };
151
- try {
152
- if (origin !== undefined) {
153
- cors["access-control-allow-origin"] = origin;
154
- cors.vary = "Origin";
155
- }
156
- if (req.method === "OPTIONS") {
157
- const preflight = {
158
- "access-control-allow-methods": "POST, PUT, OPTIONS",
159
- "access-control-allow-headers": "content-type",
160
- "access-control-max-age": "600",
161
- };
162
- // Chrome's Local Network Access / Private Network Access preflight.
163
- if (req.headers["access-control-request-private-network"] === "true") {
164
- preflight["access-control-allow-private-network"] = "true";
165
- }
166
- res.writeHead(204, { ...cors, ...preflight });
167
- return res.end();
168
- }
169
- const { pathname } = new URL(req.url ?? "/", "http://localhost");
170
- const handler = pathname === "/rpc" ? rpc : pathname.startsWith("/assets/") ? assets : undefined;
171
- if (!handler)
172
- return refuse(404, ErrorCode.NotFound, "not found");
173
- const response = await handler(toRequest(req));
174
- const headers = Object.fromEntries(response.headers);
175
- res.writeHead(response.status, { ...headers, "cache-control": "no-store", ...cors });
176
- res.end(Buffer.from(await response.arrayBuffer()));
177
- }
178
- catch (error) {
179
- refuse(500, ErrorCode.InternalError, error.message);
180
- }
181
- };
182
- const servers = await listen(handle, host ? [host] : DEFAULT_HOSTS, requestedPort);
183
- const port = servers[0].address().port;
184
- const displayHost = !host ? "localhost" : host.includes(":") ? `[${host}]` : host;
185
- const endpoint = `http://${displayHost}:${port}/rpc`;
186
- // The site editor connects only through loopback; a wildcard address
187
- // listens there too, so its link uses localhost.
188
- const wildcard = host === "0.0.0.0" || host === "::";
189
- const linkEndpoint = wildcard ? `http://localhost:${port}/rpc` : endpoint;
190
- const siteEditorUrl = `${STUDIO_ORIGIN}/site-editor#endpoint=${encodeURIComponent(linkEndpoint)}`;
191
- if (host && !LOOPBACK.has(host)) {
192
- reporter.warn(`warning: listening on ${host}: other machines on the network can reach this server and read and write the content` +
193
- (wildcard ? "" : "; the site editor connects only through localhost"));
194
- }
195
- const schemaFile = fs.existsSync(paths.schema)
196
- ? ".deco/schema.gen.json"
197
- : fs.existsSync(paths.legacySchema)
198
- ? ".deco/meta.gen.json"
199
- : "no schema yet: run deco schema for typed forms";
200
- const count = Object.keys(readSavedBlocks(paths.blocks).blocks).length;
201
- const description = await storage.describe();
202
- const base = await storage.base().catch(() => null);
203
- const label = (name) => name.padEnd(21);
204
- reporter.info(`${label("Deco server")}${endpoint}`);
205
- reporter.info(`${label("Root")}${description.root} (${schemaFile}, ${count} blocks)`);
206
- reporter.info(description.assets
207
- ? `${label("Assets")}${description.assets.dir} (PUT /assets/<name>)`
208
- : `${label("Assets")}read-only: uploads are off`);
209
- reporter.info(`${label("Preview")}${preview}`);
210
- if (base) {
211
- const commit = base.revision === UNBORN_REVISION ? "no commits yet" : base.revision.slice(0, 7);
212
- reporter.info(`${label("Changes")}compared with ${base.resolvedRef ?? "detached HEAD"} (${commit})`);
213
- }
214
- reporter.info(`${label("Site editor")}${siteEditorUrl}`);
215
- return {
216
- endpoint,
217
- siteEditorUrl,
218
- port,
219
- close: () => Promise.all(servers.map(close)).then(() => undefined),
220
- };
221
- }
222
- /**
223
- * One server per address, all on the port the first one gets. An address
224
- * after the first that the machine doesn't have (::1 without IPv6) is
225
- * skipped; with port 0, a port the next address can't take is tried again.
226
- */
227
- async function listen(handle, hosts, requestedPort) {
228
- for (let attempt = 0;; attempt++) {
229
- const servers = [];
230
- let port = requestedPort;
231
- try {
232
- for (const [i, host] of hosts.entries()) {
233
- const server = http.createServer(handle);
234
- try {
235
- await new Promise((resolve, reject) => {
236
- server.once("error", reject);
237
- server.listen(port, host, () => resolve());
238
- });
239
- }
240
- catch (error) {
241
- const code = error.code;
242
- if (i > 0 && (code === "EADDRNOTAVAIL" || code === "EAFNOSUPPORT"))
243
- continue;
244
- throw error;
245
- }
246
- servers.push(server);
247
- port = server.address().port;
248
- }
249
- return servers;
250
- }
251
- catch (error) {
252
- await Promise.all(servers.map(close));
253
- if (error.code !== "EADDRINUSE")
254
- throw error;
255
- if (requestedPort === 0 && attempt < 5)
256
- continue;
257
- throw new CliError(`port ${port} is in use; pass --port`);
258
- }
259
- }
260
- }
261
- function close(server) {
262
- return new Promise((resolve) => {
263
- server.closeAllConnections?.();
264
- server.close(() => resolve());
265
- });
266
- }
267
- /** A Node request as a fetch `Request`, its body streamed. */
268
- function toRequest(req) {
269
- const headers = new Headers();
270
- for (const [key, value] of Object.entries(req.headers)) {
271
- if (Array.isArray(value))
272
- for (const v of value)
273
- headers.append(key, v);
274
- else if (value !== undefined)
275
- headers.set(key, value);
276
- }
277
- const hasBody = req.method !== "GET" && req.method !== "HEAD";
278
- return new Request(new URL(req.url ?? "/", "http://localhost"), {
279
- method: req.method,
280
- headers,
281
- body: hasBody ? Readable.toWeb(req) : undefined,
282
- duplex: "half",
283
- });
284
- }
285
- /** `deco serve`: start, then run until interrupted. */
286
- export async function serve(options = {}) {
287
- const running = await startServer(options);
288
- await new Promise((resolve) => {
289
- const stop = () => resolve();
290
- process.once("SIGINT", stop);
291
- process.once("SIGTERM", stop);
292
- });
293
- await running.close();
294
- return 0;
295
- }
296
- //# sourceMappingURL=server.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../../../src/v8/cli/serve/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AACxD,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAC;AACxE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AACxF,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAExE,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAiB,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAE/E,yCAAyC;AACzC,MAAM,aAAa,GAAG,4BAA4B,CAAC;AAEnD,MAAM,YAAY,GAAG,IAAI,CAAC;AAC1B,mFAAmF;AACnF,MAAM,aAAa,GAAG,CAAC,WAAW,EAAE,KAAK,CAAC,CAAC;AAE3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QAClC,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC;QAC7B,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QAC7B,OAAO,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC,CAAC,CAAC;IACH,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC;IACtB,OAAO,CAAC,CAAC;AACX,CAAC"}
@@ -1,348 +0,0 @@
1
- /**
2
- * `deco serve`: the local server the site editor uses to edit the files on
3
- * this machine (spec: cli › deco serve; content-protocol › The local server).
4
- *
5
- * The content protocol is `@decocms/blocks/protocol`'s `createContentHandler`
6
- * (at `/rpc`) and `createAssetHandler` (at `/assets/<name>`) over the
7
- * filesystem storage; they own `Content-Type`, size limits and upload rules.
8
- * `deco serve` has no authentication and answers any origin: any website open
9
- * in the browser can read and write the content through it, so it is meant
10
- * to run only while editing. This file is the Node HTTP layer:
11
- *
12
- * - Listens on loopback, 127.0.0.1 and ::1 on one port, so
13
- * `http://localhost:<port>` reaches it whichever address the OS gives
14
- * localhost; `--host` listens on that one address instead (with a warning
15
- * beyond loopback: the network can reach it then).
16
- * - CORS is answered for any `Origin` (reflected, with `Vary: Origin`), and
17
- * so are Chrome's Private/Local Network Access preflights.
18
- * - Every save regenerates `.deco/blocks.gen.ts`.
19
- * - It runs only inside the site's git repository: the content's base (what
20
- * the site editor's change list compares with, and what a discard
21
- * restores) is the local git `HEAD`. Outside a git work tree, or without
22
- * git installed, it refuses to start and says what to run.
23
- */
24
- import fs from "node:fs";
25
- import http from "node:http";
26
- import type { AddressInfo } from "node:net";
27
- import path from "node:path";
28
- import { Readable } from "node:stream";
29
- import { ErrorCode } from "../../../protocol/errors.ts";
30
- import { blockNameFromFile } from "../../../protocol/keys.ts";
31
- import { createAssetHandler } from "../../../protocol/server/assets.ts";
32
- import { createContentHandler } from "../../../protocol/server/index.ts";
33
- import { checkGitWorkTree, UNBORN_REVISION } from "../../../protocol/storage/fs/git.ts";
34
- import { createFsStorage } from "../../../protocol/storage/fs/index.ts";
35
- import type { ContentStorage } from "../../../protocol/storage.ts";
36
- import { readSavedBlocks, writeContent } from "../content.ts";
37
- import { consoleReporter, type Reporter } from "../log.ts";
38
- import { CliError, decoPaths, findDecoRoot, packageVersion } from "../root.ts";
39
-
40
- /** Where the site editor link points. */
41
- const STUDIO_ORIGIN = "https://studio.decocms.com";
42
-
43
- const DEFAULT_PORT = 4545;
44
- /** Where it listens without `--host`; ::1 is skipped where IPv6 is unavailable. */
45
- const DEFAULT_HOSTS = ["127.0.0.1", "::1"];
46
-
47
- const LOOPBACK = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
48
-
49
- export interface ServeOptions {
50
- root?: string;
51
- cwd?: string;
52
- port?: number;
53
- host?: string;
54
- /** The local app the site editor previews: `localhost:8001` or a full loopback URL. */
55
- preview?: string;
56
- /** The upload folder, relative to the folder that contains `.deco`. */
57
- assets?: string;
58
- readOnly?: boolean;
59
- reporter?: Reporter;
60
- /** The git binary (default `git`, from `PATH`); tests point it elsewhere. */
61
- git?: string;
62
- }
63
-
64
- export interface RunningServer {
65
- /** The content protocol endpoint, `http://localhost:4545/rpc`. */
66
- endpoint: string;
67
- siteEditorUrl: string;
68
- port: number;
69
- close(): Promise<void>;
70
- }
71
-
72
- /** The app the site editor previews when `--preview` isn't given and no Vite port is set. */
73
- export const DEFAULT_PREVIEW_URL = "http://localhost:5173";
74
-
75
- const VITE_CONFIGS = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"];
76
-
77
- /**
78
- * `http://localhost:<server.port>` from the app's Vite config, read as text
79
- * (the config is never executed), or `DEFAULT_PREVIEW_URL`.
80
- */
81
- function defaultPreviewUrl(root: string): string {
82
- for (const name of VITE_CONFIGS) {
83
- let source: string;
84
- try {
85
- source = fs.readFileSync(path.join(root, name), "utf8");
86
- } catch {
87
- continue;
88
- }
89
- const port = /\bserver\s*:\s*\{[^}]*?\bport\s*:\s*(\d{2,5})\b/.exec(source)?.[1];
90
- return port ? `http://localhost:${port}` : DEFAULT_PREVIEW_URL;
91
- }
92
- return DEFAULT_PREVIEW_URL;
93
- }
94
-
95
- /**
96
- * `--preview` as a URL: a bare `host:port` gets `http://`; only http(s) on a
97
- * loopback host, since the site editor loads it in an iframe.
98
- */
99
- function previewUrl(input: string): string {
100
- const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(input) ? input : `http://${input}`;
101
- const url = URL.canParse(withScheme) ? new URL(withScheme) : null;
102
- if (!url || !/^https?:$/.test(url.protocol) || !LOOPBACK.has(url.hostname)) {
103
- throw new CliError(
104
- `--preview must be a local address such as localhost:5173 or http://127.0.0.1:3000, got ${input}`,
105
- );
106
- }
107
- return url.pathname === "/" && !url.search && !url.hash ? url.origin : url.href;
108
- }
109
-
110
- /**
111
- * Refuses to serve a folder that isn't inside a git work tree: every source
112
- * of the protocol has a base, and `deco serve`'s is the local `HEAD`.
113
- */
114
- async function requireGitWorkTree(root: string, git: string | undefined): Promise<void> {
115
- const check = await checkGitWorkTree(root, { git });
116
- if (check.status === "ok") return;
117
- if (check.status === "missing") {
118
- throw new CliError(
119
- "deco serve needs git, and it isn't installed here. Install git (https://git-scm.com/downloads), " +
120
- "then run deco serve again inside your site's git repository.",
121
- );
122
- }
123
- if (check.status === "not-a-repository") {
124
- throw new CliError(
125
- `deco serve runs inside your site's git repository, and ${root} isn't in one. ` +
126
- "Run it in the folder where you cloned the site, or run git init there first, then start deco serve again.",
127
- );
128
- }
129
- throw new CliError(`deco serve couldn't use the git repository at ${root}: ${check.message}`);
130
- }
131
-
132
- /** Start the server; resolves once it listens. */
133
- export async function startServer(options: ServeOptions = {}): Promise<RunningServer> {
134
- const reporter = options.reporter ?? consoleReporter;
135
- const paths = decoPaths(findDecoRoot(options));
136
- const host = options.host?.toLowerCase();
137
- const requestedPort = options.port ?? DEFAULT_PORT;
138
- const readOnly = options.readOnly ?? false;
139
- const preview = previewUrl(options.preview ?? defaultPreviewUrl(paths.root));
140
-
141
- if (!Number.isInteger(requestedPort) || requestedPort < 0 || requestedPort > 65535) {
142
- throw new CliError(`--port must be a port number, got ${requestedPort}`);
143
- }
144
-
145
- await requireGitWorkTree(paths.root, options.git);
146
-
147
- const fsStorage = createFsStorage({
148
- root: paths.root,
149
- readOnly,
150
- assetsDir: options.assets,
151
- git: options.git,
152
- });
153
- const storage: ContentStorage = {
154
- ...fsStorage,
155
- async commit(attempt) {
156
- const result = await fsStorage.commit(attempt);
157
- if (result.status !== "committed") return result;
158
- const names = [...Object.keys(attempt.put), ...attempt.delete].map(blockNameFromFile);
159
- const blocks = `${names.length} block${names.length === 1 ? "" : "s"}: ${names.join(", ")}`;
160
- reporter.info(
161
- attempt.reason === "discard" ? `discarded changes to ${blocks}` : `saved ${blocks}`,
162
- );
163
- // Every save changes the content, so the content module's revision
164
- // changes too (a revision is never reused for different content). An
165
- // unchanged module isn't rewritten, so this costs nothing when it isn't.
166
- try {
167
- await writeContent(paths);
168
- } catch (error) {
169
- reporter.warn(`couldn't regenerate .deco/blocks.gen.ts: ${(error as Error).message}`);
170
- }
171
- return result;
172
- },
173
- async putAsset(name, body) {
174
- const stored = await fsStorage.putAsset!(name, body);
175
- reporter.info(`uploaded /assets/${stored.name}`);
176
- return stored;
177
- },
178
- };
179
- const rpc = createContentHandler(storage, {
180
- server: { name: "deco-cli", version: packageVersion() },
181
- preview: { url: preview },
182
- onError: (error) => reporter.warn(String((error as Error)?.message ?? error)),
183
- });
184
- const assets = createAssetHandler(storage);
185
-
186
- const handle: http.RequestListener = async (req, res) => {
187
- const origin = req.headers.origin;
188
- const cors: Record<string, string> = {};
189
- const refuse = (status: number, code: number, message: string) => {
190
- res.writeHead(status, { "content-type": "application/json", ...cors });
191
- res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code, message } }));
192
- };
193
-
194
- try {
195
- if (origin !== undefined) {
196
- cors["access-control-allow-origin"] = origin;
197
- cors.vary = "Origin";
198
- }
199
- if (req.method === "OPTIONS") {
200
- const preflight: Record<string, string> = {
201
- "access-control-allow-methods": "POST, PUT, OPTIONS",
202
- "access-control-allow-headers": "content-type",
203
- "access-control-max-age": "600",
204
- };
205
- // Chrome's Local Network Access / Private Network Access preflight.
206
- if (req.headers["access-control-request-private-network"] === "true") {
207
- preflight["access-control-allow-private-network"] = "true";
208
- }
209
- res.writeHead(204, { ...cors, ...preflight });
210
- return res.end();
211
- }
212
-
213
- const { pathname } = new URL(req.url ?? "/", "http://localhost");
214
- const handler =
215
- pathname === "/rpc" ? rpc : pathname.startsWith("/assets/") ? assets : undefined;
216
- if (!handler) return refuse(404, ErrorCode.NotFound, "not found");
217
- const response = await handler(toRequest(req));
218
- const headers = Object.fromEntries(response.headers);
219
- res.writeHead(response.status, { ...headers, "cache-control": "no-store", ...cors });
220
- res.end(Buffer.from(await response.arrayBuffer()));
221
- } catch (error) {
222
- refuse(500, ErrorCode.InternalError, (error as Error).message);
223
- }
224
- };
225
-
226
- const servers = await listen(handle, host ? [host] : DEFAULT_HOSTS, requestedPort);
227
- const port = (servers[0].address() as AddressInfo).port;
228
-
229
- const displayHost = !host ? "localhost" : host.includes(":") ? `[${host}]` : host;
230
- const endpoint = `http://${displayHost}:${port}/rpc`;
231
- // The site editor connects only through loopback; a wildcard address
232
- // listens there too, so its link uses localhost.
233
- const wildcard = host === "0.0.0.0" || host === "::";
234
- const linkEndpoint = wildcard ? `http://localhost:${port}/rpc` : endpoint;
235
- const siteEditorUrl = `${STUDIO_ORIGIN}/site-editor#endpoint=${encodeURIComponent(linkEndpoint)}`;
236
-
237
- if (host && !LOOPBACK.has(host)) {
238
- reporter.warn(
239
- `warning: listening on ${host}: other machines on the network can reach this server and read and write the content` +
240
- (wildcard ? "" : "; the site editor connects only through localhost"),
241
- );
242
- }
243
- const schemaFile = fs.existsSync(paths.schema)
244
- ? ".deco/schema.gen.json"
245
- : fs.existsSync(paths.legacySchema)
246
- ? ".deco/meta.gen.json"
247
- : "no schema yet: run deco schema for typed forms";
248
- const count = Object.keys(readSavedBlocks(paths.blocks).blocks).length;
249
- const description = await storage.describe();
250
- const base = await storage.base().catch(() => null);
251
- const label = (name: string) => name.padEnd(21);
252
- reporter.info(`${label("Deco server")}${endpoint}`);
253
- reporter.info(`${label("Root")}${description.root} (${schemaFile}, ${count} blocks)`);
254
- reporter.info(
255
- description.assets
256
- ? `${label("Assets")}${description.assets.dir} (PUT /assets/<name>)`
257
- : `${label("Assets")}read-only: uploads are off`,
258
- );
259
- reporter.info(`${label("Preview")}${preview}`);
260
- if (base) {
261
- const commit = base.revision === UNBORN_REVISION ? "no commits yet" : base.revision.slice(0, 7);
262
- reporter.info(
263
- `${label("Changes")}compared with ${base.resolvedRef ?? "detached HEAD"} (${commit})`,
264
- );
265
- }
266
- reporter.info(`${label("Site editor")}${siteEditorUrl}`);
267
-
268
- return {
269
- endpoint,
270
- siteEditorUrl,
271
- port,
272
- close: () => Promise.all(servers.map(close)).then(() => undefined),
273
- };
274
- }
275
-
276
- /**
277
- * One server per address, all on the port the first one gets. An address
278
- * after the first that the machine doesn't have (::1 without IPv6) is
279
- * skipped; with port 0, a port the next address can't take is tried again.
280
- */
281
- async function listen(
282
- handle: http.RequestListener,
283
- hosts: string[],
284
- requestedPort: number,
285
- ): Promise<http.Server[]> {
286
- for (let attempt = 0; ; attempt++) {
287
- const servers: http.Server[] = [];
288
- let port = requestedPort;
289
- try {
290
- for (const [i, host] of hosts.entries()) {
291
- const server = http.createServer(handle);
292
- try {
293
- await new Promise<void>((resolve, reject) => {
294
- server.once("error", reject);
295
- server.listen(port, host, () => resolve());
296
- });
297
- } catch (error) {
298
- const code = (error as NodeJS.ErrnoException).code;
299
- if (i > 0 && (code === "EADDRNOTAVAIL" || code === "EAFNOSUPPORT")) continue;
300
- throw error;
301
- }
302
- servers.push(server);
303
- port = (server.address() as AddressInfo).port;
304
- }
305
- return servers;
306
- } catch (error) {
307
- await Promise.all(servers.map(close));
308
- if ((error as NodeJS.ErrnoException).code !== "EADDRINUSE") throw error;
309
- if (requestedPort === 0 && attempt < 5) continue;
310
- throw new CliError(`port ${port} is in use; pass --port`);
311
- }
312
- }
313
- }
314
-
315
- function close(server: http.Server): Promise<void> {
316
- return new Promise((resolve) => {
317
- server.closeAllConnections?.();
318
- server.close(() => resolve());
319
- });
320
- }
321
-
322
- /** A Node request as a fetch `Request`, its body streamed. */
323
- function toRequest(req: http.IncomingMessage): Request {
324
- const headers = new Headers();
325
- for (const [key, value] of Object.entries(req.headers)) {
326
- if (Array.isArray(value)) for (const v of value) headers.append(key, v);
327
- else if (value !== undefined) headers.set(key, value);
328
- }
329
- const hasBody = req.method !== "GET" && req.method !== "HEAD";
330
- return new Request(new URL(req.url ?? "/", "http://localhost"), {
331
- method: req.method,
332
- headers,
333
- body: hasBody ? (Readable.toWeb(req) as ReadableStream<Uint8Array>) : undefined,
334
- duplex: "half",
335
- } as RequestInit);
336
- }
337
-
338
- /** `deco serve`: start, then run until interrupted. */
339
- export async function serve(options: ServeOptions = {}): Promise<number> {
340
- const running = await startServer(options);
341
- await new Promise<void>((resolve) => {
342
- const stop = () => resolve();
343
- process.once("SIGINT", stop);
344
- process.once("SIGTERM", stop);
345
- });
346
- await running.close();
347
- return 0;
348
- }