@decocms/nextjs 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 (84) hide show
  1. package/README.md +77 -330
  2. package/dist/DraftPreviewIndicator.d.ts +7 -0
  3. package/dist/DraftPreviewIndicator.d.ts.map +1 -0
  4. package/dist/DraftPreviewIndicator.js +19 -0
  5. package/dist/DraftPreviewIndicator.js.map +1 -0
  6. package/dist/StudioBridge.d.ts +16 -0
  7. package/dist/StudioBridge.d.ts.map +1 -0
  8. package/dist/StudioBridge.js +17 -0
  9. package/dist/StudioBridge.js.map +1 -0
  10. package/dist/draft.d.ts +35 -0
  11. package/dist/draft.d.ts.map +1 -0
  12. package/dist/draft.js +43 -0
  13. package/dist/draft.js.map +1 -0
  14. package/dist/drafts.d.ts +94 -0
  15. package/dist/drafts.d.ts.map +1 -0
  16. package/dist/drafts.js +210 -0
  17. package/dist/drafts.js.map +1 -0
  18. package/dist/image-loader/index.d.ts +36 -0
  19. package/dist/image-loader/index.d.ts.map +1 -0
  20. package/dist/image-loader/index.js +27 -0
  21. package/dist/image-loader/index.js.map +1 -0
  22. package/dist/index.d.ts +29 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +29 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/proxy/index.d.ts +79 -0
  27. package/dist/proxy/index.d.ts.map +1 -0
  28. package/dist/proxy/index.js +92 -0
  29. package/dist/proxy/index.js.map +1 -0
  30. package/dist/server/index.d.ts +46 -0
  31. package/dist/server/index.d.ts.map +1 -0
  32. package/dist/server/index.js +64 -0
  33. package/dist/server/index.js.map +1 -0
  34. package/dist/server/slot.d.ts +6 -0
  35. package/dist/server/slot.d.ts.map +1 -0
  36. package/dist/server/slot.js +13 -0
  37. package/dist/server/slot.js.map +1 -0
  38. package/dist/studio.d.ts +30 -0
  39. package/dist/studio.d.ts.map +1 -0
  40. package/dist/studio.js +55 -0
  41. package/dist/studio.js.map +1 -0
  42. package/package.json +41 -22
  43. package/src/DraftPreviewIndicator.tsx +17 -16
  44. package/src/StudioBridge.ts +23 -0
  45. package/src/config/index.cjs +78 -0
  46. package/src/config/index.d.cts +27 -0
  47. package/src/draft.ts +30 -216
  48. package/src/drafts.ts +229 -0
  49. package/src/image-loader/index.ts +62 -0
  50. package/src/index.ts +31 -45
  51. package/src/proxy/index.ts +161 -0
  52. package/src/server/index.ts +77 -0
  53. package/src/server/slot.ts +14 -0
  54. package/src/studio.ts +54 -0
  55. package/src/ClientOnlySection.tsx +0 -20
  56. package/src/DecoPageRenderer.test.tsx +0 -37
  57. package/src/DecoPageRenderer.tsx +0 -107
  58. package/src/DecoRootLayout.test.tsx +0 -22
  59. package/src/DecoRootLayout.tsx +0 -82
  60. package/src/DeferredSection.test.tsx +0 -27
  61. package/src/DeferredSection.tsx +0 -59
  62. package/src/DraftPreviewBadge.tsx +0 -16
  63. package/src/SectionRenderer.test.tsx +0 -97
  64. package/src/SectionRenderer.tsx +0 -58
  65. package/src/__conformance__/observability.test.ts +0 -66
  66. package/src/config.cjs +0 -92
  67. package/src/config.d.cts +0 -4
  68. package/src/config.test.ts +0 -86
  69. package/src/createDecoPage.draft.test.tsx +0 -91
  70. package/src/createDecoPage.test.tsx +0 -63
  71. package/src/createDecoPage.tsx +0 -173
  72. package/src/createDecoPreviewPage.test.tsx +0 -71
  73. package/src/createDecoPreviewPage.tsx +0 -108
  74. package/src/draft.test.ts +0 -73
  75. package/src/draftConstants.test.ts +0 -21
  76. package/src/draftConstants.ts +0 -30
  77. package/src/draftMiddleware.test.ts +0 -179
  78. package/src/draftMiddleware.ts +0 -163
  79. package/src/draftShell.test.ts +0 -76
  80. package/src/routeHandlers.test.ts +0 -243
  81. package/src/routeHandlers.ts +0 -227
  82. package/src/setup.test.ts +0 -253
  83. package/src/setup.ts +0 -180
  84. package/tsconfig.json +0 -7
