@decocms/tanstack 8.1.0-next.0 → 8.4.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 (177) hide show
  1. package/README.md +79 -0
  2. package/dist/draft.d.ts +33 -0
  3. package/dist/draft.d.ts.map +1 -0
  4. package/dist/draft.js +41 -0
  5. package/dist/draft.js.map +1 -0
  6. package/dist/index.d.ts +9 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +9 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/react/DecoDocument.d.ts +61 -0
  11. package/dist/react/DecoDocument.d.ts.map +1 -0
  12. package/dist/react/DecoDocument.js +96 -0
  13. package/dist/react/DecoDocument.js.map +1 -0
  14. package/dist/react/Image.d.ts +96 -0
  15. package/dist/react/Image.d.ts.map +1 -0
  16. package/dist/react/Image.js +79 -0
  17. package/dist/react/Image.js.map +1 -0
  18. package/dist/react/index.d.ts +7 -0
  19. package/dist/react/index.d.ts.map +1 -0
  20. package/dist/react/index.js +7 -0
  21. package/dist/react/index.js.map +1 -0
  22. package/dist/react/pageValues.d.ts +10 -0
  23. package/dist/react/pageValues.d.ts.map +1 -0
  24. package/dist/react/pageValues.js +29 -0
  25. package/dist/react/pageValues.js.map +1 -0
  26. package/dist/react/scripts.d.ts +14 -0
  27. package/dist/react/scripts.d.ts.map +1 -0
  28. package/dist/react/scripts.js +96 -0
  29. package/dist/react/scripts.js.map +1 -0
  30. package/dist/router/index.d.ts +38 -0
  31. package/dist/router/index.d.ts.map +1 -0
  32. package/dist/router/index.js +60 -0
  33. package/dist/router/index.js.map +1 -0
  34. package/dist/scope/browser.d.ts +11 -0
  35. package/dist/scope/browser.d.ts.map +1 -0
  36. package/dist/scope/browser.js +8 -0
  37. package/dist/scope/browser.js.map +1 -0
  38. package/dist/scope/server.d.ts +13 -0
  39. package/dist/scope/server.d.ts.map +1 -0
  40. package/dist/scope/server.js +26 -0
  41. package/dist/scope/server.js.map +1 -0
  42. package/dist/server/index.d.ts +27 -0
  43. package/dist/server/index.d.ts.map +1 -0
  44. package/dist/server/index.js +31 -0
  45. package/dist/server/index.js.map +1 -0
  46. package/dist/shared.d.ts +26 -0
  47. package/dist/shared.d.ts.map +1 -0
  48. package/dist/shared.js +26 -0
  49. package/dist/shared.js.map +1 -0
  50. package/dist/start/index.d.ts +9 -0
  51. package/dist/start/index.d.ts.map +1 -0
  52. package/dist/start/index.js +33 -0
  53. package/dist/start/index.js.map +1 -0
  54. package/dist/studio.d.ts +28 -0
  55. package/dist/studio.d.ts.map +1 -0
  56. package/dist/studio.js +53 -0
  57. package/dist/studio.js.map +1 -0
  58. package/dist/vite/index.d.ts +15 -0
  59. package/dist/vite/index.d.ts.map +1 -0
  60. package/dist/vite/index.js +95 -0
  61. package/dist/vite/index.js.map +1 -0
  62. package/dist/worker/cacheProfiles.d.ts +43 -0
  63. package/dist/worker/cacheProfiles.d.ts.map +1 -0
  64. package/dist/worker/cacheProfiles.js +162 -0
  65. package/dist/worker/cacheProfiles.js.map +1 -0
  66. package/dist/worker/cookies.d.ts +20 -0
  67. package/dist/worker/cookies.d.ts.map +1 -0
  68. package/dist/worker/cookies.js +69 -0
  69. package/dist/worker/cookies.js.map +1 -0
  70. package/dist/worker/drafts.d.ts +59 -0
  71. package/dist/worker/drafts.d.ts.map +1 -0
  72. package/dist/worker/drafts.js +140 -0
  73. package/dist/worker/drafts.js.map +1 -0
  74. package/dist/worker/index.d.ts +107 -0
  75. package/dist/worker/index.d.ts.map +1 -0
  76. package/dist/worker/index.js +511 -0
  77. package/dist/worker/index.js.map +1 -0
  78. package/dist/worker/security.d.ts +14 -0
  79. package/dist/worker/security.d.ts.map +1 -0
  80. package/dist/worker/security.js +48 -0
  81. package/dist/worker/security.js.map +1 -0
  82. package/dist/worker/segment.d.ts +21 -0
  83. package/dist/worker/segment.d.ts.map +1 -0
  84. package/dist/worker/segment.js +43 -0
  85. package/dist/worker/segment.js.map +1 -0
  86. package/package.json +85 -37
  87. package/src/draft.ts +43 -0
  88. package/src/index.ts +8 -61
  89. package/src/react/DecoDocument.tsx +234 -0
  90. package/src/react/Image.tsx +213 -0
  91. package/src/react/index.ts +24 -0
  92. package/src/react/pageValues.ts +35 -0
  93. package/src/react/scripts.ts +98 -0
  94. package/src/router/index.ts +80 -0
  95. package/src/scope/browser.ts +18 -0
  96. package/src/scope/server.ts +37 -0
  97. package/src/server/index.ts +43 -0
  98. package/src/shared.ts +29 -0
  99. package/src/start/index.ts +31 -0
  100. package/src/studio.ts +52 -0
  101. package/src/vite/index.ts +105 -0
  102. package/src/worker/cacheProfiles.ts +180 -0
  103. package/src/worker/cookies.ts +65 -0
  104. package/src/worker/drafts.ts +157 -0
  105. package/src/worker/index.ts +648 -0
  106. package/src/worker/security.ts +63 -0
  107. package/src/worker/segment.ts +49 -0
  108. package/src/__conformance__/observability.test.ts +0 -221
  109. package/src/cms/kvBlockSource.test.ts +0 -82
  110. package/src/cms/kvBlockSource.ts +0 -68
  111. package/src/daemon/auth.ts +0 -204
  112. package/src/daemon/fs.ts +0 -238
  113. package/src/daemon/index.ts +0 -8
  114. package/src/daemon/middleware.ts +0 -156
  115. package/src/daemon/tunnel.ts +0 -129
  116. package/src/daemon/volumes.ts +0 -366
  117. package/src/daemon/watch.ts +0 -272
  118. package/src/hooks/CdnSegmentMarker.tsx +0 -38
  119. package/src/hooks/DecoPageRenderer.tsx +0 -750
  120. package/src/hooks/DecoRootLayout.tsx +0 -192
  121. package/src/hooks/DraftPreviewIndicator.test.tsx +0 -60
  122. package/src/hooks/DraftPreviewIndicator.tsx +0 -64
  123. package/src/hooks/NavigationProgress.test.tsx +0 -58
  124. package/src/hooks/NavigationProgress.tsx +0 -63
  125. package/src/hooks/PreviewProviders.test.tsx +0 -42
  126. package/src/hooks/PreviewProviders.tsx +0 -45
  127. package/src/hooks/StableOutlet.tsx +0 -30
  128. package/src/hooks/deferredObserverTiming.test.tsx +0 -91
  129. package/src/hooks/index.ts +0 -10
  130. package/src/routes/adminRoutes.test.ts +0 -99
  131. package/src/routes/adminRoutes.ts +0 -153
  132. package/src/routes/cmsRoute.test.ts +0 -267
  133. package/src/routes/cmsRoute.ts +0 -1053
  134. package/src/routes/components.tsx +0 -57
  135. package/src/routes/index.ts +0 -24
  136. package/src/routes/pageUrl.test.ts +0 -70
  137. package/src/routes/pageUrl.ts +0 -55
  138. package/src/routes/withSiteGlobals.test.ts +0 -243
  139. package/src/routes/withSiteGlobals.ts +0 -243
  140. package/src/sdk/backgroundTasks.test.ts +0 -68
  141. package/src/sdk/backgroundTasks.ts +0 -38
  142. package/src/sdk/cdnSegment.test.ts +0 -67
  143. package/src/sdk/cdnSegment.ts +0 -71
  144. package/src/sdk/cookiePassthrough.ts +0 -58
  145. package/src/sdk/createInvoke.ts +0 -77
  146. package/src/sdk/deferredSectionLoader.test.ts +0 -94
  147. package/src/sdk/deferredSectionLoader.ts +0 -46
  148. package/src/sdk/draft.test.ts +0 -341
  149. package/src/sdk/draft.ts +0 -277
  150. package/src/sdk/draftShared.ts +0 -16
  151. package/src/sdk/kvHydration.test.ts +0 -371
  152. package/src/sdk/kvHydration.ts +0 -263
  153. package/src/sdk/kvRedirects.test.ts +0 -132
  154. package/src/sdk/kvRedirects.ts +0 -125
  155. package/src/sdk/outboundHeaders.test.ts +0 -113
  156. package/src/sdk/outboundHeaders.ts +0 -81
  157. package/src/sdk/router.ts +0 -101
  158. package/src/sdk/serverFnFetch.ts +0 -59
  159. package/src/sdk/speculationRules.test.ts +0 -82
  160. package/src/sdk/speculationRules.ts +0 -136
  161. package/src/sdk/startEntry.ts +0 -31
  162. package/src/sdk/useHydrated.ts +0 -19
  163. package/src/sdk/workerEntry.cacheStorage.test.ts +0 -147
  164. package/src/sdk/workerEntry.test.ts +0 -1033
  165. package/src/sdk/workerEntry.trackingCache.test.ts +0 -328
  166. package/src/sdk/workerEntry.ts +0 -3154
  167. package/src/setupFastDeploy.ts +0 -13
  168. package/src/v8/__conformance__/delivery.test.ts +0 -100
  169. package/src/v8/binding.ts +0 -70
  170. package/src/v8/kvLoader.bundle.test.ts +0 -42
  171. package/src/v8/kvLoader.test.ts +0 -74
  172. package/src/v8/kvLoader.ts +0 -43
  173. package/src/vite/plugin-scaffold-gen.test.js +0 -106
  174. package/src/vite/plugin.js +0 -1022
  175. package/src/vite/plugin.test.js +0 -238
  176. package/src/vite/plugin.test.ts +0 -176
  177. package/tsconfig.json +0 -7
