@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,13 +0,0 @@
1
- import { setFastDeployKVGetter } from "@decocms/blocks-admin";
2
- import { getFastDeployKV } from "./sdk/kvHydration";
3
-
4
- /**
5
- * Reconnects packages/blocks-admin's decofile write-through to this
6
- * package's Cloudflare KV reader. Call once at site startup (from the
7
- * site's own setup.ts, alongside createSiteSetup()) — without this call,
8
- * handleDecofileReload's KV write-through silently no-ops (same as it
9
- * does today for sites that never configure fast-deploy).
10
- */
11
- export function setupTanstackFastDeploy(): void {
12
- setFastDeployKVGetter(getFastDeployKV);
13
- }
@@ -1,100 +0,0 @@
1
- // @vitest-environment node
2
- /**
3
- * Docs conformance, Workers binding: hosted.mdx ("Release checks on Workers
4
- * run after the response, inside ctx.waitUntil, on their own"),
5
- * hosted-releases-internals.mdx (idle scheduling on Workers) and
6
- * hosted-publishing.mdx ("Large content on Workers": kvLoader as `content`).
7
- */
8
- import fs from "node:fs";
9
- import path from "node:path";
10
- import { fileURLToPath } from "node:url";
11
- import { createCMS, resetForTests } from "@decocms/blocks";
12
- import { computeContentRevision } from "@decocms/blocks/protocol";
13
- import { afterEach, describe, expect, it, vi } from "vitest";
14
- import { kvLoader } from "../kvLoader";
15
-
16
- const HERE = path.dirname(fileURLToPath(import.meta.url));
17
- const WORKSPACE = path.resolve(HERE, "../../../../..");
18
- const ORIGIN = "https://delivery.decocms.com";
19
-
20
- afterEach(() => {
21
- vi.unstubAllGlobals();
22
- vi.restoreAllMocks();
23
- resetForTests();
24
- });
25
-
26
- const seo = (props: { title: string; description: string }) => props;
27
-
28
- describe("hosted-publishing: large content on Workers", () => {
29
- it("HP-14: kvLoader as content; a missing key fails reads until the first release check", async () => {
30
- const blocks = { SummerSEO: { __resolveType: "seo", title: "Released", description: "d" } };
31
- const revision = await computeContentRevision(blocks);
32
- const asset = `/sites/acme/revisions/${revision}.json`;
33
- vi.stubGlobal(
34
- "fetch",
35
- vi.fn(async (input: string | URL | Request) => {
36
- const url = String(input);
37
- if (url === `${ORIGIN}/sites/acme/channels/production.json`) {
38
- return Response.json({ format: 1, generation: 1, revision, snapshot: asset });
39
- }
40
- if (url === `${ORIGIN}${asset}`) return Response.json({ revision, blocks });
41
- return new Response("not found", { status: 404 });
42
- }),
43
- );
44
- const namespace = { get: vi.fn(async () => null) }; // the deploy didn't write the key
45
- const cms = createCMS({
46
- blocks: { seo },
47
- content: kvLoader(namespace, { key: "decofile:abc" }),
48
- site: "acme",
49
- token: "t",
50
- });
51
- const [, error] = await cms.forRelease().resolve("SummerSEO");
52
- expect(error?.code).toBe("LOADER_FAILED");
53
- expect(await cms.update()).toEqual({ updated: true });
54
- const [value, after] = await cms.forRelease().resolve<{ title: string }>("SummerSEO");
55
- expect(after).toBeNull();
56
- expect(value?.title).toBe("Released");
57
- });
58
- });
59
-
60
- describe("hosted: release checks on Workers", () => {
61
- it("H-10/HRI-4: the documented Workers setup runs due checks inside ctx.waitUntil, with no user code", () => {
62
- // The documented TanStack Start setup (tanstack-start-descriptors.mdx,
63
- // examples/tanstack-smoke) runs Start's own server entry:
64
- const wrangler = fs.readFileSync(
65
- path.join(WORKSPACE, "examples/tanstack-smoke/wrangler.jsonc"),
66
- "utf8",
67
- );
68
- expect(wrangler).toContain('"main": "@tanstack/react-start/server-entry"');
69
- // So something in the next-major surface (core or binding) must route the
70
- // core's background work into ctx.waitUntil on its own: install the
71
- // `Symbol.for("decocms.blocks.background")` hook, or use Workers'
72
- // `waitUntil` from "cloudflare:workers". Today only the v7
73
- // `createDecoWorkerEntry` (sdk/workerEntry.ts) installs that hook, and the
74
- // documented setup never runs it, so checks fall back to a timer.
75
- const roots = [
76
- path.join(WORKSPACE, "packages/blocks/src/v8"),
77
- path.join(WORKSPACE, "packages/tanstack/src/v8"),
78
- ];
79
- const installers: string[] = [];
80
- const walk = (dir: string) => {
81
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
82
- const full = path.join(dir, entry.name);
83
- if (entry.isDirectory()) {
84
- if (entry.name !== "__conformance__") walk(full);
85
- } else if (/\.tsx?$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name)) {
86
- const text = fs.readFileSync(full, "utf8");
87
- if (
88
- /installBackgroundHook|from "cloudflare:workers"|\[(BACKGROUND_HOOK|HOOK)\]\s*=(?!=)/.test(
89
- text,
90
- )
91
- ) {
92
- installers.push(path.relative(WORKSPACE, full));
93
- }
94
- }
95
- }
96
- };
97
- for (const dir of roots) walk(dir);
98
- expect(installers).not.toEqual([]);
99
- });
100
- });
package/src/v8/binding.ts DELETED
@@ -1,70 +0,0 @@
1
- /**
2
- * What `@decocms/tanstack` adds to a next-major site on Cloudflare Workers
3
- * (see /next/caching#upstream-data): GETs made through
4
- * `createInstrumentedFetch` are served from the Cloudflare Cache API,
5
- * honouring the upstream's `cache-control`, and bypass it while a draft is
6
- * rendered. Hits carry the instrumented fetch's `cached=true` label.
7
- *
8
- * It reaches the core through a `Symbol.for` hook on `globalThis`
9
- * (`decocms.blocks.upstreamCache`; the core imports nothing from a binding).
10
- * Nothing here is exported from the package; the worker entry calls it.
11
- */
12
- import { draftPointer } from "@decocms/blocks";
13
- // The worker entry runs every request inside RequestContext, whose storage
14
- // resolves to a no-op stub in browser bundles (this module is reachable from
15
- // the package root, which client code imports).
16
- import { RequestContext } from "@decocms/blocks/sdk/requestContext";
17
-
18
- const UPSTREAM_CACHE = Symbol.for("decocms.blocks.upstreamCache");
19
-
20
- /** Whether the request being served renders a draft (then upstream caching is off). */
21
- function renderingDraft(): boolean {
22
- try {
23
- return draftPointer(RequestContext.request) !== null;
24
- } catch {
25
- return false; // outside a request
26
- }
27
- }
28
-
29
- /** Whether a response may be kept in a shared cache, per its `cache-control`. */
30
- function cacheable(response: Response): boolean {
31
- if (response.status !== 200) return false;
32
- const control = response.headers.get("cache-control")?.toLowerCase() ?? "";
33
- if (/\b(no-store|no-cache|private)\b/.test(control)) return false;
34
- return /\b(s-maxage|max-age)=[1-9]/.test(control);
35
- }
36
-
37
- /**
38
- * Installs the upstream cache (idempotent). Requests that carry a user's
39
- * credentials (`authorization`, `cookie`) are never cached, and nothing is
40
- * read or written while a draft is rendered.
41
- */
42
- export function installUpstreamCache(): void {
43
- const g = globalThis as Record<symbol, unknown>;
44
- if (typeof g[UPSTREAM_CACHE] === "function") return;
45
- g[UPSTREAM_CACHE] = async (
46
- input: string | URL | Request,
47
- init: RequestInit,
48
- fetch: typeof globalThis.fetch,
49
- ): Promise<{ response: Response; cached: boolean }> => {
50
- const cache = (globalThis as { caches?: { default?: Cache } }).caches?.default;
51
- const request = new Request(input, init);
52
- if (
53
- cache === undefined ||
54
- renderingDraft() ||
55
- request.headers.has("authorization") ||
56
- request.headers.has("cookie")
57
- ) {
58
- return { response: await fetch(input, init), cached: false };
59
- }
60
- const hit = await cache.match(request.url).catch(() => undefined);
61
- if (hit) return { response: hit, cached: true };
62
- const response = await fetch(input, init);
63
- if (cacheable(response)) {
64
- // Awaited: the Cache API is local to the data center, and the next
65
- // request for the same URL should already find it.
66
- await cache.put(request.url, response.clone()).catch(() => {});
67
- }
68
- return { response, cached: false };
69
- };
70
- }
@@ -1,42 +0,0 @@
1
- import { execFileSync } from "node:child_process";
2
- import { dirname, join } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- import { describe, expect, it } from "vitest";
5
-
6
- const here = dirname(fileURLToPath(import.meta.url));
7
- // The esbuild CLI, not its JS API: the API breaks across Vitest's realm
8
- // boundary (see packages/blocks/src/cms/client.browserBundle.test.ts).
9
- const esbuildBin = join(here, "../../../../node_modules/.bin/esbuild");
10
-
11
- /**
12
- * The docs import `kvLoader` from the package root, which still re-exports
13
- * the v7 binding. `"sideEffects"` in package.json lets a bundler drop every
14
- * root module the site doesn't use; without it the Worker ships the v7
15
- * runtime (react-dom/server, Start server-core, OpenTelemetry...).
16
- */
17
- describe("kvLoader bundle", () => {
18
- it("imports from the package root without pulling in the v7 binding", () => {
19
- const output = execFileSync(
20
- esbuildBin,
21
- [
22
- "--bundle",
23
- "--format=esm",
24
- "--platform=neutral",
25
- "--minify",
26
- "--main-fields=module,main",
27
- "--external:react",
28
- "--external:react-dom",
29
- "--external:@tanstack/*",
30
- "--external:node:*",
31
- "--log-level=error",
32
- ],
33
- {
34
- cwd: join(here, "../.."),
35
- input: 'export { kvLoader } from "@decocms/tanstack";',
36
- encoding: "utf-8",
37
- },
38
- );
39
- expect(output).toContain("kvLoader");
40
- expect(output.length).toBeLessThan(2048);
41
- });
42
- });
@@ -1,74 +0,0 @@
1
- import { createCMS, resetForTests, type Snapshot } from "@decocms/blocks";
2
- import { afterEach, describe, expect, it, vi } from "vitest";
3
- import { kvLoader } from "./kvLoader";
4
-
5
- const snapshot: Snapshot = {
6
- revision: "r1",
7
- blocks: { Hello: { __resolveType: "greeting", name: "world" } },
8
- };
9
-
10
- function kv(values: Record<string, unknown>) {
11
- return { get: vi.fn(async (key: string, _type: "json") => values[key] ?? null) };
12
- }
13
-
14
- afterEach(() => resetForTests());
15
-
16
- describe("kvLoader", () => {
17
- it("reads the snapshot under its key once per isolate", async () => {
18
- const namespace = kv({ "decofile:abc": snapshot });
19
- const loader = kvLoader(namespace, { key: "decofile:abc" });
20
- expect(await loader.load()).toEqual(snapshot);
21
- expect(await loader.load("api.deco.example/drafts/x@v1")).toEqual(snapshot);
22
- expect(namespace.get).toHaveBeenCalledTimes(1);
23
- expect(namespace.get).toHaveBeenCalledWith("decofile:abc", "json");
24
- expect(loader.update).toBeUndefined();
25
- });
26
-
27
- it("shares one in-flight read between concurrent loads", async () => {
28
- let release!: (value: unknown) => void;
29
- const namespace = { get: vi.fn(() => new Promise((resolve) => (release = resolve))) };
30
- const loader = kvLoader(namespace, { key: "content" });
31
- const first = loader.load();
32
- const second = loader.load();
33
- release(snapshot);
34
- expect(await first).toEqual(snapshot);
35
- expect(await second).toEqual(snapshot);
36
- expect(namespace.get).toHaveBeenCalledTimes(1);
37
- });
38
-
39
- it("fails on a missing key and reads KV again on the next call", async () => {
40
- const values: Record<string, unknown> = {};
41
- const namespace = kv(values);
42
- const loader = kvLoader(namespace, { key: "decofile:abc" });
43
- await expect(loader.load()).rejects.toThrow(/decofile:abc/);
44
- values["decofile:abc"] = snapshot;
45
- expect(await loader.load()).toEqual(snapshot);
46
- expect(namespace.get).toHaveBeenCalledTimes(2);
47
- });
48
-
49
- it("serves a CMS without reading KV per request", async () => {
50
- const namespace = kv({ content: snapshot });
51
- const cms = createCMS({
52
- blocks: { greeting: (input: { name: string }) => `Hello, ${input.name}` },
53
- content: kvLoader(namespace, { key: "content" }),
54
- });
55
- expect(await cms.forRelease().resolve("Hello")).toEqual(["Hello, world", null]);
56
- expect(await cms.forRelease().resolve("Hello")).toEqual(["Hello, world", null]);
57
- expect(namespace.get).toHaveBeenCalledTimes(1);
58
- });
59
-
60
- it("surfaces a missing key as LOADER_FAILED", async () => {
61
- const cms = createCMS({ blocks: {}, content: kvLoader(kv({}), { key: "content" }) });
62
- const [, error] = await cms.forRelease().list("page");
63
- expect(error?.code).toBe("LOADER_FAILED");
64
- });
65
-
66
- it("surfaces a value that isn't a snapshot as LOADER_FAILED", async () => {
67
- const cms = createCMS({
68
- blocks: {},
69
- content: kvLoader(kv({ content: {} }), { key: "content" }),
70
- });
71
- const [, error] = await cms.forRelease().list("page");
72
- expect(error?.code).toBe("LOADER_FAILED");
73
- });
74
- });
@@ -1,43 +0,0 @@
1
- /**
2
- * `kvLoader(namespace, { key })`: the content snapshot your deploy stored in a
3
- * Workers KV namespace, for sites whose content is too large to bundle. See
4
- * /next/api-reference#loaders and /next/hosted-publishing#large-content-on-workers.
5
- */
6
- import type { Loader, Snapshot } from "@decocms/blocks";
7
-
8
- /** The one KV method this loader calls; a Workers `KVNamespace` binding fits it. */
9
- export interface KVNamespaceLike {
10
- get(key: string, type: "json"): Promise<unknown>;
11
- }
12
-
13
- /**
14
- * Reads the snapshot under `key` once per isolate and keeps it. It ignores
15
- * draft pointers and has no `update()`: the deploy writes the key before the
16
- * Worker takes traffic, and it doesn't change while the Worker runs. A missing
17
- * key or a failed read isn't kept, so the next request reads KV again.
18
- *
19
- * The kept read is a promise shared across requests, so the Worker needs the
20
- * `no_handle_cross_request_promise_resolution` compatibility flag, as the CMS
21
- * itself does (see /next/tanstack-start-descriptors).
22
- */
23
- export function kvLoader(namespace: KVNamespaceLike, options: { key: string }): Loader {
24
- const { key } = options;
25
- let snapshot: Promise<Snapshot> | undefined;
26
- return {
27
- load() {
28
- if (snapshot === undefined) {
29
- const pending = namespace.get(key, "json").then((value) => {
30
- if (value === null || value === undefined) {
31
- throw new Error(`kvLoader: no content snapshot under the KV key "${key}"`);
32
- }
33
- return value as Snapshot;
34
- });
35
- snapshot = pending;
36
- pending.catch(() => {
37
- if (snapshot === pending) snapshot = undefined;
38
- });
39
- }
40
- return snapshot;
41
- },
42
- };
43
- }
@@ -1,106 +0,0 @@
1
- import { EventEmitter } from "node:events";
2
- import * as fs from "node:fs";
3
- import * as os from "node:os";
4
- import * as path from "node:path";
5
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6
-
7
- const execCalls = [];
8
- const execFileSyncCalls = [];
9
-
10
- vi.mock("node:child_process", () => {
11
- const exec = (cmd, _opts, cb) => {
12
- execCalls.push(cmd);
13
- cb(null, "", "");
14
- };
15
- const execFileSync = (cmd, args) => {
16
- execFileSyncCalls.push([cmd, args]);
17
- return "";
18
- };
19
- return { exec, execFileSync, default: { exec, execFileSync } };
20
- });
21
-
22
- /**
23
- * Regression guard for #371: `vite dev` never re-ran the sections/loaders/
24
- * invoke generators, only `npm run build` did (via the full `generate`
25
- * orchestrator) — so editing a section/loader's TS interface left the
26
- * `.gen` files silently stale until a manual `generate` run. This test
27
- * exercises `configureServer`'s scaffold-gen hook against a real
28
- * (empty) tmp dir + a real EventEmitter as `server.watcher`, with
29
- * `node:child_process` mocked so no real subprocess is spawned.
30
- */
31
- describe("decoVitePlugin — sections/loaders/invoke dev regeneration (#371)", () => {
32
- let tmp;
33
- let cwdSpy;
34
- let plugin;
35
-
36
- beforeEach(async () => {
37
- vi.resetModules();
38
- execCalls.length = 0;
39
- execFileSyncCalls.length = 0;
40
- tmp = fs.mkdtempSync(path.join(os.tmpdir(), "plugin-scaffold-gen-"));
41
- cwdSpy = vi.spyOn(process, "cwd").mockReturnValue(tmp);
42
- vi.useFakeTimers();
43
- ({ decoVitePlugin: plugin } = await import("./plugin.js"));
44
- });
45
-
46
- afterEach(() => {
47
- vi.useRealTimers();
48
- cwdSpy.mockRestore();
49
- fs.rmSync(tmp, { recursive: true, force: true });
50
- vi.restoreAllMocks();
51
- });
52
-
53
- function makeServer() {
54
- return {
55
- watcher: new EventEmitter(),
56
- config: { define: {} },
57
- environments: undefined,
58
- httpServer: { once: () => {} },
59
- };
60
- }
61
-
62
- it("runs the sections/loaders/invoke generator on dev startup (debounced)", async () => {
63
- const p = Array.isArray(plugin()) ? plugin()[0] : plugin();
64
- const server = makeServer();
65
- p.configureServer(server);
66
-
67
- await vi.advanceTimersByTimeAsync(600);
68
-
69
- const scaffoldCalls = execCalls.filter((c) => c.includes("--only sections,loaders,invoke"));
70
- expect(scaffoldCalls).toHaveLength(1);
71
- expect(scaffoldCalls[0]).toContain("generate.ts");
72
- });
73
-
74
- it("debounces multiple src/ file-watcher events into a single regen call", async () => {
75
- const p = Array.isArray(plugin()) ? plugin()[0] : plugin();
76
- const server = makeServer();
77
- p.configureServer(server);
78
-
79
- // Consume the cold-start call first.
80
- await vi.advanceTimersByTimeAsync(600);
81
- execCalls.length = 0;
82
-
83
- const srcFile = path.join(tmp, "src", "sections", "Foo.tsx");
84
- server.watcher.emit("change", srcFile);
85
- server.watcher.emit("change", srcFile);
86
- server.watcher.emit("add", srcFile);
87
-
88
- await vi.advanceTimersByTimeAsync(600);
89
-
90
- const scaffoldCalls = execCalls.filter((c) => c.includes("--only sections,loaders,invoke"));
91
- expect(scaffoldCalls).toHaveLength(1);
92
- });
93
-
94
- it("does not trigger for a file outside src/", async () => {
95
- const p = Array.isArray(plugin()) ? plugin()[0] : plugin();
96
- const server = makeServer();
97
- p.configureServer(server);
98
- await vi.advanceTimersByTimeAsync(600);
99
- execCalls.length = 0;
100
-
101
- server.watcher.emit("change", path.join(tmp, "README.md"));
102
- await vi.advanceTimersByTimeAsync(600);
103
-
104
- expect(execCalls.filter((c) => c.includes("--only sections,loaders,invoke"))).toHaveLength(0);
105
- });
106
- });