@@ -1,163 +0,0 @@
1
- /**
2
- * Draft preview — middleware half.
3
- *
4
- * Two composable calls, because sites already own their middleware and this
5
- * must slot into it rather than replace it:
6
- *
7
- * ```ts
8
- * // middleware.ts (Next <16) / proxy.ts (Next 16+)
9
- * export function middleware(request: NextRequest) {
10
- * const decision = prepareDraft(request);
11
- * return applyDraft(NextResponse.next(), decision);
12
- * }
13
- * ```
14
- *
15
- * The middleware owns only the cookie and the cache/indexing headers — a
16
- * Server Component can read cookies but cannot set them, so that part has to
17
- * live here. The pointer itself is read by the page.
18
- *
19
- * Lives on its own subpath so middleware (edge runtime) never imports the root
20
- * barrel, which pulls in the client component graph.
21
- */
22
-
23
- import { isDraftHostAllowed } from "@decocms/blocks/cms";
24
- import { type NextRequest, NextResponse } from "next/server";
25
- import {
26
- DRAFT_COOKIE,
27
- DRAFT_COOKIE_OPTIONS,
28
- DRAFT_HEADER,
29
- type DraftMiddlewareDecision,
30
- decideDraft,
31
- } from "./draft";
32
-
33
- /**
34
- * Compute the draft decision for a request.
35
- *
36
- * Only the cookie and the response headers are the middleware's business now —
37
- * the page reads the pointer itself from `searchParams` + `cookies()`, so
38
- * nothing has to be forwarded through the request. That also means a draft
39
- * still works on routes this middleware never matches.
40
- */
41
- const INERT: DraftMiddlewareDecision = { pointer: null, setCookie: null, clearCookie: false };
42
-
43
- export function prepareDraft(request: NextRequest): DraftMiddlewareDecision {
44
- // The AUTHORITATIVE host gate lives page-side (`ensureDraft`): the site
45
- // block's `previewHosts` are installed in the server-components graph, and
46
- // middleware runs in a separate module graph/runtime that never sees them.
47
- // Middleware therefore hard-gates only on the env override — keeping
48
- // DECO_ALLOWED_PREVIEW_HOSTS a full kill switch — and otherwise passes the
49
- // decision through. Worst case on a non-preview host is a cookie the
50
- // page-side gate then ignores; drafts never render there.
51
- if (process.env.DECO_ALLOWED_PREVIEW_HOSTS) {
52
- const host =
53
- request.headers.get("x-forwarded-host") ??
54
- request.headers.get("host") ??
55
- request.nextUrl.host;
56
- if (!isDraftHostAllowed(host)) return INERT;
57
- }
58
- return decideDraft(new URL(request.url), request.cookies.get(DRAFT_COOKIE)?.value ?? null);
59
- }
60
-
61
- /**
62
- * URL prefix a drafted request is rewritten onto.
63
- *
64
- * The site must mount the matching route as `app/%5Fdraft/...` — URL-encoded.
65
- * A literal `_draft/` directory is a Next "private folder", excluded from
66
- * routing entirely, so the rewrite would fall through to whatever catch-all
67
- * follows and 404. The encoded directory serves the same `/_draft` URL while
68
- * staying routable.
69
- */
70
- export const DRAFT_ROUTE_PREFIX = "/_draft";
71
-
72
- /**
73
- * Rewrite a drafted request onto the dynamic draft route.
74
- *
75
- * This exists because `dynamic` / `revalidate` are STATIC route exports: a
76
- * statically rendered page cannot become dynamic for one request. Making the
77
- * real route dynamic to support drafts would cost every shopper their cached
78
- * page, and — worse — a statically rendered draft would be cached and served to
79
- * them. Rewriting sends only drafted requests to a route that is dynamic by
80
- * construction, leaving ordinary traffic's ISR completely untouched.
81
- *
82
- * The original path is preserved in the rewritten pathname, so the draft route
83
- * can resolve exactly the page the visitor asked for.
84
- *
85
- * Returns null when this request is not drafted, so callers fall through to
86
- * their normal response.
87
- */
88
- export function rewriteToDraftRoute(
89
- request: NextRequest,
90
- decision: DraftMiddlewareDecision,
91
- ): NextResponse | null {
92
- if (!decision.pointer) return null;
93
- const url = request.nextUrl.clone();
94
- // Already rewritten (Next re-runs middleware on the rewritten URL in some
95
- // configurations) — never nest the prefix.
96
- if (url.pathname.startsWith(`${DRAFT_ROUTE_PREFIX}/`)) return null;
97
- url.pathname = `${DRAFT_ROUTE_PREFIX}${url.pathname}`;
98
- return NextResponse.rewrite(url);
99
- }
100
-
101
- /**
102
- * Apply the cookie and the cache/indexing headers a draft response requires.
103
- *
104
- * The caching headers are the difference between a preview and a **leak**.
105
- * With the pointer in a cookie, a draft response and a published one share an
106
- * identical URL, so a CDN keyed on URL alone would happily serve unpublished
107
- * content to a real visitor. `no-store` is what actually prevents that;
108
- * `Vary: Cookie` keeps any intermediary that *does* respect it from mixing the
109
- * two; `X-Robots-Tag` keeps a leaked draft out of search results.
110
- */
111
- export function applyDraft(
112
- response: NextResponse,
113
- decision: DraftMiddlewareDecision,
114
- ): NextResponse {
115
- if (decision.clearCookie) {
116
- response.cookies.delete(DRAFT_COOKIE);
117
- } else if (decision.setCookie) {
118
- response.cookies.set(DRAFT_COOKIE, decision.setCookie, DRAFT_COOKIE_OPTIONS);
119
- }
120
-
121
- if (decision.pointer) {
122
- response.headers.set("cache-control", "no-store, private");
123
- response.headers.set("vary", "Cookie");
124
- response.headers.set("x-robots-tag", "noindex, nofollow");
125
- }
126
-
127
- return response;
128
- }
129
-
130
- /**
131
- * Request headers to forward downstream, carrying the active pointer on
132
- * `x-deco-draft` (see {@link DRAFT_HEADER}) so the RSC tree — including the app
133
- * shell — can bind the draft via `ensureDraft()` and reflect it in
134
- * shell-resolved Header/Footer, not only page sections.
135
- *
136
- * Pass to `NextResponse.next({ request: { headers } })`. Strips any
137
- * client-supplied `x-deco-draft` when this request is not previewing, so the
138
- * header is only ever present on a legitimately-gated preview request.
139
- */
140
- export function draftRequestHeaders(
141
- request: NextRequest,
142
- decision: DraftMiddlewareDecision,
143
- ): Headers {
144
- const headers = new Headers(request.headers);
145
- if (decision.pointer) headers.set(DRAFT_HEADER, decision.pointer);
146
- else headers.delete(DRAFT_HEADER);
147
- return headers;
148
- }
149
-
150
- /**
151
- * Convenience for sites with no middleware of their own: prepare, forward the
152
- * pointer header, continue, apply. Sites that already have middleware should
153
- * call the halves directly (`prepareDraft` → `draftRequestHeaders` on the
154
- * `NextResponse.next({ request: { headers } })` → `applyDraft`) so their own
155
- * logic sits in between.
156
- */
157
- export function draftMiddleware(request: NextRequest): NextResponse {
158
- const decision = prepareDraft(request);
159
- const response = NextResponse.next({
160
- request: { headers: draftRequestHeaders(request, decision) },
161
- });
162
- return applyDraft(response, decision);
163
- }
@@ -1,76 +0,0 @@
1
- /**
2
- * `ensureDraft()` must bind from the middleware-forwarded `x-deco-draft` header
3
- * — the only pointer source a LAYOUT (app shell) can see: it receives no
4
- * `searchParams`, and on the entry request the cookie has only just been set on
5
- * the response. This is what lets shell-resolved Header/Footer reflect a draft,
6
- * not just page sections.
7
- */
8
- import { clearDraftCache } from "@decocms/blocks/cms";
9
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
10
-
11
- // Mutable header/cookie state the mock reads, so each test drives its own.
12
- let headerState = new Headers();
13
- let cookieState: Record<string, string> = {};
14
-
15
- vi.mock("next/headers", () => ({
16
- headers: async () => headerState,
17
- cookies: async () => ({
18
- get: (name: string) =>
19
- name in cookieState ? { name, value: cookieState[name] } : undefined,
20
- }),
21
- }));
22
-
23
- const { ensureDraft, DRAFT_HEADER, DRAFT_COOKIE } = await import("./draft");
24
-
25
- const DRAFT_BLOCKS = { "pages-home": { title: "DRAFT" } };
26
- const POINTER = "abc.localhost:60534/api/o/decofile/m/main?token=t@v1";
27
-
28
- beforeEach(() => {
29
- headerState = new Headers({ host: "site.example" });
30
- cookieState = {};
31
- process.env.DECO_ALLOWED_PREVIEW_HOSTS = "site.example";
32
- clearDraftCache();
33
- vi.stubGlobal(
34
- "fetch",
35
- vi.fn(async (url: string) => {
36
- if (
37
- String(url) ===
38
- "http://abc.localhost:60534/api/o/decofile/m/main?token=t"
39
- ) {
40
- return new Response(JSON.stringify(DRAFT_BLOCKS), {
41
- status: 200,
42
- headers: { "content-type": "application/json" },
43
- });
44
- }
45
- throw new Error(`unexpected fetch: ${url}`);
46
- }),
47
- );
48
- });
49
-
50
- afterEach(() => {
51
- vi.unstubAllGlobals();
52
- delete process.env.DECO_ALLOWED_PREVIEW_HOSTS;
53
- });
54
-
55
- describe("ensureDraft — app-shell (layout) binding via the forwarded header", () => {
56
- it("binds the draft from x-deco-draft with no searchParams (the layout case)", async () => {
57
- headerState.set(DRAFT_HEADER, POINTER);
58
- // No searchParams (layouts get none) and no cookie (entry request).
59
- expect(await ensureDraft()).toBe(true);
60
- });
61
-
62
- it("still binds from the cookie when there is no forwarded header", async () => {
63
- cookieState[DRAFT_COOKIE] = POINTER;
64
- expect(await ensureDraft()).toBe(true);
65
- });
66
-
67
- it("does not bind when neither header, cookie, nor param is present", async () => {
68
- expect(await ensureDraft()).toBe(false);
69
- });
70
-
71
- it("stays gated by the host allowlist even with a forwarded header", async () => {
72
- headerState = new Headers({ host: "prod.example" });
73
- headerState.set(DRAFT_HEADER, POINTER);
74
- expect(await ensureDraft()).toBe(false);
75
- });
76
- });
@@ -1,243 +0,0 @@
1
- // @vitest-environment node
2
- //
3
- // Route Handlers run server-side with no DOM (same rationale as
4
- // setup.test.ts in this package). This matters concretely here: jsdom's
5
- // bundled Request polyfill does not reproduce Node/edge's Request-as-init
6
- // body-stream forwarding (`new Request(url, existingRequest)`) — under
7
- // jsdom the body-forwarding test below silently loses the body. Node's
8
- // native Request (used in this environment, and in the real Next.js
9
- // runtime) preserves it, which is what the previews-rebuild code path
10
- // relies on.
11
- import { beforeEach, describe, expect, it, vi } from "vitest";
12
-
13
- const mocks = vi.hoisted(() => ({
14
- handleDecofileRead: vi.fn(async () => new Response("decofile")),
15
- handleDecofileReload: vi.fn(async () => new Response("reloaded")),
16
- handleInvoke: vi.fn(async () => new Response("invoked")),
17
- handleMeta: vi.fn(() => new Response("meta")),
18
- handleRender: vi.fn(async (req: Request) => new Response(new URL(req.url).pathname)),
19
- setMetaData: vi.fn(),
20
- // Real corsHeaders shape (mirrors blocks-admin/src/admin/cors.ts) so the
21
- // CORS assertions below test genuine header propagation, not a stub echo.
22
- corsHeaders: vi.fn((req: Request) => ({
23
- "Access-Control-Allow-Origin": req.headers.get("origin") || "*",
24
- "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
25
- "Access-Control-Allow-Headers": "Content-Type, Authorization, If-None-Match",
26
- "Access-Control-Allow-Credentials": "true",
27
- })),
28
- }));
29
- vi.mock("@decocms/blocks-admin", () => mocks);
30
-
31
- import { setMetaData } from "@decocms/blocks-admin";
32
- import { createDecoRouteHandlers, metaGET } from "./routeHandlers";
33
-
34
- describe("routeHandlers (next)", () => {
35
- it("metaGET returns the schema response", async () => {
36
- setMetaData({ sections: {}, actions: {}, loaders: {} } as any);
37
- const response = await metaGET(new Request("https://example.com/live/_meta"));
38
- expect(response.status).toBe(200);
39
- });
40
- });
41
-
42
- describe("createDecoRouteHandlers", () => {
43
- beforeEach(() => vi.clearAllMocks());
44
-
45
- it("runs setup before dispatching and routes decofile GET/POST", async () => {
46
- const order: string[] = [];
47
- const setup = vi.fn(async () => {
48
- order.push("setup");
49
- });
50
- const { GET, POST } = createDecoRouteHandlers({ setup });
51
-
52
- await GET(new Request("http://x/deco/decofile"));
53
- expect(setup).toHaveBeenCalled();
54
- expect(mocks.handleDecofileRead).toHaveBeenCalled();
55
-
56
- await POST(new Request("http://x/deco/decofile", { method: "POST" }));
57
- expect(mocks.handleDecofileReload).toHaveBeenCalled();
58
- });
59
-
60
- it("routes meta, render, and invoke", async () => {
61
- const { GET, POST } = createDecoRouteHandlers();
62
- await GET(new Request("http://x/deco/meta"));
63
- expect(mocks.handleMeta).toHaveBeenCalled();
64
- await POST(new Request("http://x/deco/render", { method: "POST" }));
65
- expect(mocks.handleRender).toHaveBeenCalled();
66
- await POST(new Request("http://x/deco/invoke/site/actions/x", { method: "POST" }));
67
- expect(mocks.handleInvoke).toHaveBeenCalled();
68
- });
69
-
70
- it("redirects preview GETs to the fixed RSC page and preserves the path and query", async () => {
71
- const { GET } = createDecoRouteHandlers();
72
- const res = await GET(
73
- new Request("http://x/deco/previews/pages-Home-123?props=x&deviceHint=mobile"),
74
- );
75
-
76
- expect(res.status).toBe(307);
77
- expect(res.headers.get("location")).toBe(
78
- "http://x/deco/preview/pages-Home-123?props=x&deviceHint=mobile",
79
- );
80
- expect(mocks.handleRender).not.toHaveBeenCalled();
81
- });
82
-
83
- it("redirects the public /live/previews path to the fixed RSC page", async () => {
84
- const { GET } = createDecoRouteHandlers();
85
- const res = await GET(
86
- new Request("http://x/live/previews/site/sections/Hero.tsx?deviceHint=desktop"),
87
- );
88
-
89
- expect(res.status).toBe(307);
90
- expect(res.headers.get("location")).toBe(
91
- "http://x/deco/preview/site/sections/Hero.tsx?deviceHint=desktop",
92
- );
93
- expect(mocks.handleRender).not.toHaveBeenCalled();
94
- });
95
-
96
- it("keeps preview POSTs on handleRender", async () => {
97
- const { POST } = createDecoRouteHandlers();
98
- const res = await POST(
99
- new Request("http://x/deco/previews/pages-Home-123", {
100
- method: "POST",
101
- headers: { "Content-Type": "application/json" },
102
- body: JSON.stringify({ hello: "world" }),
103
- }),
104
- );
105
-
106
- expect(res.status).toBe(200);
107
- expect(mocks.handleRender).toHaveBeenCalledOnce();
108
- });
109
-
110
- it("forwards a POST body through the /deco/previews/* URL rebuild (Request-as-init carries the body stream)", async () => {
111
- // Pins the `new Request(rebuilt, request)` semantics documented on the
112
- // rebuild line: passing a Request as `init` clones the body stream
113
- // without a `duplex` option. A refactor to a plain init object would
114
- // throw "duplex option is required" for this POST body.
115
- mocks.handleRender.mockImplementationOnce(async (req: Request) => {
116
- const body = await req.json();
117
- return new Response(JSON.stringify({ pathname: new URL(req.url).pathname, body }));
118
- });
119
- const { POST } = createDecoRouteHandlers();
120
- const res = await POST(
121
- new Request("http://x/deco/previews/pages-Home-123", {
122
- method: "POST",
123
- headers: { "Content-Type": "application/json" },
124
- body: JSON.stringify({ hello: "world" }),
125
- }),
126
- );
127
- const json = await res.json();
128
- expect(json.pathname).toBe("/live/previews/pages-Home-123");
129
- expect(json.body).toEqual({ hello: "world" });
130
- });
131
-
132
- it("404s unknown deco paths", async () => {
133
- const { GET } = createDecoRouteHandlers();
134
- const res = await GET(new Request("http://x/deco/nope"));
135
- expect(res.status).toBe(404);
136
- });
137
-
138
- // Regression coverage for the rewrite-source paths, not just their
139
- // /deco/* destinations: a Next.js App Router route handler reached via a
140
- // next.config.js `rewrites()` entry sees `request.url` as the ORIGINAL,
141
- // pre-rewrite path (verified empirically against a real `next build` +
142
- // `next start`) — NOT the /deco/* destination the rewrite maps to. Every
143
- // test above this one only ever constructs an already-/deco/*-shaped
144
- // Request, so it would keep passing even if the dispatcher only matched
145
- // that form and 404'd every real rewritten request — which is exactly
146
- // the bug these tests catch.
147
- it("routes the rewrite-source /.decofile path (not just its /deco/decofile destination)", async () => {
148
- const { GET, POST } = createDecoRouteHandlers();
149
- await GET(new Request("http://x/.decofile"));
150
- expect(mocks.handleDecofileRead).toHaveBeenCalled();
151
- await POST(new Request("http://x/.decofile", { method: "POST" }));
152
- expect(mocks.handleDecofileReload).toHaveBeenCalled();
153
- });
154
-
155
- it("routes the rewrite-source /live/_meta path (not just its /deco/meta destination)", async () => {
156
- const { GET } = createDecoRouteHandlers();
157
- const res = await GET(new Request("http://x/live/_meta"));
158
- expect(mocks.handleMeta).toHaveBeenCalled();
159
- expect(res.status).not.toBe(404);
160
- });
161
-
162
- it("405s POST /live/_meta with Allow: GET (the PRE-rewrite URL form)", async () => {
163
- const { POST } = createDecoRouteHandlers();
164
- const res = await POST(new Request("http://x/live/_meta", { method: "POST" }));
165
- expect(res.status).toBe(405);
166
- expect(res.headers.get("Allow")).toBe("GET");
167
- expect(mocks.handleMeta).not.toHaveBeenCalled();
168
- });
169
-
170
- it("redirects the rewrite-source /live/previews/* path to the fixed RSC page", async () => {
171
- const { GET } = createDecoRouteHandlers();
172
- const res = await GET(new Request("http://x/live/previews/pages-Home-123?props=x"));
173
- expect(res.status).toBe(307);
174
- expect(res.headers.get("location")).toBe("http://x/deco/preview/pages-Home-123?props=x");
175
- expect(mocks.handleRender).not.toHaveBeenCalled();
176
- });
177
-
178
- it("405s GET /deco/invoke/* with Allow: POST (CSRF protection — see comment on the invoke branch)", async () => {
179
- const { GET } = createDecoRouteHandlers();
180
- const res = await GET(new Request("http://x/deco/invoke/site/actions/x"));
181
- expect(res.status).toBe(405);
182
- expect(res.headers.get("Allow")).toBe("POST");
183
- expect(mocks.handleInvoke).not.toHaveBeenCalled();
184
- });
185
-
186
- it("405s POST /deco/meta with Allow: GET", async () => {
187
- const { POST } = createDecoRouteHandlers();
188
- const res = await POST(new Request("http://x/deco/meta", { method: "POST" }));
189
- expect(res.status).toBe(405);
190
- expect(res.headers.get("Allow")).toBe("GET");
191
- expect(mocks.handleMeta).not.toHaveBeenCalled();
192
- });
193
- });
194
-
195
- describe("createDecoRouteHandlers — CORS (Studio is a cross-origin browser client)", () => {
196
- beforeEach(() => vi.clearAllMocks());
197
-
198
- it("answers OPTIONS preflight with 204 + CORS headers, without running setup", async () => {
199
- const setup = vi.fn(async () => {});
200
- const { OPTIONS } = createDecoRouteHandlers({ setup });
201
- const res = await OPTIONS(
202
- new Request("http://x/live/_meta", {
203
- method: "OPTIONS",
204
- headers: {
205
- origin: "https://decocms.com",
206
- "access-control-request-method": "GET",
207
- "access-control-request-headers": "if-none-match",
208
- },
209
- }),
210
- );
211
- expect(res.status).toBe(204);
212
- expect(res.headers.get("Access-Control-Allow-Origin")).toBe("https://decocms.com");
213
- expect(res.headers.get("Access-Control-Allow-Headers")).toContain("If-None-Match");
214
- expect(setup).not.toHaveBeenCalled();
215
- });
216
-
217
- it("stamps CORS headers on successful responses (meta via pre-rewrite URL)", async () => {
218
- const { GET } = createDecoRouteHandlers();
219
- const res = await GET(
220
- new Request("http://x/live/_meta", { headers: { origin: "https://admin.deco.cx" } }),
221
- );
222
- expect(await res.text()).toBe("meta");
223
- expect(res.headers.get("Access-Control-Allow-Origin")).toBe("https://admin.deco.cx");
224
- });
225
-
226
- it("stamps CORS headers on method-gate 405s too", async () => {
227
- const { GET } = createDecoRouteHandlers();
228
- const res = await GET(
229
- new Request("http://x/deco/invoke/site/actions/x", {
230
- headers: { origin: "https://decocms.com" },
231
- }),
232
- );
233
- expect(res.status).toBe(405);
234
- expect(res.headers.get("Access-Control-Allow-Origin")).toBe("https://decocms.com");
235
- });
236
-
237
- it("named exports carry CORS as well (metaGET)", async () => {
238
- const res = await metaGET(
239
- new Request("http://x/live/_meta", { headers: { origin: "https://decocms.com" } }),
240
- );
241
- expect(res.headers.get("Access-Control-Allow-Origin")).toBe("https://decocms.com");
242
- });
243
- });