@@ -1,366 +0,0 @@
1
- /**
2
- * Volumes API — CRUD for .deco/ files with JSON patch support
3
- * and WebSocket realtime broadcast of file changes.
4
- *
5
- * Ported from: deco-cx/deco daemon/realtime/app.ts (without CRDT)
6
- */
7
- import { readdir, readFile, writeFile, mkdir, rm, stat } from "node:fs/promises";
8
- import { join, resolve, sep, posix } from "node:path";
9
- import type { IncomingMessage, ServerResponse, Server as HttpServer } from "node:http";
10
- import { WebSocketServer, WebSocket } from "ws";
11
- import fjp from "fast-json-patch";
12
- import type { Operation } from "fast-json-patch";
13
-
14
- // ---------------------------------------------------------------------------
15
- // Types — ported from daemon/realtime/types.ts
16
- // ---------------------------------------------------------------------------
17
-
18
- interface BaseFilePatch {
19
- path: string;
20
- }
21
-
22
- interface JSONFilePatch extends BaseFilePatch {
23
- patches: Operation[];
24
- }
25
-
26
- interface TextFileSet extends BaseFilePatch {
27
- content: string | null;
28
- }
29
-
30
- type FilePatch = JSONFilePatch | TextFileSet;
31
-
32
- interface VolumePatchRequest {
33
- messageId?: string;
34
- patches: FilePatch[];
35
- }
36
-
37
- interface FilePatchResult {
38
- path: string;
39
- accepted: boolean;
40
- content?: string;
41
- deleted?: boolean;
42
- }
43
-
44
- interface VolumePatchResponse {
45
- results: FilePatchResult[];
46
- timestamp: number;
47
- }
48
-
49
- function isJSONFilePatch(patch: FilePatch): patch is JSONFilePatch {
50
- return "patches" in patch && Array.isArray((patch as JSONFilePatch).patches);
51
- }
52
-
53
- function isTextFileSet(patch: FilePatch): patch is TextFileSet {
54
- return "content" in patch && !("patches" in patch);
55
- }
56
-
57
- // ---------------------------------------------------------------------------
58
- // Helpers
59
- // ---------------------------------------------------------------------------
60
-
61
- const toPosix = (p: string) => p.replaceAll(sep, "/");
62
-
63
- function safePath(base: string, untrusted: string): string | null {
64
- const resolved = resolve(base, untrusted);
65
- if (!resolved.startsWith(base + sep) && resolved !== base) return null;
66
- return resolved;
67
- }
68
-
69
- async function readTextFileSafe(path: string): Promise<string | null> {
70
- try {
71
- return await readFile(path, "utf-8");
72
- } catch (err: unknown) {
73
- if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
74
- throw err;
75
- }
76
- }
77
-
78
- async function ensureFile(path: string): Promise<void> {
79
- const dir = join(path, "..");
80
- await mkdir(dir, { recursive: true });
81
- }
82
-
83
- // ---------------------------------------------------------------------------
84
- // WebSocket realtime sessions
85
- // ---------------------------------------------------------------------------
86
-
87
- interface BroadcastMessage {
88
- path: string;
89
- timestamp: number;
90
- deleted?: boolean;
91
- messageId?: string;
92
- }
93
-
94
- interface VolumesState {
95
- sessions: WebSocket[];
96
- wss: WebSocketServer;
97
- timestamp: number;
98
- }
99
-
100
- function broadcast(state: VolumesState, msg: BroadcastMessage): void {
101
- const data = JSON.stringify(msg);
102
- for (const ws of state.sessions) {
103
- if (ws.readyState === WebSocket.OPEN) {
104
- ws.send(data);
105
- }
106
- }
107
- }
108
-
109
- // ---------------------------------------------------------------------------
110
- // Walk directory (Node.js equivalent of @std/fs/walk)
111
- // ---------------------------------------------------------------------------
112
-
113
- async function walkFiles(
114
- root: string,
115
- ): Promise<string[]> {
116
- const results: string[] = [];
117
- try {
118
- const entries = await readdir(root, {
119
- recursive: true,
120
- withFileTypes: true,
121
- });
122
- for (const entry of entries) {
123
- if (!entry.isFile()) continue;
124
- const fullPath = join(entry.parentPath, entry.name);
125
- const rel = toPosix(fullPath.replace(root, ""));
126
- if (
127
- rel.includes("/.git/") ||
128
- rel.includes("/node_modules/") ||
129
- rel.includes("/.agent-home/") ||
130
- rel.includes("/.claude/")
131
- ) {
132
- continue;
133
- }
134
- results.push(fullPath);
135
- }
136
- } catch {
137
- // root might be a file, not a directory
138
- }
139
- return results;
140
- }
141
-
142
- // ---------------------------------------------------------------------------
143
- // Request handlers
144
- // ---------------------------------------------------------------------------
145
-
146
- const cwd = process.cwd();
147
-
148
- async function handleGetFiles(
149
- req: IncomingMessage,
150
- res: ServerResponse,
151
- state: VolumesState,
152
- ): Promise<void> {
153
- const url = new URL(req.url ?? "/", "http://localhost");
154
- const [, ...segments] = url.pathname.split("/files");
155
- const filePath = segments.join("/files") || "/";
156
- const withContent = url.searchParams.get("content") === "true";
157
-
158
- const root = safePath(cwd, filePath);
159
- if (!root) {
160
- res.writeHead(403);
161
- res.end("Path traversal denied");
162
- return;
163
- }
164
- const fs: Record<string, { content: string | null }> = {};
165
-
166
- const files = await walkFiles(root);
167
- if (files.length > 0) {
168
- for (const fullPath of files) {
169
- const key = toPosix(fullPath.replace(root, "/"));
170
- fs[key] = {
171
- content: withContent ? await readTextFileSafe(fullPath) : null,
172
- };
173
- }
174
- } else {
175
- // Might be a single file
176
- const content = withContent ? await readTextFileSafe(root) : null;
177
- fs[toPosix(filePath)] = { content };
178
- }
179
-
180
- const body = JSON.stringify({ timestamp: state.timestamp, fs });
181
- res.writeHead(200, { "Content-Type": "application/json" });
182
- res.end(body);
183
- }
184
-
185
- async function handlePatchFiles(
186
- req: IncomingMessage,
187
- res: ServerResponse,
188
- state: VolumesState,
189
- ): Promise<void> {
190
- const raw = await readBody(req);
191
- let request: VolumePatchRequest;
192
- try {
193
- request = JSON.parse(raw);
194
- } catch {
195
- res.writeHead(400);
196
- res.end("Invalid JSON");
197
- return;
198
- }
199
-
200
- const results: FilePatchResult[] = [];
201
-
202
- for (const patch of request.patches) {
203
- // Validate path traversal for every patch
204
- const resolvedPath = safePath(cwd, patch.path);
205
- if (!resolvedPath) {
206
- results.push({ accepted: false, path: patch.path });
207
- continue;
208
- }
209
-
210
- if (isJSONFilePatch(patch)) {
211
- const { path: filePath, patches: operations } = patch;
212
- const content =
213
- (await readTextFileSafe(resolvedPath)) ?? "{}";
214
- try {
215
- const newContent = JSON.stringify(
216
- operations.reduce(fjp.applyReducer, JSON.parse(content)),
217
- );
218
- results.push({
219
- accepted: true,
220
- path: filePath,
221
- content: newContent,
222
- deleted: newContent === "null",
223
- });
224
- } catch (error) {
225
- console.error(error);
226
- results.push({ accepted: false, path: filePath, content });
227
- }
228
- } else if (isTextFileSet(patch)) {
229
- const { path: filePath, content } = patch;
230
- results.push({
231
- accepted: true,
232
- path: filePath,
233
- content: content ?? "",
234
- deleted: content === null,
235
- });
236
- }
237
- }
238
-
239
- state.timestamp = Date.now();
240
-
241
- // Atomic: only commit writes if all patches accepted
242
- const shouldWrite = results.every((r) => r.accepted);
243
- if (shouldWrite) {
244
- await Promise.all(
245
- results.map(async (r) => {
246
- try {
247
- const system = join(cwd, r.path);
248
- if (r.deleted) {
249
- await rm(system, { force: true });
250
- } else if (r.content != null) {
251
- await ensureFile(system);
252
- await writeFile(system, r.content, "utf-8");
253
- }
254
- } catch (error) {
255
- console.error(error);
256
- r.accepted = false;
257
- }
258
- }),
259
- );
260
- }
261
-
262
- const body: VolumePatchResponse = { timestamp: state.timestamp, results };
263
- res.writeHead(200, { "Content-Type": "application/json" });
264
- res.end(JSON.stringify(body));
265
- }
266
-
267
- // ---------------------------------------------------------------------------
268
- // Body reader helper
269
- // ---------------------------------------------------------------------------
270
-
271
- function readBody(req: IncomingMessage): Promise<string> {
272
- return new Promise((resolve, reject) => {
273
- const chunks: Buffer[] = [];
274
- req.on("data", (chunk: Buffer) => chunks.push(chunk));
275
- req.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
276
- req.on("error", reject);
277
- });
278
- }
279
-
280
- // ---------------------------------------------------------------------------
281
- // Setup: attach WebSocket server and file watcher
282
- // ---------------------------------------------------------------------------
283
-
284
- export interface VolumesOptions {
285
- /** Vite's HTTP server to attach WebSocket upgrades to. */
286
- httpServer: HttpServer;
287
- /** Vite's file watcher (chokidar instance) for broadcasting changes. */
288
- watcher: { on(event: string, cb: (...args: unknown[]) => void): void };
289
- }
290
-
291
- export function createVolumesHandler(opts: VolumesOptions) {
292
- const state: VolumesState = {
293
- sessions: [],
294
- wss: new WebSocketServer({ noServer: true }),
295
- timestamp: Date.now(),
296
- };
297
-
298
- // Handle WebSocket upgrades for /volumes/*/files paths with x-daemon-api
299
- opts.httpServer.on("upgrade", (req, socket, head) => {
300
- const isDaemon =
301
- req.headers["x-daemon-api"] ?? req.headers["x-hypervisor-api"];
302
- if (!isDaemon) return;
303
-
304
- const url = req.url ?? "";
305
- if (!url.includes("/volumes/") || !url.includes("/files")) return;
306
-
307
- state.wss.handleUpgrade(req, socket, head, (ws) => {
308
- state.sessions.push(ws);
309
- console.log("[deco] admin websocket connected");
310
-
311
- ws.on("close", () => {
312
- console.log("[deco] admin websocket disconnected");
313
- const idx = state.sessions.indexOf(ws);
314
- if (idx > -1) state.sessions.splice(idx, 1);
315
- });
316
- });
317
- });
318
-
319
- // Broadcast file changes from Vite's watcher
320
- const broadcastChange = (filePath: string, deleted = false) => {
321
- const rel = toPosix(filePath).replace(toPosix(cwd), "");
322
- if (
323
- rel.includes("/.git/") ||
324
- rel.includes("/node_modules/") ||
325
- rel.includes("/.agent-home/") ||
326
- rel.includes("/.claude/")
327
- ) {
328
- return;
329
- }
330
- broadcast(state, { path: rel, timestamp: Date.now(), deleted });
331
- };
332
-
333
- opts.watcher.on("change", (path: unknown) => {
334
- if (typeof path === "string") broadcastChange(path);
335
- });
336
- opts.watcher.on("add", (path: unknown) => {
337
- if (typeof path === "string") broadcastChange(path);
338
- });
339
- opts.watcher.on("unlink", (path: unknown) => {
340
- if (typeof path === "string") broadcastChange(path, true);
341
- });
342
-
343
- // Connect-style middleware for HTTP requests
344
- return async (
345
- req: IncomingMessage,
346
- res: ServerResponse,
347
- next: () => void,
348
- ): Promise<void> => {
349
- const url = req.url ?? "";
350
-
351
- // Match /volumes/:id/files patterns
352
- if (!url.includes("/volumes/") || !url.includes("/files")) {
353
- next();
354
- return;
355
- }
356
-
357
- if (req.method === "GET") {
358
- await handleGetFiles(req, res, state);
359
- } else if (req.method === "PATCH") {
360
- await handlePatchFiles(req, res, state);
361
- } else {
362
- res.writeHead(405);
363
- res.end();
364
- }
365
- };
366
- }
@@ -1,272 +0,0 @@
1
- /**
2
- * SSE endpoint for file change events — initial sync + live updates.
3
- *
4
- * Ported from: deco-cx/deco daemon/sse/api.ts + daemon/sse/channel.ts
5
- */
6
- import { readdir, readFile, stat } from "node:fs/promises";
7
- import { join, sep } from "node:path";
8
- import type { IncomingMessage, ServerResponse } from "node:http";
9
-
10
- // ---------------------------------------------------------------------------
11
- // Event types — simplified from daemon/fs/common.ts
12
- // ---------------------------------------------------------------------------
13
-
14
- interface FSEvent {
15
- type: "fs-sync" | "fs-snapshot" | "worker-status" | "meta-info";
16
- detail: Record<string, unknown>;
17
- }
18
-
19
- // ---------------------------------------------------------------------------
20
- // Broadcast channel (EventTarget-based, same as daemon/sse/channel.ts)
21
- // ---------------------------------------------------------------------------
22
-
23
- const channel = new EventTarget();
24
-
25
- export function broadcastFSEvent(event: FSEvent): void {
26
- channel.dispatchEvent(new CustomEvent("broadcast", { detail: event }));
27
- }
28
-
29
- // ---------------------------------------------------------------------------
30
- // Helpers
31
- // ---------------------------------------------------------------------------
32
-
33
- const toPosix = (p: string) => p.replaceAll(sep, "/");
34
-
35
- function shouldIgnore(path: string): boolean {
36
- return (
37
- path.includes(`${sep}.git${sep}`) ||
38
- path.includes(`${sep}node_modules${sep}`) ||
39
- path.includes(`${sep}.agent-home${sep}`) ||
40
- path.includes(`${sep}.claude${sep}`)
41
- );
42
- }
43
-
44
- /**
45
- * Infer block type from __resolveType string.
46
- * Maps to manifest block categories (pages, sections, loaders, etc.).
47
- */
48
- function inferBlockType(resolveType: string): string | null {
49
- if (!resolveType) return null;
50
- if (resolveType.includes("/pages/")) return "pages";
51
- if (resolveType.includes("/sections/")) return "sections";
52
- if (resolveType.includes("/loaders/")) return "loaders";
53
- if (resolveType.includes("/actions/")) return "actions";
54
- if (resolveType.includes("/matchers/")) return "matchers";
55
- if (resolveType.includes("/flags/")) return "sections";
56
- return null;
57
- }
58
-
59
- export interface Metadata {
60
- kind: "block" | "file";
61
- blockType?: string;
62
- __resolveType?: string;
63
- name?: string;
64
- path?: string;
65
- }
66
-
67
- /**
68
- * Read a JSON file and infer its metadata (block type, resolveType, etc.).
69
- * Matches the Deno daemon's inferMetadata from daemon/fs/api.ts.
70
- */
71
- export async function inferMetadata(filepath: string): Promise<Metadata | null> {
72
- try {
73
- const raw = await readFile(filepath, "utf-8");
74
- const parsed = JSON.parse(raw);
75
- const { __resolveType, name, path: pagePath } = parsed;
76
-
77
- if (!__resolveType) return { kind: "file" };
78
-
79
- const blockType = inferBlockType(__resolveType);
80
- if (!blockType) return { kind: "file" };
81
-
82
- if (blockType === "pages") {
83
- return {
84
- kind: "block",
85
- blockType,
86
- __resolveType,
87
- name: name ?? undefined,
88
- path: pagePath ?? undefined,
89
- };
90
- }
91
-
92
- return { kind: "block", blockType, __resolveType };
93
- } catch {
94
- return { kind: "file" };
95
- }
96
- }
97
-
98
- // ---------------------------------------------------------------------------
99
- // Initial file scan — yields fs-sync events for each .deco/ file
100
- // ---------------------------------------------------------------------------
101
-
102
- async function* scanFiles(
103
- cwd: string,
104
- since: number,
105
- ): AsyncGenerator<FSEvent> {
106
- const decoDir = join(cwd, ".deco");
107
- try {
108
- const entries = await readdir(decoDir, {
109
- recursive: true,
110
- withFileTypes: true,
111
- });
112
- for (const entry of entries) {
113
- if (!entry.isFile()) continue;
114
- const fullPath = join(entry.parentPath, entry.name);
115
- if (shouldIgnore(fullPath)) continue;
116
-
117
- let mtime: number;
118
- try {
119
- const stats = await stat(fullPath);
120
- mtime = stats.mtimeMs;
121
- } catch {
122
- mtime = Date.now();
123
- }
124
-
125
- if (mtime < since) continue;
126
-
127
- const metadata = await inferMetadata(fullPath);
128
- const filepath = toPosix(fullPath.replace(cwd, ""));
129
- yield {
130
- type: "fs-sync",
131
- detail: { metadata, filepath, timestamp: mtime },
132
- };
133
- }
134
- } catch {
135
- // .deco dir might not exist yet
136
- }
137
-
138
- yield {
139
- type: "fs-snapshot",
140
- detail: { timestamp: Date.now() },
141
- };
142
- }
143
-
144
- // ---------------------------------------------------------------------------
145
- // SSE handler — Connect-style middleware
146
- // ---------------------------------------------------------------------------
147
-
148
- export function createWatchHandler(opts?: { getPort?: () => number }) {
149
- const cwd = process.cwd();
150
- const getPort = opts?.getPort ?? (() => 5173);
151
-
152
- return async (
153
- req: IncomingMessage,
154
- res: ServerResponse,
155
- next: () => void,
156
- ): Promise<void> => {
157
- const url = new URL(req.url ?? "/", "http://localhost");
158
-
159
- // Only handle /watch or the root SSE endpoint
160
- if (url.pathname !== "/watch" && url.pathname !== "/") {
161
- next();
162
- return;
163
- }
164
-
165
- if (req.method !== "GET") {
166
- next();
167
- return;
168
- }
169
-
170
- // SSE headers
171
- res.writeHead(200, {
172
- "Content-Type": "text/event-stream",
173
- "Cache-Control": "no-cache",
174
- Connection: "keep-alive",
175
- });
176
-
177
- const since = Number(url.searchParams.get("since")) || 0;
178
- let closed = false;
179
-
180
- req.on("close", () => {
181
- closed = true;
182
- console.log("[deco] SSE stream closed");
183
- });
184
-
185
- function sendEvent(event: FSEvent): void {
186
- if (closed) return;
187
- const data = encodeURIComponent(JSON.stringify(event));
188
- res.write(`event: message\ndata: ${data}\n\n`);
189
- }
190
-
191
- // Live broadcast listener
192
- const handler = (e: Event) => {
193
- const ce = e as CustomEvent<FSEvent>;
194
- sendEvent(ce.detail);
195
- };
196
- channel.addEventListener("broadcast", handler);
197
- req.on("close", () => {
198
- channel.removeEventListener("broadcast", handler);
199
- });
200
-
201
- console.log("[deco] SSE stream opened");
202
-
203
- // Initial scan
204
- for await (const event of scanFiles(cwd, since)) {
205
- if (closed) break;
206
- sendEvent(event);
207
- }
208
-
209
- if (closed) return;
210
-
211
- // Worker status — Vite dev server is always ready
212
- sendEvent({
213
- type: "worker-status",
214
- detail: { state: "ready" },
215
- });
216
-
217
- // Meta info — schema + manifest so admin knows about sections/loaders/actions.
218
- // Fetch via HTTP so the request goes through Vite SSR where the data lives
219
- // (daemon's native imports create separate module instances).
220
- try {
221
- const metaResponse = await fetch(`http://localhost:${getPort()}/live/_meta`);
222
- if (metaResponse.ok) {
223
- const metaData = await metaResponse.json();
224
- sendEvent({
225
- type: "meta-info",
226
- detail: { ...metaData, timestamp: Date.now() },
227
- });
228
- }
229
- } catch {
230
- // Schema may not be initialized yet — admin will retry via /live/_meta
231
- }
232
- };
233
- }
234
-
235
- // ---------------------------------------------------------------------------
236
- // Wire Vite watcher to broadcast channel
237
- // ---------------------------------------------------------------------------
238
-
239
- export function watchFS(watcher: {
240
- on(event: string, cb: (...args: unknown[]) => void): void;
241
- }): void {
242
- const cwd = process.cwd();
243
-
244
- const onChange = async (filePath: unknown, deleted = false) => {
245
- if (typeof filePath !== "string") return;
246
- if (shouldIgnore(filePath)) return;
247
-
248
- const metadata = deleted ? null : await inferMetadata(filePath);
249
- let mtime = Date.now();
250
- if (!deleted) {
251
- try {
252
- const stats = await stat(filePath);
253
- mtime = stats.mtimeMs;
254
- } catch {
255
- // use Date.now()
256
- }
257
- }
258
-
259
- broadcastFSEvent({
260
- type: "fs-sync",
261
- detail: {
262
- metadata,
263
- filepath: toPosix(filePath.replace(cwd, "")),
264
- timestamp: mtime,
265
- },
266
- });
267
- };
268
-
269
- watcher.on("change", (path: unknown) => onChange(path));
270
- watcher.on("add", (path: unknown) => onChange(path));
271
- watcher.on("unlink", (path: unknown) => onChange(path, true));
272
- }
@@ -1,38 +0,0 @@
1
- /**
2
- * Publishes the CDN segment token this server computed, so `decoServerFnFetch`
3
- * can echo it back on `/_serverFn` URLs.
4
- *
5
- * Only the server can produce this value: the segment includes dimensions the
6
- * browser cannot observe — region is resolved from `request.cf.regionCode`.
7
- * A client that derives its own token therefore never matches on a
8
- * regionalized store, which is exactly why this component exists.
9
- *
10
- * - **Server:** read the token from the RequestContext bag (filled by
11
- * `createDecoWorkerEntry`) and emit a tiny inline `<script>`.
12
- * - **Client:** the bag is a no-op stub, so the read yields undefined and this
13
- * renders nothing — the global set during SSR is already on `window`.
14
- *
15
- * Safe in a cached response: the Worker's edge cache keys on the segment, so a
16
- * stored entry carries the token of its own segment. And a stale token is
17
- * harmless by construction — the Worker verifies by recomputing and falls back
18
- * to `no-store` when it doesn't match.
19
- */
20
-
21
- import { getRequestNonce } from "@decocms/blocks/sdk/nonce";
22
- import { RequestContext } from "@decocms/blocks/sdk/requestContext";
23
- import { CSEG_BAG_KEY, CSEG_GLOBAL } from "../sdk/cdnSegment";
24
-
25
- export function CdnSegmentMarker() {
26
- const token = RequestContext.getBag<string>(CSEG_BAG_KEY);
27
- if (!token) return null;
28
- return (
29
- <script
30
- nonce={getRequestNonce()}
31
- // A hash this server computed, not user input. JSON.stringify keeps it
32
- // inert regardless.
33
- dangerouslySetInnerHTML={{
34
- __html: `window.${CSEG_GLOBAL}=${JSON.stringify(token)}`,
35
- }}
36
- />
37
- );
38
- }