siteplane 0.3.5 → 0.3.7

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.
@@ -790,6 +790,7 @@ async function readBoundedText(body, maxBytes) {
790
790
  }
791
791
 
792
792
  // src/runtime/preview.ts
793
+ var PREVIEW_COOKIE = "siteplane-preview";
793
794
  var COUNT_COOKIE = "siteplane-count";
794
795
  async function verifySitePreviewToken(config, token, keys, now) {
795
796
  const verify = async (reload) => verifyPreviewToken({
@@ -920,6 +921,43 @@ function isRecord2(value) {
920
921
  return typeof value === "object" && value !== null && !Array.isArray(value);
921
922
  }
922
923
 
924
+ // src/route/frame-script.ts
925
+ var FRAME_PARAM = "siteplane-frame";
926
+ var PREVIEW_HEADER = "x-siteplane-preview";
927
+ var PAGE_HEADER = "x-siteplane-path";
928
+ var FRAME_SCRIPT = `(()=>{
929
+ const script=document.currentScript,{token,path,direct}=JSON.parse(script.dataset.siteplaneFrame),route=location.pathname,base=route.replace(/\\/api\\/siteplane\\/draft\\/?$/,"");
930
+ script.remove();
931
+ history.replaceState(history.state,"",path+location.hash);
932
+ const below=url=>{const full=url.pathname;return(base&&(full===base||full.startsWith(base+"/"))?full.slice(base.length)||"/":full)+url.search};
933
+ const through=(url,open)=>{const to=new URL(route,location.origin);to.searchParams.set("path",below(url));to.searchParams.set("${FRAME_PARAM}","page");if(open)to.searchParams.set("token",token);return to};
934
+ const plain=href=>{const url=new URL(href,location.origin);url.searchParams.delete("_rsc");return url.pathname+url.search};
935
+ const send=window.fetch;
936
+ window.fetch=async function(input,init){
937
+ const request=input instanceof Request,headers=new Headers((init&&init.headers)||(request?input.headers:undefined));
938
+ let url;try{url=new URL(request?input.url:String(input),document.baseURI)}catch{return send.call(this,input,init)}
939
+ if(url.origin!==location.origin||!(direct||headers.has("rsc")||headers.has("next-action")))return send.call(this,input,init);
940
+ headers.set("${PREVIEW_HEADER}",token);
941
+ if(direct)return send.call(this,input,{...init,headers});
942
+ const answer=await send.call(this,request?new Request(through(url),input):through(url),{...init,headers});
943
+ const page=answer.headers.get("${PAGE_HEADER}")||url.pathname+url.search,at=new URL(page,location.origin);
944
+ const flight=(answer.headers.get("content-type")||"").startsWith("text/x-component");
945
+ Object.defineProperty(answer,"url",{value:(flight?at:through(new URL(plain(page),location.origin),true)).href});
946
+ Object.defineProperty(answer,"redirected",{value:plain(page)!==plain(url.href)});
947
+ return answer};
948
+ addEventListener("click",event=>{
949
+ if(event.defaultPrevented||event.button||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey)return;
950
+ const link=event.target instanceof Element?event.target.closest("a[href]"):null;
951
+ if(!link||(link.target&&link.target!=="_self")||link.hasAttribute("download"))return;
952
+ const url=new URL(link.href);
953
+ if(url.origin!==location.origin||(url.hash&&url.pathname+url.search===location.pathname+location.search))return;
954
+ event.preventDefault();
955
+ location.assign(through(url,true).href)});
956
+ const place="siteplane-scroll:"+path;
957
+ window.siteplaneReload=()=>{try{sessionStorage.setItem(place,String(scrollY))}catch{}location.replace(through(new URL(location.href),true).href)};
958
+ try{const top=sessionStorage.getItem(place);if(top!==null){sessionStorage.removeItem(place);addEventListener("load",()=>scrollTo({top:Number(top),behavior:"instant"}))}}catch{}
959
+ })()`;
960
+
923
961
  // src/route/handlers.ts
924
962
  var MAX_REVALIDATION_BYTES = 16 * 1024;
925
963
  var noStore = { "Cache-Control": "no-store" };
@@ -932,6 +970,7 @@ function createRouteHandlers(dependencies) {
932
970
  }
933
971
  async function POST(request) {
934
972
  const config = dependencies.config();
973
+ if (config && routeName(request) === "draft" && request.headers.has(PREVIEW_HEADER)) return draft(request, config);
935
974
  if (!config || routeName(request) !== "revalidate") return notFound();
936
975
  return revalidate(request, config);
937
976
  }
@@ -965,10 +1004,26 @@ function createRouteHandlers(dependencies) {
965
1004
  return redirect(url, path, await dependencies.enableCount?.() ?? {});
966
1005
  }
967
1006
  const now = dependencies.now();
968
- const token = query.get("token") ?? "";
1007
+ const carried = request.headers.get(PREVIEW_HEADER);
1008
+ const token = carried ?? query.get("token") ?? "";
969
1009
  const claims = token ? await verifySitePreviewToken(config, token, dependencies.keys, now) : null;
970
1010
  if (!claims) return Response.json({ error: "preview_token_invalid" }, { status: 401, headers: noStore });
1011
+ if (carried !== null) {
1012
+ const page = ownRoute(path) ? null : await dependencies.framedPage?.({ request, path, token });
1013
+ return page ?? Response.json({ error: "preview_page_unavailable" }, { status: 502, headers: noStore });
1014
+ }
971
1015
  await dependencies.enableDraftMode({ token, maxAgeSeconds: claims.exp - Math.floor(now.getTime() / 1e3) });
1016
+ if (dependencies.framedPage && (query.has(FRAME_PARAM) || request.headers.get("sec-fetch-dest") === "iframe")) {
1017
+ const step = query.get(FRAME_PARAM);
1018
+ if (step !== "check" && step !== "page") {
1019
+ query.set(FRAME_PARAM, "check");
1020
+ return new Response(null, { status: 307, headers: { ...noStore, Location: `?${query}` } });
1021
+ }
1022
+ if (cookieOf(request, PREVIEW_COOKIE) !== token && !ownRoute(path)) {
1023
+ const page = await dependencies.framedPage({ request, path, token });
1024
+ if (page) return page;
1025
+ }
1026
+ }
972
1027
  return redirect(url, path);
973
1028
  }
974
1029
  function redirect(url, path, headers = {}) {
@@ -993,6 +1048,16 @@ function createRouteHandlers(dependencies) {
993
1048
  function routeName(request) {
994
1049
  return /\/api\/siteplane\/([a-z]+)\/?$/u.exec(new URL(request.url).pathname)?.[1] ?? null;
995
1050
  }
1051
+ function ownRoute(path) {
1052
+ return /(?:^|\/)api\/siteplane(?:\/|$)/u.test(new URL(path, "https://website.invalid").pathname);
1053
+ }
1054
+ function cookieOf(request, name) {
1055
+ for (const part of (request.headers.get("cookie") ?? "").split(";")) {
1056
+ const at = part.indexOf("=");
1057
+ if (at > 0 && part.slice(0, at).trim() === name) return decodeURIComponent(part.slice(at + 1).trim());
1058
+ }
1059
+ return null;
1060
+ }
996
1061
  function notFound() {
997
1062
  return Response.json({ error: "not_found" }, { status: 404, headers: noStore });
998
1063
  }
@@ -1005,7 +1070,7 @@ function readSiteId(payload) {
1005
1070
  }
1006
1071
 
1007
1072
  // src/version.ts
1008
- var PACKAGE_VERSION = "0.3.5";
1073
+ var PACKAGE_VERSION = "0.3.7";
1009
1074
 
1010
1075
  // src/astro/build-images.ts
1011
1076
  import { mkdir, readdir, readFile, rename, rm, writeFile } from "fs/promises";
@@ -1,7 +1,12 @@
1
1
  import {
2
+ PAGE_HEADER,
2
3
  PREVIEW_COOKIE,
4
+ PREVIEW_HEADER,
5
+ allowScript,
3
6
  buildInfo,
4
7
  createValueLoader,
8
+ frameScriptHash,
9
+ mergeFrameAncestors,
5
10
  runtimeCdnValuesUrl,
6
11
  runtimeValuesUrl,
7
12
  serverShared,
@@ -10,7 +15,7 @@ import {
10
15
  siteSchema,
11
16
  verifySitePreviewToken,
12
17
  webFetch
13
- } from "../chunk-46ZC6NGK.js";
18
+ } from "../chunk-C2GSMH3L.js";
14
19
 
15
20
  // ../shared/dist/field-id.js
16
21
  import { z } from "zod";
@@ -213,35 +218,6 @@ function isRecord(value) {
213
218
  return typeof value === "object" && value !== null && !Array.isArray(value);
214
219
  }
215
220
 
216
- // src/runtime/frame-ancestors.ts
217
- var FRAME_ANCESTORS = /^frame-ancestors(?:\s|$)/iu;
218
- function mergeFrameAncestors(policy, editorOrigins) {
219
- const policies = (policy ?? "").split(",").map(
220
- (text) => text.split(";").map((directive) => directive.trim()).filter(Boolean)
221
- ).filter((directives) => directives.length > 0);
222
- let extended = false;
223
- const merged = policies.map((directives) => {
224
- const index = directives.findIndex((directive) => FRAME_ANCESTORS.test(directive));
225
- if (index === -1) return directives;
226
- extended = true;
227
- const sources = (directives[index] ?? "").split(/\s+/u).slice(1);
228
- const allowed = sources.some((source) => source.toLowerCase() === "'none'") ? editorOrigins : [...sources, ...editorOrigins.filter((origin) => !sources.includes(origin))];
229
- return [
230
- ...directives.slice(0, index),
231
- `frame-ancestors ${allowed.join(" ") || "'none'"}`,
232
- // Browsers use the first directive of a name and ignore repeats.
233
- ...directives.slice(index + 1).filter((directive) => !FRAME_ANCESTORS.test(directive))
234
- ];
235
- });
236
- if (!extended) {
237
- const own = `frame-ancestors ${["'self'", ...editorOrigins].join(" ")}`;
238
- const last = merged.at(-1);
239
- if (last) last.push(own);
240
- else merged.push([own]);
241
- }
242
- return merged.map((directives) => directives.join("; ")).join(", ");
243
- }
244
-
245
221
  // src/runtime/read.ts
246
222
  var VALUE_TYPES = /* @__PURE__ */ new Set(["text", "textarea", "link", "image", "json"]);
247
223
  var notFound = "[Siteplane] siteplane.schema.ts was not found next to siteplane.config.json, or it has no default export defineSchema({ globals: [ \u2026 ] }). Describe the content there and run npx siteplane check. If the file was created while the dev server was running, restart the dev server: it looks for the file when it starts.";
@@ -514,6 +490,7 @@ function createSiteplaneMiddleware(dependencies) {
514
490
  );
515
491
  const response = await next();
516
492
  cache?.set(false);
493
+ if (response.headers.has(PAGE_HEADER)) return previewResponse(response, config.editorOrigins, await frameScriptHash());
517
494
  return preview ? previewResponse(response, config.editorOrigins) : response;
518
495
  };
519
496
  }
@@ -529,7 +506,7 @@ var onRequest = createSiteplaneMiddleware({
529
506
  });
530
507
  async function readPreview(context, config, dependencies) {
531
508
  try {
532
- const token = context.cookies.get(PREVIEW_COOKIE)?.value;
509
+ const token = context.request.headers.get(PREVIEW_HEADER) ?? context.cookies.get(PREVIEW_COOKIE)?.value;
533
510
  if (!token) return null;
534
511
  const claims = await verifySitePreviewToken(config, token, dependencies.keys, dependencies.now());
535
512
  return claims ? { token, editorOrigin: claims.editor_origin } : null;
@@ -548,8 +525,9 @@ var CDN_CACHE_HEADERS = [
548
525
  "cloudflare-cdn-cache-control",
549
526
  "surrogate-control"
550
527
  ];
551
- function previewResponse(response, editorOrigins) {
552
- const policy = mergeFrameAncestors(response.headers.get("content-security-policy"), editorOrigins);
528
+ function previewResponse(response, editorOrigins, script) {
529
+ const framed = mergeFrameAncestors(response.headers.get("content-security-policy"), editorOrigins);
530
+ const policy = script ? allowScript(framed, script) : framed;
553
531
  const forPreview = (headers) => {
554
532
  headers.set("cache-control", "no-store");
555
533
  headers.set("content-security-policy", policy);
@@ -1,13 +1,16 @@
1
1
  import {
2
+ FRAME_PARAM,
2
3
  PREVIEW_COOKIE,
4
+ PREVIEW_HEADER,
3
5
  buildInfo,
4
6
  readBoundedText,
5
7
  signingKeys,
6
8
  siteCacheTag,
7
9
  siteConfig,
8
10
  verifySitePreviewToken,
9
- verifySiteRevalidation
10
- } from "../chunk-46ZC6NGK.js";
11
+ verifySiteRevalidation,
12
+ withFrameScript
13
+ } from "../chunk-C2GSMH3L.js";
11
14
 
12
15
  // ../shared/dist/safe-redirect.js
13
16
  var UNSAFE_URL_CHARACTERS = /[\\\u0000-\u001f\u007f]/u;
@@ -41,6 +44,7 @@ function createRouteHandlers(dependencies) {
41
44
  }
42
45
  async function POST2(request) {
43
46
  const config = dependencies.config();
47
+ if (config && routeName(request) === "draft" && request.headers.has(PREVIEW_HEADER)) return draft(request, config);
44
48
  if (!config || routeName(request) !== "revalidate") return notFound();
45
49
  return revalidate(request, config);
46
50
  }
@@ -74,10 +78,26 @@ function createRouteHandlers(dependencies) {
74
78
  return redirect(url, path, await dependencies.enableCount?.() ?? {});
75
79
  }
76
80
  const now = dependencies.now();
77
- const token = query.get("token") ?? "";
81
+ const carried = request.headers.get(PREVIEW_HEADER);
82
+ const token = carried ?? query.get("token") ?? "";
78
83
  const claims = token ? await verifySitePreviewToken(config, token, dependencies.keys, now) : null;
79
84
  if (!claims) return Response.json({ error: "preview_token_invalid" }, { status: 401, headers: noStore });
85
+ if (carried !== null) {
86
+ const page = ownRoute(path) ? null : await dependencies.framedPage?.({ request, path, token });
87
+ return page ?? Response.json({ error: "preview_page_unavailable" }, { status: 502, headers: noStore });
88
+ }
80
89
  await dependencies.enableDraftMode({ token, maxAgeSeconds: claims.exp - Math.floor(now.getTime() / 1e3) });
90
+ if (dependencies.framedPage && (query.has(FRAME_PARAM) || request.headers.get("sec-fetch-dest") === "iframe")) {
91
+ const step = query.get(FRAME_PARAM);
92
+ if (step !== "check" && step !== "page") {
93
+ query.set(FRAME_PARAM, "check");
94
+ return new Response(null, { status: 307, headers: { ...noStore, Location: `?${query}` } });
95
+ }
96
+ if (cookieOf(request, PREVIEW_COOKIE) !== token && !ownRoute(path)) {
97
+ const page = await dependencies.framedPage({ request, path, token });
98
+ if (page) return page;
99
+ }
100
+ }
81
101
  return redirect(url, path);
82
102
  }
83
103
  function redirect(url, path, headers = {}) {
@@ -102,6 +122,16 @@ function createRouteHandlers(dependencies) {
102
122
  function routeName(request) {
103
123
  return /\/api\/siteplane\/([a-z]+)\/?$/u.exec(new URL(request.url).pathname)?.[1] ?? null;
104
124
  }
125
+ function ownRoute(path) {
126
+ return /(?:^|\/)api\/siteplane(?:\/|$)/u.test(new URL(path, "https://website.invalid").pathname);
127
+ }
128
+ function cookieOf(request, name) {
129
+ for (const part of (request.headers.get("cookie") ?? "").split(";")) {
130
+ const at = part.indexOf("=");
131
+ if (at > 0 && part.slice(0, at).trim() === name) return decodeURIComponent(part.slice(at + 1).trim());
132
+ }
133
+ return null;
134
+ }
105
135
  function notFound() {
106
136
  return Response.json({ error: "not_found" }, { status: 404, headers: noStore });
107
137
  }
@@ -114,7 +144,7 @@ function readSiteId(payload) {
114
144
  }
115
145
 
116
146
  // src/version.ts
117
- var PACKAGE_VERSION = "0.3.5";
147
+ var PACKAGE_VERSION = "0.3.7";
118
148
 
119
149
  // src/astro/route.ts
120
150
  var embeddable = { httpOnly: true, secure: true, sameSite: "none", partitioned: true, path: "/" };
@@ -129,6 +159,7 @@ function createSiteplaneRoute(dependencies) {
129
159
  enableDraftMode: async ({ token, maxAgeSeconds }) => {
130
160
  context.cookies.set(PREVIEW_COOKIE, token, { ...embeddable, maxAge: maxAgeSeconds });
131
161
  },
162
+ framedPage: ({ path, token }) => framedPage(context, path, token),
132
163
  env: { VERCEL_GIT_COMMIT_SHA: build.commit ?? void 0, VERCEL_ENV: build.environment ?? void 0 },
133
164
  version: PACKAGE_VERSION,
134
165
  now: dependencies.now,
@@ -141,6 +172,26 @@ function createSiteplaneRoute(dependencies) {
141
172
  pageCache: build.pageCache
142
173
  })
143
174
  });
175
+ async function framedPage(context, path, token) {
176
+ if (!config || typeof context.rewrite !== "function") return null;
177
+ const base = context.url.pathname.replace(/\/api\/siteplane\/draft\/?$/u, "");
178
+ const target = new URL(base + path, context.url.origin);
179
+ const headers = new Headers(context.request.headers);
180
+ headers.set(PREVIEW_HEADER, token);
181
+ headers.delete("cookie");
182
+ try {
183
+ const answer = await context.rewrite(new Request(target, { headers }));
184
+ if (answer.status >= 300 && answer.status < 400) return null;
185
+ return await withFrameScript(answer, {
186
+ path: target.pathname + target.search,
187
+ token,
188
+ editorOrigins: config.editorOrigins,
189
+ direct: true
190
+ });
191
+ } catch {
192
+ return null;
193
+ }
194
+ }
144
195
  return {
145
196
  GET: (context) => {
146
197
  if (config && !build.drafts && DRAFT_ROUTE.test(context.url.pathname) && !context.url.searchParams.has("count")) {
@@ -4102,7 +4102,7 @@ function contentWriteResponseWith(extra) {
4102
4102
  z11.object({
4103
4103
  ...extra,
4104
4104
  status: z11.literal("restore_refused"),
4105
- fields: z11.array(z11.object({ fieldId: fieldIdSchema, person: z11.string().nullable(), publishedAt: isoTime, version, previousVersion: version }))
4105
+ fields: z11.array(z11.object({ fieldId: fieldIdSchema, person: z11.string().nullable(), publishedAt: isoTime, version, previousVersion: version, restoredVersion: version.min(1).exactOptional() }))
4106
4106
  }),
4107
4107
  z11.object({
4108
4108
  ...extra,
@@ -4773,7 +4773,7 @@ function createBookingCliRequestHeaders(config) {
4773
4773
  authorization: `Bearer ${config.accessToken}`,
4774
4774
  "content-type": "application/json"
4775
4775
  };
4776
- const bypassSecret = config.vercelAutomationBypassSecret?.trim();
4776
+ const bypassSecret = config.siteplaneBypassSecret?.trim();
4777
4777
  if (bypassSecret) {
4778
4778
  headers["x-vercel-protection-bypass"] = bypassSecret;
4779
4779
  }
@@ -18211,7 +18211,7 @@ function normalizePagePath(path2) {
18211
18211
  const encoded = encodeURI(decoded);
18212
18212
  return encoded.length > 1 ? encoded.replace(/\/+$/u, "") : encoded;
18213
18213
  }
18214
- async function projectPages(root, stack) {
18214
+ async function projectPages(root, project) {
18215
18215
  const fixed = [];
18216
18216
  const dynamic = [];
18217
18217
  const add = (segments) => {
@@ -18221,7 +18221,7 @@ async function projectPages(root, stack) {
18221
18221
  else
18222
18222
  fixed.push(normalizePagePath(path2));
18223
18223
  };
18224
- if (stack === "astro") {
18224
+ if (project.stack === "astro") {
18225
18225
  const walk2 = async (folder, segments) => {
18226
18226
  for (const name of (await readdir6(folder).catch(() => [])).sort()) {
18227
18227
  const full = join18(folder, name);
@@ -18237,7 +18237,7 @@ async function projectPages(root, stack) {
18237
18237
  }
18238
18238
  }
18239
18239
  };
18240
- await walk2(join18(root, "src", "pages"), []);
18240
+ await walk2(join18(root, project.astroSrcDir ?? "src", "pages"), []);
18241
18241
  } else {
18242
18242
  for (const app of ["app", "src/app"]) {
18243
18243
  const walk2 = async (folder, segments) => {
@@ -18769,7 +18769,7 @@ async function checkUrlCommand(deps, input) {
18769
18769
  const ignore = description.schema?.ignore ?? [];
18770
18770
  const values = Object.fromEntries(Object.entries(content.data.fields).map(([id, field]) => [id, field.value]));
18771
18771
  const confirmed = Boolean(task.data.contentConnectedAt) || hasConnectedSection(agents);
18772
- const pages = await projectPages(deps.root, project.stack);
18772
+ const pages = await projectPages(deps.root, project);
18773
18773
  const crawled = await crawl(fetch2, address, { start: pages.fixed, cookie: cookies.cookie || null, ...page2 ? { only: page2 } : {} });
18774
18774
  const counts2 = crawled.pages.map(({ path: path2, page: read }) => countPage(read, { path: path2, values, fields, ignore }));
18775
18775
  const search = await createSourceSearch(deps.root);
@@ -18802,6 +18802,7 @@ async function checkUrlCommand(deps, input) {
18802
18802
  uncounted(`${page2 ?? "/"} (no page of text/html with status 200)`, page2 ?? "/", "no-page");
18803
18803
  const comparisons = /* @__PURE__ */ new Map();
18804
18804
  const baselineRefused = [];
18805
+ const lostPages = [];
18805
18806
  const next = { ...countFile };
18806
18807
  if (confirmed) {
18807
18808
  delete next.baseline;
@@ -18825,6 +18826,12 @@ async function checkUrlCommand(deps, input) {
18825
18826
  wanted: republished.flatMap((field) => countFile.firstContent?.[field]?.texts ?? [])
18826
18827
  }));
18827
18828
  }
18829
+ if (!page2) {
18830
+ const reached = /* @__PURE__ */ new Set([...crawled.pages.map(({ path: path2 }) => path2), ...crawled.failed.map(({ path: path2 }) => path2), ...crawled.overLimit]);
18831
+ for (const path2 of Object.keys(baseline.pages))
18832
+ if (!reached.has(path2) && !pageRuleFor(path2, ignore))
18833
+ lostPages.push(path2);
18834
+ }
18828
18835
  next.baseline = baseline;
18829
18836
  }
18830
18837
  const units = unitsOf(counts2);
@@ -18896,6 +18903,12 @@ async function checkUrlCommand(deps, input) {
18896
18903
  for (const line of excusedLines(path2, comparison))
18897
18904
  deps.out(line);
18898
18905
  }
18906
+ for (const path2 of lostPages) {
18907
+ red += 1;
18908
+ deps.out(`difference ${path2}: this page is in the baseline, but the count did not reach it today (no route, link or sitemap entry leads to it, or it answers as no page).`);
18909
+ deps.out(` If it is content, bring back its page and a link to it. If the user removed it on purpose, leave it out in siteplane.schema.ts: ignore: [{ path: ${JSON.stringify(path2)}, reason: "owner-wish" }].`);
18910
+ deps.out(` ${ON_PURPOSE}`);
18911
+ }
18899
18912
  const documents = await projectDocuments(deps.root, {
18900
18913
  contentFiles: [...new Set(counts2.flatMap((item) => item.pieces.filter((piece) => piece.status !== "bound").map((piece) => search(piece.text)?.file).filter((file) => Boolean(file))))],
18901
18914
  texts: [...units.textsBound].map((path2) => valueText(values, path2)).filter((text) => Boolean(text))
@@ -18986,7 +18999,7 @@ async function keepBaseline(deps, input) {
18986
18999
  return 0;
18987
19000
  }
18988
19001
  const project = await detectProject(deps.root);
18989
- const pages = input.page ? { fixed: [], dynamic: [] } : await projectPages(deps.root, project.stack);
19002
+ const pages = input.page ? { fixed: [], dynamic: [] } : await projectPages(deps.root, project);
18990
19003
  const crawled = await crawl(input.fetch, input.address, { start: pages.fixed, cookie: null, ...input.page ? { only: input.page } : {} });
18991
19004
  if (crawled.pages.length === 0) {
18992
19005
  deps.out(`Nothing to keep: ${input.address.origin}${input.address.base} answered with no page of text/html.`);
@@ -20640,7 +20653,7 @@ async function requestAgentConnection(input, deps) {
20640
20653
  const headers = {
20641
20654
  "content-type": "application/x-www-form-urlencoded",
20642
20655
  accept: "application/json",
20643
- ...input.vercelAutomationBypassSecret ? { "x-vercel-protection-bypass": input.vercelAutomationBypassSecret } : {}
20656
+ ...input.siteplaneBypassSecret ? { "x-vercel-protection-bypass": input.siteplaneBypassSecret } : {}
20644
20657
  };
20645
20658
  const codeResponse = await deps.fetch(`${apiOrigin2}/api/cli/device/code`, {
20646
20659
  method: "POST",
@@ -20730,7 +20743,7 @@ async function ensureAgentConnection(input, deps) {
20730
20743
  agentName: detectAgentName(input.env),
20731
20744
  machineName: machineName(deps.hostname ?? hostname),
20732
20745
  openBrowser: shouldOpenBrowser(input.env, deps.platform ?? process.platform, input.args ?? []),
20733
- ...input.vercelAutomationBypassSecret ? { vercelAutomationBypassSecret: input.vercelAutomationBypassSecret } : {}
20746
+ ...input.siteplaneBypassSecret ? { siteplaneBypassSecret: input.siteplaneBypassSecret } : {}
20734
20747
  }, deps);
20735
20748
  const connection = { ...grant, purpose: input.purpose };
20736
20749
  const path2 = await deps.connections.save(connection);
@@ -21405,11 +21418,16 @@ async function finishWrite(deps, ctx, result, sent, again, options) {
21405
21418
  }
21406
21419
  case "restore_refused": {
21407
21420
  for (const field of answer.fields) {
21421
+ if (field.restoredVersion !== void 0) {
21422
+ deps.out(`${label(ctx, field.fieldId)} is restored already: version ${field.version} of ${shortDate3(field.publishedAt)} is version ${field.restoredVersion} again. ${field.previousVersion > 0 ? `To go back further, ask the user; then run it again with --version ${field.previousVersion}.` : "There is no earlier version to go back to."}`);
21423
+ continue;
21424
+ }
21408
21425
  const who = field.person ?? "a person whose account no longer exists";
21409
21426
  deps.out(`${label(ctx, field.fieldId)} was last published by ${who} on ${shortDate3(field.publishedAt)} (version ${field.version}). Ask the user before you undo it; then run it again with --version ${field.previousVersion}.`);
21410
21427
  }
21411
21428
  deps.out("Nothing was restored.");
21412
- deps.out(`Next: ask the user, then run npx siteplane content restore ${answer.fields[0]?.fieldId ?? "<field id>"} --version ${answer.fields[0]?.previousVersion ?? "<n>"}.`);
21429
+ const person = answer.fields.find((field) => field.restoredVersion === void 0);
21430
+ deps.out(person ? `Next: ask the user, then run npx siteplane content restore ${person.fieldId} --version ${person.previousVersion}.` : "Next: tell the user what is restored already; go back further only when they ask for it, with --version.");
21413
21431
  return 1;
21414
21432
  }
21415
21433
  case "withdrawn": {
@@ -21559,7 +21577,7 @@ async function contentRestoreCommand(deps, input) {
21559
21577
 
21560
21578
  // src/version.ts
21561
21579
  init_esm_shims();
21562
- var PACKAGE_VERSION = "0.3.5";
21580
+ var PACKAGE_VERSION = "0.3.7";
21563
21581
 
21564
21582
  // src/bin/run-siteplane.ts
21565
21583
  var usage = [
@@ -21855,15 +21873,16 @@ async function withAgentConnection(siteId, args, dependencies, send) {
21855
21873
  apiBaseUrl,
21856
21874
  accessToken: connection.accessToken,
21857
21875
  siteId,
21858
- ...readOptionalVercelAutomationBypassSecret(dependencies.env)
21876
+ ...readSiteplaneBypassSecret(dependencies.env)
21859
21877
  });
21860
21878
  };
21861
21879
  const response = await attempt(false);
21862
21880
  return response.status === 401 ? attempt(true) : response;
21863
21881
  }
21864
- function readOptionalVercelAutomationBypassSecret(env) {
21865
- const secret = env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();
21866
- return secret ? { vercelAutomationBypassSecret: secret } : {};
21882
+ var SITEPLANE_BYPASS_VARIABLE = "SITEPLANE_VERCEL_BYPASS_SECRET";
21883
+ function readSiteplaneBypassSecret(env) {
21884
+ const secret = env[SITEPLANE_BYPASS_VARIABLE]?.trim();
21885
+ return secret ? { siteplaneBypassSecret: secret } : {};
21867
21886
  }
21868
21887
  function agentConnection(input, purpose) {
21869
21888
  const connections = {
@@ -21880,7 +21899,7 @@ function agentConnection(input, purpose) {
21880
21899
  env: input.env,
21881
21900
  args: input.args,
21882
21901
  forceNew,
21883
- ...readOptionalVercelAutomationBypassSecret(input.env)
21902
+ ...readSiteplaneBypassSecret(input.env)
21884
21903
  },
21885
21904
  { ...input.device, connections }
21886
21905
  ),
@@ -21901,7 +21920,7 @@ function processRuntime() {
21901
21920
  }
21902
21921
  function createDefaultDependencies(runtime = processRuntime()) {
21903
21922
  const store = { configDir: runtime.configDir };
21904
- const bypass = runtime.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();
21923
+ const bypass = readSiteplaneBypassSecret(runtime.env).siteplaneBypassSecret;
21905
21924
  const website = agentConnection({ store, env: runtime.env, args: runtime.args, device: runtime.device }, "website");
21906
21925
  const booking = (args) => agentConnection({ store, env: runtime.env, args, device: runtime.device }, "booking");
21907
21926
  const agentDependencies = {
@@ -18,6 +18,147 @@ function runtimeApi(apiOrigin) {
18
18
  return `${apiOrigin.replace(/\/+$/u, "")}/api/runtime/v1`;
19
19
  }
20
20
 
21
+ // src/route/frame-script.ts
22
+ var FRAME_PARAM = "siteplane-frame";
23
+ var PREVIEW_HEADER = "x-siteplane-preview";
24
+ var PAGE_HEADER = "x-siteplane-path";
25
+ var FRAME_SCRIPT = `(()=>{
26
+ const script=document.currentScript,{token,path,direct}=JSON.parse(script.dataset.siteplaneFrame),route=location.pathname,base=route.replace(/\\/api\\/siteplane\\/draft\\/?$/,"");
27
+ script.remove();
28
+ history.replaceState(history.state,"",path+location.hash);
29
+ const below=url=>{const full=url.pathname;return(base&&(full===base||full.startsWith(base+"/"))?full.slice(base.length)||"/":full)+url.search};
30
+ const through=(url,open)=>{const to=new URL(route,location.origin);to.searchParams.set("path",below(url));to.searchParams.set("${FRAME_PARAM}","page");if(open)to.searchParams.set("token",token);return to};
31
+ const plain=href=>{const url=new URL(href,location.origin);url.searchParams.delete("_rsc");return url.pathname+url.search};
32
+ const send=window.fetch;
33
+ window.fetch=async function(input,init){
34
+ const request=input instanceof Request,headers=new Headers((init&&init.headers)||(request?input.headers:undefined));
35
+ let url;try{url=new URL(request?input.url:String(input),document.baseURI)}catch{return send.call(this,input,init)}
36
+ if(url.origin!==location.origin||!(direct||headers.has("rsc")||headers.has("next-action")))return send.call(this,input,init);
37
+ headers.set("${PREVIEW_HEADER}",token);
38
+ if(direct)return send.call(this,input,{...init,headers});
39
+ const answer=await send.call(this,request?new Request(through(url),input):through(url),{...init,headers});
40
+ const page=answer.headers.get("${PAGE_HEADER}")||url.pathname+url.search,at=new URL(page,location.origin);
41
+ const flight=(answer.headers.get("content-type")||"").startsWith("text/x-component");
42
+ Object.defineProperty(answer,"url",{value:(flight?at:through(new URL(plain(page),location.origin),true)).href});
43
+ Object.defineProperty(answer,"redirected",{value:plain(page)!==plain(url.href)});
44
+ return answer};
45
+ addEventListener("click",event=>{
46
+ if(event.defaultPrevented||event.button||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey)return;
47
+ const link=event.target instanceof Element?event.target.closest("a[href]"):null;
48
+ if(!link||(link.target&&link.target!=="_self")||link.hasAttribute("download"))return;
49
+ const url=new URL(link.href);
50
+ if(url.origin!==location.origin||(url.hash&&url.pathname+url.search===location.pathname+location.search))return;
51
+ event.preventDefault();
52
+ location.assign(through(url,true).href)});
53
+ const place="siteplane-scroll:"+path;
54
+ window.siteplaneReload=()=>{try{sessionStorage.setItem(place,String(scrollY))}catch{}location.replace(through(new URL(location.href),true).href)};
55
+ try{const top=sessionStorage.getItem(place);if(top!==null){sessionStorage.removeItem(place);addEventListener("load",()=>scrollTo({top:Number(top),behavior:"instant"}))}}catch{}
56
+ })()`;
57
+
58
+ // src/runtime/frame-ancestors.ts
59
+ var FRAME_ANCESTORS = /^frame-ancestors(?:\s|$)/iu;
60
+ function mergeFrameAncestors(policy, editorOrigins) {
61
+ const policies = (policy ?? "").split(",").map(
62
+ (text) => text.split(";").map((directive) => directive.trim()).filter(Boolean)
63
+ ).filter((directives) => directives.length > 0);
64
+ let extended = false;
65
+ const merged = policies.map((directives) => {
66
+ const index = directives.findIndex((directive) => FRAME_ANCESTORS.test(directive));
67
+ if (index === -1) return directives;
68
+ extended = true;
69
+ const sources = (directives[index] ?? "").split(/\s+/u).slice(1);
70
+ const allowed = sources.some((source) => source.toLowerCase() === "'none'") ? editorOrigins : [...sources, ...editorOrigins.filter((origin) => !sources.includes(origin))];
71
+ return [
72
+ ...directives.slice(0, index),
73
+ `frame-ancestors ${allowed.join(" ") || "'none'"}`,
74
+ // Browsers use the first directive of a name and ignore repeats.
75
+ ...directives.slice(index + 1).filter((directive) => !FRAME_ANCESTORS.test(directive))
76
+ ];
77
+ });
78
+ if (!extended) {
79
+ const own = `frame-ancestors ${["'self'", ...editorOrigins].join(" ")}`;
80
+ const last = merged.at(-1);
81
+ if (last) last.push(own);
82
+ else merged.push([own]);
83
+ }
84
+ return merged.map((directives) => directives.join("; ")).join(", ");
85
+ }
86
+
87
+ // src/runtime/script-policy.ts
88
+ var SCRIPT_DIRECTIVE = /^script-src(?:-elem)?(?:\s|$)/iu;
89
+ var DEFAULT_DIRECTIVE = /^default-src(?:\s|$)/iu;
90
+ function allowScript(policy, hash2) {
91
+ return policy.split(",").map((text) => {
92
+ const directives = text.split(";").map((directive) => directive.trim()).filter(Boolean);
93
+ const scripts = directives.filter((directive) => SCRIPT_DIRECTIVE.test(directive));
94
+ if (scripts.length > 0) {
95
+ return directives.map((directive) => SCRIPT_DIRECTIVE.test(directive) ? withSource(directive, hash2) : directive).join("; ");
96
+ }
97
+ const fallback = directives.find((directive) => DEFAULT_DIRECTIVE.test(directive));
98
+ if (!fallback) return directives.join("; ");
99
+ const own = withSource(fallback.replace(/^default-src/iu, "script-src"), hash2);
100
+ return [...directives, own].join("; ");
101
+ }).filter(Boolean).join(", ");
102
+ }
103
+ function withSource(directive, hash2) {
104
+ const [name = "", ...sources] = directive.split(/\s+/u);
105
+ const inline = sources.some((source) => source.toLowerCase() === "'unsafe-inline'");
106
+ const strict = sources.some((source) => /^'(?:nonce-|sha(?:256|384|512)-|strict-dynamic)/iu.test(source));
107
+ if (inline && !strict || sources.includes(hash2)) return directive;
108
+ return [name, ...sources.filter((source) => source.toLowerCase() !== "'none'"), hash2].join(" ");
109
+ }
110
+
111
+ // src/route/framed-page.ts
112
+ async function withFrameScript(answer, input) {
113
+ const out = new Headers(answer.headers);
114
+ out.set(PAGE_HEADER, input.path);
115
+ out.set("referrer-policy", "same-origin");
116
+ if (!answer.body || !(out.get("content-type") ?? "").includes("text/html")) {
117
+ return withoutCache(new Response(answer.body, { status: answer.status, headers: out }));
118
+ }
119
+ const policy = mergeFrameAncestors(out.get("content-security-policy"), input.editorOrigins);
120
+ out.set("content-security-policy", allowScript(policy, await frameScriptHash()));
121
+ out.delete("content-length");
122
+ const element = frameScriptElement({ token: input.token, path: input.path, ...input.direct ? { direct: true } : {} });
123
+ return withoutCache(new Response(answer.body.pipeThrough(atHeadStart(element)), { status: answer.status, headers: out }));
124
+ }
125
+ var hash;
126
+ function frameScriptHash() {
127
+ return hash ??= crypto.subtle.digest("SHA-256", new TextEncoder().encode(FRAME_SCRIPT)).then((digest) => `'sha256-${btoa(String.fromCharCode(...new Uint8Array(digest)))}'`);
128
+ }
129
+ function frameScriptElement(data) {
130
+ const attribute = JSON.stringify(data).replace(/&/gu, "&amp;").replace(/"/gu, "&quot;").replace(/</gu, "&lt;");
131
+ return `<script data-siteplane-frame="${attribute}">${FRAME_SCRIPT}</script>`;
132
+ }
133
+ function atHeadStart(element) {
134
+ const bytes = new TextDecoder("latin1");
135
+ let held = new Uint8Array(0);
136
+ let done = false;
137
+ return new TransformStream({
138
+ transform(chunk, controller) {
139
+ if (done) return controller.enqueue(chunk);
140
+ const joined = new Uint8Array(held.length + chunk.length);
141
+ joined.set(held);
142
+ joined.set(chunk, held.length);
143
+ held = joined;
144
+ const head = /<head(?:\s[^>]*)?>/iu.exec(bytes.decode(held));
145
+ if (!head) return;
146
+ const end = head.index + head[0].length;
147
+ done = true;
148
+ controller.enqueue(held.slice(0, end));
149
+ controller.enqueue(new TextEncoder().encode(element));
150
+ controller.enqueue(held.slice(end));
151
+ },
152
+ flush(controller) {
153
+ if (!done) controller.enqueue(held);
154
+ }
155
+ });
156
+ }
157
+ function withoutCache(response) {
158
+ response.headers.set("cache-control", "no-store");
159
+ return response;
160
+ }
161
+
21
162
  // ../shared/dist/website-status.js
22
163
  function isRevision(value) {
23
164
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
@@ -478,6 +619,13 @@ var signingKeys = createSigningKeyStore({ fetch: webFetch, now: () => Date.now()
478
619
  export {
479
620
  runtimeValuesUrl,
480
621
  runtimeCdnValuesUrl,
622
+ FRAME_PARAM,
623
+ PREVIEW_HEADER,
624
+ PAGE_HEADER,
625
+ mergeFrameAncestors,
626
+ allowScript,
627
+ withFrameScript,
628
+ frameScriptHash,
481
629
  PREVIEW_COOKIE,
482
630
  verifySitePreviewToken,
483
631
  verifySiteRevalidation,
@@ -0,0 +1,98 @@
1
+ // src/runtime/frame-ancestors.ts
2
+ var FRAME_ANCESTORS = /^frame-ancestors(?:\s|$)/iu;
3
+ function mergeFrameAncestors(policy, editorOrigins) {
4
+ const policies = (policy ?? "").split(",").map(
5
+ (text) => text.split(";").map((directive) => directive.trim()).filter(Boolean)
6
+ ).filter((directives) => directives.length > 0);
7
+ let extended = false;
8
+ const merged = policies.map((directives) => {
9
+ const index = directives.findIndex((directive) => FRAME_ANCESTORS.test(directive));
10
+ if (index === -1) return directives;
11
+ extended = true;
12
+ const sources = (directives[index] ?? "").split(/\s+/u).slice(1);
13
+ const allowed = sources.some((source) => source.toLowerCase() === "'none'") ? editorOrigins : [...sources, ...editorOrigins.filter((origin) => !sources.includes(origin))];
14
+ return [
15
+ ...directives.slice(0, index),
16
+ `frame-ancestors ${allowed.join(" ") || "'none'"}`,
17
+ // Browsers use the first directive of a name and ignore repeats.
18
+ ...directives.slice(index + 1).filter((directive) => !FRAME_ANCESTORS.test(directive))
19
+ ];
20
+ });
21
+ if (!extended) {
22
+ const own = `frame-ancestors ${["'self'", ...editorOrigins].join(" ")}`;
23
+ const last = merged.at(-1);
24
+ if (last) last.push(own);
25
+ else merged.push([own]);
26
+ }
27
+ return merged.map((directives) => directives.join("; ")).join(", ");
28
+ }
29
+
30
+ // src/runtime/script-policy.ts
31
+ var SCRIPT_DIRECTIVE = /^script-src(?:-elem)?(?:\s|$)/iu;
32
+ var DEFAULT_DIRECTIVE = /^default-src(?:\s|$)/iu;
33
+ function allowScript(policy, hash) {
34
+ return policy.split(",").map((text) => {
35
+ const directives = text.split(";").map((directive) => directive.trim()).filter(Boolean);
36
+ const scripts = directives.filter((directive) => SCRIPT_DIRECTIVE.test(directive));
37
+ if (scripts.length > 0) {
38
+ return directives.map((directive) => SCRIPT_DIRECTIVE.test(directive) ? withSource(directive, hash) : directive).join("; ");
39
+ }
40
+ const fallback = directives.find((directive) => DEFAULT_DIRECTIVE.test(directive));
41
+ if (!fallback) return directives.join("; ");
42
+ const own = withSource(fallback.replace(/^default-src/iu, "script-src"), hash);
43
+ return [...directives, own].join("; ");
44
+ }).filter(Boolean).join(", ");
45
+ }
46
+ function withSource(directive, hash) {
47
+ const [name = "", ...sources] = directive.split(/\s+/u);
48
+ const inline = sources.some((source) => source.toLowerCase() === "'unsafe-inline'");
49
+ const strict = sources.some((source) => /^'(?:nonce-|sha(?:256|384|512)-|strict-dynamic)/iu.test(source));
50
+ if (inline && !strict || sources.includes(hash)) return directive;
51
+ return [name, ...sources.filter((source) => source.toLowerCase() !== "'none'"), hash].join(" ");
52
+ }
53
+
54
+ // src/route/frame-script.ts
55
+ var FRAME_PARAM = "siteplane-frame";
56
+ var PREVIEW_HEADER = "x-siteplane-preview";
57
+ var PAGE_HEADER = "x-siteplane-path";
58
+ var FRAME_SCRIPT = `(()=>{
59
+ const script=document.currentScript,{token,path,direct}=JSON.parse(script.dataset.siteplaneFrame),route=location.pathname,base=route.replace(/\\/api\\/siteplane\\/draft\\/?$/,"");
60
+ script.remove();
61
+ history.replaceState(history.state,"",path+location.hash);
62
+ const below=url=>{const full=url.pathname;return(base&&(full===base||full.startsWith(base+"/"))?full.slice(base.length)||"/":full)+url.search};
63
+ const through=(url,open)=>{const to=new URL(route,location.origin);to.searchParams.set("path",below(url));to.searchParams.set("${FRAME_PARAM}","page");if(open)to.searchParams.set("token",token);return to};
64
+ const plain=href=>{const url=new URL(href,location.origin);url.searchParams.delete("_rsc");return url.pathname+url.search};
65
+ const send=window.fetch;
66
+ window.fetch=async function(input,init){
67
+ const request=input instanceof Request,headers=new Headers((init&&init.headers)||(request?input.headers:undefined));
68
+ let url;try{url=new URL(request?input.url:String(input),document.baseURI)}catch{return send.call(this,input,init)}
69
+ if(url.origin!==location.origin||!(direct||headers.has("rsc")||headers.has("next-action")))return send.call(this,input,init);
70
+ headers.set("${PREVIEW_HEADER}",token);
71
+ if(direct)return send.call(this,input,{...init,headers});
72
+ const answer=await send.call(this,request?new Request(through(url),input):through(url),{...init,headers});
73
+ const page=answer.headers.get("${PAGE_HEADER}")||url.pathname+url.search,at=new URL(page,location.origin);
74
+ const flight=(answer.headers.get("content-type")||"").startsWith("text/x-component");
75
+ Object.defineProperty(answer,"url",{value:(flight?at:through(new URL(plain(page),location.origin),true)).href});
76
+ Object.defineProperty(answer,"redirected",{value:plain(page)!==plain(url.href)});
77
+ return answer};
78
+ addEventListener("click",event=>{
79
+ if(event.defaultPrevented||event.button||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey)return;
80
+ const link=event.target instanceof Element?event.target.closest("a[href]"):null;
81
+ if(!link||(link.target&&link.target!=="_self")||link.hasAttribute("download"))return;
82
+ const url=new URL(link.href);
83
+ if(url.origin!==location.origin||(url.hash&&url.pathname+url.search===location.pathname+location.search))return;
84
+ event.preventDefault();
85
+ location.assign(through(url,true).href)});
86
+ const place="siteplane-scroll:"+path;
87
+ window.siteplaneReload=()=>{try{sessionStorage.setItem(place,String(scrollY))}catch{}location.replace(through(new URL(location.href),true).href)};
88
+ try{const top=sessionStorage.getItem(place);if(top!==null){sessionStorage.removeItem(place);addEventListener("load",()=>scrollTo({top:Number(top),behavior:"instant"}))}}catch{}
89
+ })()`;
90
+
91
+ export {
92
+ mergeFrameAncestors,
93
+ allowScript,
94
+ FRAME_PARAM,
95
+ PREVIEW_HEADER,
96
+ PAGE_HEADER,
97
+ FRAME_SCRIPT
98
+ };
@@ -102,7 +102,8 @@ function startPreviewBridge(input) {
102
102
  void import("siteplane/internal/bridge").then(
103
103
  ({ startBridge }) => startBridge({
104
104
  editorOrigin: input.editorOrigin,
105
- refresh: () => window.location.reload(),
105
+ // Doc 79: a page without cookies comes again through the draft route (route/frame-script.ts).
106
+ refresh: () => (window.siteplaneReload ?? (() => window.location.reload()))(),
106
107
  path: () => pathBelow(window.location.pathname, base)
107
108
  })
108
109
  );
package/dist/next.cjs CHANGED
@@ -52,6 +52,43 @@ function isWebOrigin(value) {
52
52
  }
53
53
  }
54
54
 
55
+ // src/route/frame-script.ts
56
+ var FRAME_PARAM = "siteplane-frame";
57
+ var PREVIEW_HEADER = "x-siteplane-preview";
58
+ var PAGE_HEADER = "x-siteplane-path";
59
+ var FRAME_SCRIPT = `(()=>{
60
+ const script=document.currentScript,{token,path,direct}=JSON.parse(script.dataset.siteplaneFrame),route=location.pathname,base=route.replace(/\\/api\\/siteplane\\/draft\\/?$/,"");
61
+ script.remove();
62
+ history.replaceState(history.state,"",path+location.hash);
63
+ const below=url=>{const full=url.pathname;return(base&&(full===base||full.startsWith(base+"/"))?full.slice(base.length)||"/":full)+url.search};
64
+ const through=(url,open)=>{const to=new URL(route,location.origin);to.searchParams.set("path",below(url));to.searchParams.set("${FRAME_PARAM}","page");if(open)to.searchParams.set("token",token);return to};
65
+ const plain=href=>{const url=new URL(href,location.origin);url.searchParams.delete("_rsc");return url.pathname+url.search};
66
+ const send=window.fetch;
67
+ window.fetch=async function(input,init){
68
+ const request=input instanceof Request,headers=new Headers((init&&init.headers)||(request?input.headers:undefined));
69
+ let url;try{url=new URL(request?input.url:String(input),document.baseURI)}catch{return send.call(this,input,init)}
70
+ if(url.origin!==location.origin||!(direct||headers.has("rsc")||headers.has("next-action")))return send.call(this,input,init);
71
+ headers.set("${PREVIEW_HEADER}",token);
72
+ if(direct)return send.call(this,input,{...init,headers});
73
+ const answer=await send.call(this,request?new Request(through(url),input):through(url),{...init,headers});
74
+ const page=answer.headers.get("${PAGE_HEADER}")||url.pathname+url.search,at=new URL(page,location.origin);
75
+ const flight=(answer.headers.get("content-type")||"").startsWith("text/x-component");
76
+ Object.defineProperty(answer,"url",{value:(flight?at:through(new URL(plain(page),location.origin),true)).href});
77
+ Object.defineProperty(answer,"redirected",{value:plain(page)!==plain(url.href)});
78
+ return answer};
79
+ addEventListener("click",event=>{
80
+ if(event.defaultPrevented||event.button||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey)return;
81
+ const link=event.target instanceof Element?event.target.closest("a[href]"):null;
82
+ if(!link||(link.target&&link.target!=="_self")||link.hasAttribute("download"))return;
83
+ const url=new URL(link.href);
84
+ if(url.origin!==location.origin||(url.hash&&url.pathname+url.search===location.pathname+location.search))return;
85
+ event.preventDefault();
86
+ location.assign(through(url,true).href)});
87
+ const place="siteplane-scroll:"+path;
88
+ window.siteplaneReload=()=>{try{sessionStorage.setItem(place,String(scrollY))}catch{}location.replace(through(new URL(location.href),true).href)};
89
+ try{const top=sessionStorage.getItem(place);if(top!==null){sessionStorage.removeItem(place);addEventListener("load",()=>scrollTo({top:Number(top),behavior:"instant"}))}}catch{}
90
+ })()`;
91
+
55
92
  // src/runtime/frame-ancestors.ts
56
93
  var FRAME_ANCESTORS = /^frame-ancestors(?:\s|$)/iu;
57
94
  function mergeFrameAncestors(policy, editorOrigins) {
@@ -81,7 +118,32 @@ function mergeFrameAncestors(policy, editorOrigins) {
81
118
  return merged.map((directives) => directives.join("; ")).join(", ");
82
119
  }
83
120
 
121
+ // src/runtime/script-policy.ts
122
+ var SCRIPT_DIRECTIVE = /^script-src(?:-elem)?(?:\s|$)/iu;
123
+ var DEFAULT_DIRECTIVE = /^default-src(?:\s|$)/iu;
124
+ function allowScript(policy, hash) {
125
+ return policy.split(",").map((text) => {
126
+ const directives = text.split(";").map((directive) => directive.trim()).filter(Boolean);
127
+ const scripts = directives.filter((directive) => SCRIPT_DIRECTIVE.test(directive));
128
+ if (scripts.length > 0) {
129
+ return directives.map((directive) => SCRIPT_DIRECTIVE.test(directive) ? withSource(directive, hash) : directive).join("; ");
130
+ }
131
+ const fallback = directives.find((directive) => DEFAULT_DIRECTIVE.test(directive));
132
+ if (!fallback) return directives.join("; ");
133
+ const own = withSource(fallback.replace(/^default-src/iu, "script-src"), hash);
134
+ return [...directives, own].join("; ");
135
+ }).filter(Boolean).join(", ");
136
+ }
137
+ function withSource(directive, hash) {
138
+ const [name = "", ...sources] = directive.split(/\s+/u);
139
+ const inline = sources.some((source) => source.toLowerCase() === "'unsafe-inline'");
140
+ const strict = sources.some((source) => /^'(?:nonce-|sha(?:256|384|512)-|strict-dynamic)/iu.test(source));
141
+ if (inline && !strict || sources.includes(hash)) return directive;
142
+ return [name, ...sources.filter((source) => source.toLowerCase() !== "'none'"), hash].join(" ");
143
+ }
144
+
84
145
  // src/next.ts
146
+ var FRAME_QUERY = { type: "query", key: FRAME_PARAM };
85
147
  var DRAFT_MODE_COOKIE = { type: "cookie", key: "__prerender_bypass" };
86
148
  var siteIdPattern2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
87
149
  var SCHEMA_FILE = "siteplane.schema.ts";
@@ -120,7 +182,12 @@ function withEditor(config, project, options) {
120
182
  );
121
183
  }
122
184
  const next = { ...config, ...moduleAlias(config, options.projectDir, schema !== null) };
123
- if (options.phase === BUILD_PHASE) next.env = { ...config.env, SITEPLANE_BUILD_STAMP: `siteplane-mark-${(0, import_node_crypto.randomUUID)()}` };
185
+ const basePath = typeof config.basePath === "string" ? config.basePath : "";
186
+ next.env = {
187
+ ...config.env,
188
+ ...basePath ? { SITEPLANE_BASE_PATH: basePath } : {},
189
+ ...options.phase === BUILD_PHASE ? { SITEPLANE_BUILD_STAMP: `siteplane-mark-${(0, import_node_crypto.randomUUID)()}` } : {}
190
+ };
124
191
  next.webpack = (webpackConfig, context) => {
125
192
  webpackConfig.resolve ??= {};
126
193
  const server = context?.isServer === true;
@@ -150,7 +217,11 @@ function withEditor(config, project, options) {
150
217
  if (websiteHeaders) {
151
218
  next.headers = async () => {
152
219
  const rules = await websiteHeaders();
153
- return [...rules, ...draftFrameRules(rules, project.editorOrigins)];
220
+ return [
221
+ ...rules,
222
+ ...draftFrameRules(rules, project.editorOrigins),
223
+ ...draftFrameRules(rules, project.editorOrigins, "frame")
224
+ ];
154
225
  };
155
226
  }
156
227
  if (options.admin) {
@@ -186,25 +257,28 @@ function usesExperimentalTurbo(projectDir) {
186
257
  return false;
187
258
  }
188
259
  }
189
- function draftFrameRules(rules, editorOrigins) {
260
+ function draftFrameRules(rules, editorOrigins, of = "cookie") {
261
+ const condition = of === "cookie" ? DRAFT_MODE_COOKIE : FRAME_QUERY;
190
262
  const isCsp = (key) => key.toLowerCase() === "content-security-policy";
191
263
  const isXfo = (key) => key.toLowerCase() === "x-frame-options";
264
+ const script = `'sha256-${(0, import_node_crypto.createHash)("sha256").update(FRAME_SCRIPT).digest("base64")}'`;
265
+ const allow = (policy) => of === "frame" ? allowScript(policy, script) : policy;
192
266
  const hasFrameOptions = rules.some((rule) => rule.headers.some((header) => isXfo(header.key)));
193
267
  const draftRule = (rule, headers) => ({
194
268
  ...rule,
195
- has: [...rule.has ?? [], DRAFT_MODE_COOKIE],
269
+ has: [...rule.has ?? [], condition],
196
270
  headers
197
271
  });
198
272
  const optionsOnly = rules.filter((rule) => rule.headers.some((header) => isXfo(header.key)) && !rule.headers.some((header) => isCsp(header.key))).map(
199
273
  (rule) => draftRule(rule, [...rule.headers, { key: "Content-Security-Policy", value: mergeFrameAncestors(null, editorOrigins) }])
200
274
  );
201
275
  const policies = rules.filter(
202
- (rule) => rule.headers.some((header) => isCsp(header.key) && (hasFrameOptions || /frame-ancestors/iu.test(header.value)))
276
+ (rule) => rule.headers.some((header) => isCsp(header.key) && (of === "frame" || hasFrameOptions || /frame-ancestors/iu.test(header.value)))
203
277
  ).map(
204
278
  (rule) => draftRule(
205
279
  rule,
206
280
  rule.headers.map(
207
- (header) => isCsp(header.key) ? { ...header, value: mergeFrameAncestors(header.value, editorOrigins) } : header
281
+ (header) => isCsp(header.key) ? { ...header, value: allow(mergeFrameAncestors(header.value, editorOrigins)) } : header
208
282
  )
209
283
  )
210
284
  );
package/dist/next.js CHANGED
@@ -1,45 +1,21 @@
1
+ import {
2
+ FRAME_PARAM,
3
+ FRAME_SCRIPT,
4
+ allowScript,
5
+ mergeFrameAncestors
6
+ } from "./chunk-UC6YGNU6.js";
1
7
  import {
2
8
  SITEPLANE_CONFIG_FILE,
3
9
  readSiteplaneConfig
4
10
  } from "./chunk-KZ3AQ6OA.js";
5
11
 
6
12
  // src/next.ts
7
- import { randomUUID } from "crypto";
13
+ import { createHash, randomUUID } from "crypto";
8
14
  import { existsSync, readFileSync } from "fs";
9
15
  import { access } from "fs/promises";
10
16
  import { createRequire } from "module";
11
17
  import { join } from "path";
12
-
13
- // src/runtime/frame-ancestors.ts
14
- var FRAME_ANCESTORS = /^frame-ancestors(?:\s|$)/iu;
15
- function mergeFrameAncestors(policy, editorOrigins) {
16
- const policies = (policy ?? "").split(",").map(
17
- (text) => text.split(";").map((directive) => directive.trim()).filter(Boolean)
18
- ).filter((directives) => directives.length > 0);
19
- let extended = false;
20
- const merged = policies.map((directives) => {
21
- const index = directives.findIndex((directive) => FRAME_ANCESTORS.test(directive));
22
- if (index === -1) return directives;
23
- extended = true;
24
- const sources = (directives[index] ?? "").split(/\s+/u).slice(1);
25
- const allowed = sources.some((source) => source.toLowerCase() === "'none'") ? editorOrigins : [...sources, ...editorOrigins.filter((origin) => !sources.includes(origin))];
26
- return [
27
- ...directives.slice(0, index),
28
- `frame-ancestors ${allowed.join(" ") || "'none'"}`,
29
- // Browsers use the first directive of a name and ignore repeats.
30
- ...directives.slice(index + 1).filter((directive) => !FRAME_ANCESTORS.test(directive))
31
- ];
32
- });
33
- if (!extended) {
34
- const own = `frame-ancestors ${["'self'", ...editorOrigins].join(" ")}`;
35
- const last = merged.at(-1);
36
- if (last) last.push(own);
37
- else merged.push([own]);
38
- }
39
- return merged.map((directives) => directives.join("; ")).join(", ");
40
- }
41
-
42
- // src/next.ts
18
+ var FRAME_QUERY = { type: "query", key: FRAME_PARAM };
43
19
  var DRAFT_MODE_COOKIE = { type: "cookie", key: "__prerender_bypass" };
44
20
  var siteIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
45
21
  var SCHEMA_FILE = "siteplane.schema.ts";
@@ -78,7 +54,12 @@ function withEditor(config, project, options) {
78
54
  );
79
55
  }
80
56
  const next = { ...config, ...moduleAlias(config, options.projectDir, schema !== null) };
81
- if (options.phase === BUILD_PHASE) next.env = { ...config.env, SITEPLANE_BUILD_STAMP: `siteplane-mark-${randomUUID()}` };
57
+ const basePath = typeof config.basePath === "string" ? config.basePath : "";
58
+ next.env = {
59
+ ...config.env,
60
+ ...basePath ? { SITEPLANE_BASE_PATH: basePath } : {},
61
+ ...options.phase === BUILD_PHASE ? { SITEPLANE_BUILD_STAMP: `siteplane-mark-${randomUUID()}` } : {}
62
+ };
82
63
  next.webpack = (webpackConfig, context) => {
83
64
  webpackConfig.resolve ??= {};
84
65
  const server = context?.isServer === true;
@@ -108,7 +89,11 @@ function withEditor(config, project, options) {
108
89
  if (websiteHeaders) {
109
90
  next.headers = async () => {
110
91
  const rules = await websiteHeaders();
111
- return [...rules, ...draftFrameRules(rules, project.editorOrigins)];
92
+ return [
93
+ ...rules,
94
+ ...draftFrameRules(rules, project.editorOrigins),
95
+ ...draftFrameRules(rules, project.editorOrigins, "frame")
96
+ ];
112
97
  };
113
98
  }
114
99
  if (options.admin) {
@@ -144,25 +129,28 @@ function usesExperimentalTurbo(projectDir) {
144
129
  return false;
145
130
  }
146
131
  }
147
- function draftFrameRules(rules, editorOrigins) {
132
+ function draftFrameRules(rules, editorOrigins, of = "cookie") {
133
+ const condition = of === "cookie" ? DRAFT_MODE_COOKIE : FRAME_QUERY;
148
134
  const isCsp = (key) => key.toLowerCase() === "content-security-policy";
149
135
  const isXfo = (key) => key.toLowerCase() === "x-frame-options";
136
+ const script = `'sha256-${createHash("sha256").update(FRAME_SCRIPT).digest("base64")}'`;
137
+ const allow = (policy) => of === "frame" ? allowScript(policy, script) : policy;
150
138
  const hasFrameOptions = rules.some((rule) => rule.headers.some((header) => isXfo(header.key)));
151
139
  const draftRule = (rule, headers) => ({
152
140
  ...rule,
153
- has: [...rule.has ?? [], DRAFT_MODE_COOKIE],
141
+ has: [...rule.has ?? [], condition],
154
142
  headers
155
143
  });
156
144
  const optionsOnly = rules.filter((rule) => rule.headers.some((header) => isXfo(header.key)) && !rule.headers.some((header) => isCsp(header.key))).map(
157
145
  (rule) => draftRule(rule, [...rule.headers, { key: "Content-Security-Policy", value: mergeFrameAncestors(null, editorOrigins) }])
158
146
  );
159
147
  const policies = rules.filter(
160
- (rule) => rule.headers.some((header) => isCsp(header.key) && (hasFrameOptions || /frame-ancestors/iu.test(header.value)))
148
+ (rule) => rule.headers.some((header) => isCsp(header.key) && (of === "frame" || hasFrameOptions || /frame-ancestors/iu.test(header.value)))
161
149
  ).map(
162
150
  (rule) => draftRule(
163
151
  rule,
164
152
  rule.headers.map(
165
- (header) => isCsp(header.key) ? { ...header, value: mergeFrameAncestors(header.value, editorOrigins) } : header
153
+ (header) => isCsp(header.key) ? { ...header, value: allow(mergeFrameAncestors(header.value, editorOrigins)) } : header
166
154
  )
167
155
  )
168
156
  );
package/dist/route.d.ts CHANGED
@@ -6,7 +6,8 @@
6
6
  * ```
7
7
  *
8
8
  * GET serves `draft` (Draft Mode for the editor, and on the dev server the
9
- * count request of the CLI) and `status`, POST `revalidate`.
9
+ * count request of the CLI) and `status`, POST `revalidate` and the Server
10
+ * Actions of a preview without cookies (doc 79).
10
11
  */
11
12
  declare const GET: (request: Request) => Promise<Response>;
12
13
  declare const POST: (request: Request) => Promise<Response>;
package/dist/route.js CHANGED
@@ -7,12 +7,155 @@ import {
7
7
  verifySitePreviewToken,
8
8
  verifySiteRevalidation
9
9
  } from "./chunk-IOFM5PE3.js";
10
+ import {
11
+ FRAME_PARAM,
12
+ FRAME_SCRIPT,
13
+ PAGE_HEADER,
14
+ PREVIEW_HEADER,
15
+ allowScript,
16
+ mergeFrameAncestors
17
+ } from "./chunk-UC6YGNU6.js";
10
18
  import "./chunk-KZ3AQ6OA.js";
11
19
 
12
20
  // src/route.ts
13
21
  import { revalidateTag } from "next/cache";
14
22
  import { cookies, draftMode } from "next/headers";
15
23
 
24
+ // src/route/framed-page.ts
25
+ var FORWARDED = [
26
+ "accept",
27
+ "accept-language",
28
+ "content-type",
29
+ "next-action",
30
+ "next-router-prefetch",
31
+ "next-router-segment-prefetch",
32
+ "next-router-state-tree",
33
+ "next-url",
34
+ "origin",
35
+ "rsc",
36
+ "user-agent"
37
+ ];
38
+ var KEPT_BACK = /* @__PURE__ */ new Set([
39
+ "age",
40
+ "cache-control",
41
+ "connection",
42
+ "content-encoding",
43
+ "content-length",
44
+ "date",
45
+ "etag",
46
+ "keep-alive",
47
+ "set-cookie",
48
+ "transfer-encoding"
49
+ ]);
50
+ async function framedPage(input) {
51
+ const { request } = input;
52
+ let { target } = input;
53
+ const headers = new Headers({ cookie: Object.entries(input.cookies).map(([name, value]) => `${name}=${value}`).join("; ") });
54
+ for (const name of FORWARDED) {
55
+ const value = request.headers.get(name);
56
+ if (value !== null) headers.set(name, value);
57
+ }
58
+ let answer;
59
+ try {
60
+ for (const [name, value] of Object.entries(input.headers ?? {})) headers.set(name, value);
61
+ const body = request.method === "POST" ? await request.arrayBuffer() : void 0;
62
+ const ask = () => input.fetch(target, { method: request.method, headers, ...body ? { body } : {}, redirect: "manual", cache: "no-store" });
63
+ answer = await ask();
64
+ const spelled = redirectOf(answer, target, request);
65
+ if (spelled && sameButSlash(spelled, target)) {
66
+ target = spelled;
67
+ answer = await ask();
68
+ }
69
+ } catch {
70
+ return null;
71
+ }
72
+ if (answer.status === 401 || answer.status === 403 || answer.status === 429 || answer.status >= 502) return null;
73
+ const next = redirectOf(answer, target, request);
74
+ if (next) {
75
+ if (next.origin !== target.origin) return withoutCache(new Response(null, { status: 307, headers: { location: next.href } }));
76
+ const back = new URL(request.url);
77
+ back.searchParams.set("path", belowBase(next, input.target, back.searchParams.get("path") ?? "/"));
78
+ back.searchParams.set(FRAME_PARAM, "page");
79
+ return withoutCache(new Response(null, { status: 307, headers: { location: back.search } }));
80
+ }
81
+ const out = new Headers();
82
+ answer.headers.forEach((value, name) => {
83
+ if (!KEPT_BACK.has(name)) out.set(name, value);
84
+ });
85
+ return withFrameScript(new Response(answer.body, { status: answer.status, headers: out }), {
86
+ path: target.pathname + target.search,
87
+ token: input.token,
88
+ editorOrigins: input.editorOrigins
89
+ });
90
+ }
91
+ async function withFrameScript(answer, input) {
92
+ const out = new Headers(answer.headers);
93
+ out.set(PAGE_HEADER, input.path);
94
+ out.set("referrer-policy", "same-origin");
95
+ if (!answer.body || !(out.get("content-type") ?? "").includes("text/html")) {
96
+ return withoutCache(new Response(answer.body, { status: answer.status, headers: out }));
97
+ }
98
+ const policy = mergeFrameAncestors(out.get("content-security-policy"), input.editorOrigins);
99
+ out.set("content-security-policy", allowScript(policy, await frameScriptHash()));
100
+ out.delete("content-length");
101
+ const element = frameScriptElement({ token: input.token, path: input.path, ...input.direct ? { direct: true } : {} });
102
+ return withoutCache(new Response(answer.body.pipeThrough(atHeadStart(element)), { status: answer.status, headers: out }));
103
+ }
104
+ var hash;
105
+ function frameScriptHash() {
106
+ return hash ??= crypto.subtle.digest("SHA-256", new TextEncoder().encode(FRAME_SCRIPT)).then((digest) => `'sha256-${btoa(String.fromCharCode(...new Uint8Array(digest)))}'`);
107
+ }
108
+ function frameScriptElement(data) {
109
+ const attribute = JSON.stringify(data).replace(/&/gu, "&amp;").replace(/"/gu, "&quot;").replace(/</gu, "&lt;");
110
+ return `<script data-siteplane-frame="${attribute}">${FRAME_SCRIPT}</script>`;
111
+ }
112
+ function atHeadStart(element) {
113
+ const bytes = new TextDecoder("latin1");
114
+ let held = new Uint8Array(0);
115
+ let done = false;
116
+ return new TransformStream({
117
+ transform(chunk, controller) {
118
+ if (done) return controller.enqueue(chunk);
119
+ const joined = new Uint8Array(held.length + chunk.length);
120
+ joined.set(held);
121
+ joined.set(chunk, held.length);
122
+ held = joined;
123
+ const head = /<head(?:\s[^>]*)?>/iu.exec(bytes.decode(held));
124
+ if (!head) return;
125
+ const end = head.index + head[0].length;
126
+ done = true;
127
+ controller.enqueue(held.slice(0, end));
128
+ controller.enqueue(new TextEncoder().encode(element));
129
+ controller.enqueue(held.slice(end));
130
+ },
131
+ flush(controller) {
132
+ if (!done) controller.enqueue(held);
133
+ }
134
+ });
135
+ }
136
+ function redirectOf(answer, from, request) {
137
+ const location = answer.headers.get("location");
138
+ if (!location || answer.status < 300 || answer.status >= 400 || answer.status === 304) return null;
139
+ const next = new URL(location, from);
140
+ const own = [request.headers.get("x-forwarded-host"), request.headers.get("host"), new URL(request.url).host];
141
+ return own.includes(next.host) ? new URL(next.pathname + next.search, from.origin) : next;
142
+ }
143
+ function sameButSlash(first, second) {
144
+ const bare = (url) => url.pathname.replace(/\/+$/u, "") + url.search;
145
+ return first.origin === second.origin && bare(first) === bare(second);
146
+ }
147
+ function belowBase(next, target, path) {
148
+ const own = new URL(path, target.origin).pathname;
149
+ const base = own !== "/" && target.pathname.endsWith(own) ? target.pathname.slice(0, -own.length) : own === "/" ? target.pathname.replace(/\/$/u, "") : "";
150
+ const full = next.pathname;
151
+ const below = base && (full === base || full.startsWith(`${base}/`)) ? full.slice(base.length) || "/" : full;
152
+ return below + next.search;
153
+ }
154
+ function withoutCache(response) {
155
+ response.headers.set("cache-control", "no-store");
156
+ return response;
157
+ }
158
+
16
159
  // ../shared/dist/safe-redirect.js
17
160
  var UNSAFE_URL_CHARACTERS = /[\\\u0000-\u001f\u007f]/u;
18
161
  var MAX_REDIRECT_PATH_LENGTH = 2048;
@@ -45,6 +188,7 @@ function createRouteHandlers(dependencies) {
45
188
  }
46
189
  async function POST2(request) {
47
190
  const config = dependencies.config();
191
+ if (config && routeName(request) === "draft" && request.headers.has(PREVIEW_HEADER)) return draft(request, config);
48
192
  if (!config || routeName(request) !== "revalidate") return notFound();
49
193
  return revalidate(request, config);
50
194
  }
@@ -78,10 +222,26 @@ function createRouteHandlers(dependencies) {
78
222
  return redirect(url, path, await dependencies.enableCount?.() ?? {});
79
223
  }
80
224
  const now = dependencies.now();
81
- const token = query.get("token") ?? "";
225
+ const carried = request.headers.get(PREVIEW_HEADER);
226
+ const token = carried ?? query.get("token") ?? "";
82
227
  const claims = token ? await verifySitePreviewToken(config, token, dependencies.keys, now) : null;
83
228
  if (!claims) return Response.json({ error: "preview_token_invalid" }, { status: 401, headers: noStore });
229
+ if (carried !== null) {
230
+ const page = ownRoute(path) ? null : await dependencies.framedPage?.({ request, path, token });
231
+ return page ?? Response.json({ error: "preview_page_unavailable" }, { status: 502, headers: noStore });
232
+ }
84
233
  await dependencies.enableDraftMode({ token, maxAgeSeconds: claims.exp - Math.floor(now.getTime() / 1e3) });
234
+ if (dependencies.framedPage && (query.has(FRAME_PARAM) || request.headers.get("sec-fetch-dest") === "iframe")) {
235
+ const step = query.get(FRAME_PARAM);
236
+ if (step !== "check" && step !== "page") {
237
+ query.set(FRAME_PARAM, "check");
238
+ return new Response(null, { status: 307, headers: { ...noStore, Location: `?${query}` } });
239
+ }
240
+ if (cookieOf(request, PREVIEW_COOKIE) !== token && !ownRoute(path)) {
241
+ const page = await dependencies.framedPage({ request, path, token });
242
+ if (page) return page;
243
+ }
244
+ }
85
245
  return redirect(url, path);
86
246
  }
87
247
  function redirect(url, path, headers = {}) {
@@ -106,6 +266,16 @@ function createRouteHandlers(dependencies) {
106
266
  function routeName(request) {
107
267
  return /\/api\/siteplane\/([a-z]+)\/?$/u.exec(new URL(request.url).pathname)?.[1] ?? null;
108
268
  }
269
+ function ownRoute(path) {
270
+ return /(?:^|\/)api\/siteplane(?:\/|$)/u.test(new URL(path, "https://website.invalid").pathname);
271
+ }
272
+ function cookieOf(request, name) {
273
+ for (const part of (request.headers.get("cookie") ?? "").split(";")) {
274
+ const at = part.indexOf("=");
275
+ if (at > 0 && part.slice(0, at).trim() === name) return decodeURIComponent(part.slice(at + 1).trim());
276
+ }
277
+ return null;
278
+ }
109
279
  function notFound() {
110
280
  return Response.json({ error: "not_found" }, { status: 404, headers: noStore });
111
281
  }
@@ -118,7 +288,7 @@ function readSiteId(payload) {
118
288
  }
119
289
 
120
290
  // src/version.ts
121
- var PACKAGE_VERSION = "0.3.5";
291
+ var PACKAGE_VERSION = "0.3.7";
122
292
 
123
293
  // src/route.ts
124
294
  var embeddable = { httpOnly: true, secure: true, sameSite: "none", partitioned: true, path: "/" };
@@ -136,6 +306,24 @@ var handlers = createRouteHandlers({
136
306
  if (bypass) store.set({ ...embeddable, name: "__prerender_bypass", value: bypass.value });
137
307
  store.set({ ...embeddable, name: PREVIEW_COOKIE, value: token, maxAge: maxAgeSeconds });
138
308
  },
309
+ framedPage: async ({ request, path, token }) => {
310
+ (await draftMode()).enable();
311
+ const bypass = (await cookies()).get("__prerender_bypass")?.value;
312
+ if (!siteConfig || !bypass) return null;
313
+ const url = new URL(request.url);
314
+ const own = process.env.__NEXT_PRIVATE_ORIGIN;
315
+ const host = request.headers.get("x-forwarded-host") ?? request.headers.get("host");
316
+ return framedPage({
317
+ request,
318
+ // `withSiteplane` compiles the base path in; a route handler does not know it.
319
+ target: new URL((process.env.SITEPLANE_BASE_PATH ?? "") + path, own ?? url.origin),
320
+ token,
321
+ cookies: { __prerender_bypass: bypass, [PREVIEW_COOKIE]: token },
322
+ ...own && host ? { headers: { "x-forwarded-host": host, "x-forwarded-proto": request.headers.get("x-forwarded-proto") ?? url.protocol.slice(0, -1) } } : {},
323
+ editorOrigins: siteConfig.editorOrigins,
324
+ fetch: (input, init) => fetch(input, init)
325
+ });
326
+ },
139
327
  env: process.env,
140
328
  version: PACKAGE_VERSION,
141
329
  now: () => /* @__PURE__ */ new Date(),
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "siteplane",
3
3
  "private": false,
4
- "version": "0.3.5",
4
+ "version": "0.3.7",
5
5
  "description": "Siteplane for Next.js and Astro websites: content from Siteplane, Draft Mode preview, Booking and the siteplane CLI.",
6
6
  "type": "module",
7
7
  "license": "SEE LICENSE IN LICENSE",
@@ -78,7 +78,7 @@
78
78
  "@vercel/stega": "1.1.0",
79
79
  "jiti": "2.7.0",
80
80
  "typescript": "6.0.3",
81
- "zod": "4.4.3"
81
+ "zod": "4.6.7"
82
82
  },
83
83
  "peerDependencies": {
84
84
  "astro": ">=5 <8",