sitecms-next 0.6.0 → 0.7.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.
- package/CHANGELOG.md +53 -0
- package/README.md +84 -7
- package/dist/analytics-client.d.ts +4 -14
- package/dist/analytics-client.d.ts.map +1 -1
- package/dist/analytics-client.js +9 -52
- package/dist/analytics-client.js.map +1 -1
- package/dist/analytics.d.ts +4 -11
- package/dist/analytics.d.ts.map +1 -1
- package/dist/analytics.js +5 -133
- package/dist/analytics.js.map +1 -1
- package/dist/cli-helpers.d.ts +3 -67
- package/dist/cli-helpers.d.ts.map +1 -1
- package/dist/cli-helpers.js +9 -370
- package/dist/cli-helpers.js.map +1 -1
- package/dist/cli.js +95 -727
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +45 -345
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +52 -460
- package/dist/index.js.map +1 -1
- package/dist/preview-client.d.ts.map +1 -1
- package/dist/preview-client.js +15 -291
- package/dist/preview-client.js.map +1 -1
- package/dist/preview.d.ts +3 -67
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +21 -186
- package/dist/preview.js.map +1 -1
- package/dist/revalidate.d.ts.map +1 -1
- package/dist/revalidate.js +15 -29
- package/dist/revalidate.js.map +1 -1
- package/package.json +16 -6
- package/src/analytics-client.tsx +12 -51
- package/src/analytics.tsx +6 -130
- package/src/cli-helpers.ts +26 -407
- package/src/cli.ts +105 -775
- package/src/index.ts +147 -733
- package/src/preview-client.tsx +22 -295
- package/src/preview.tsx +34 -216
- package/src/revalidate.ts +15 -37
package/src/preview-client.tsx
CHANGED
|
@@ -13,6 +13,18 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import { useCallback, useEffect, useRef, useState, useTransition } from "react";
|
|
15
15
|
import { usePathname, useRouter } from "next/navigation.js";
|
|
16
|
+
// Overlay, patch och protokollet är ramverksoberoende och delas med andra
|
|
17
|
+
// adaptrar via sitecms-js; här finns bara React-livscykeln och Nexts router.
|
|
18
|
+
import {
|
|
19
|
+
cleanupCreatedTextNodes,
|
|
20
|
+
collectFields,
|
|
21
|
+
createOverlay,
|
|
22
|
+
elementsFor,
|
|
23
|
+
parsePanelMessage,
|
|
24
|
+
patchImage,
|
|
25
|
+
patchText,
|
|
26
|
+
} from "sitecms-js/preview-client";
|
|
27
|
+
import type { PreviewOverlay } from "sitecms-js/preview-client";
|
|
16
28
|
|
|
17
29
|
export type SitecmsPreviewClientProps = {
|
|
18
30
|
/** Panelens origin (från cookien sitecms_preview_origin). null → ingen kommunikation. */
|
|
@@ -21,300 +33,17 @@ export type SitecmsPreviewClientProps = {
|
|
|
21
33
|
exitHref?: string;
|
|
22
34
|
};
|
|
23
35
|
|
|
24
|
-
type Field = { page: string; key: string };
|
|
25
|
-
|
|
26
|
-
const PART = /^[A-Za-z0-9._-]+$/;
|
|
27
|
-
const ATTR = "data-sitecms";
|
|
28
36
|
const Z = "2147483646";
|
|
29
|
-
const BRAND = "#2450d1";
|
|
30
37
|
const FONT = 'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif';
|
|
31
38
|
|
|
32
|
-
function validPart(value: unknown): value is string {
|
|
33
|
-
return typeof value === "string" && value.length <= 200 && PART.test(value);
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function parseField(value: string | null): Field | null {
|
|
37
|
-
if (!value) return null;
|
|
38
|
-
const i = value.indexOf(":");
|
|
39
|
-
if (i < 0) return null;
|
|
40
|
-
const page = value.slice(0, i);
|
|
41
|
-
const key = value.slice(i + 1);
|
|
42
|
-
return validPart(page) && validPart(key) ? { page, key } : null;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function elementsFor(page: string, key: string): HTMLElement[] {
|
|
46
|
-
// page och key är validerade (a–z0–9._-), så selektorn behöver ingen escaping.
|
|
47
|
-
return Array.from(document.querySelectorAll<HTMLElement>(`[${ATTR}="${page}:${key}"]`));
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
function collectFields(): Field[] {
|
|
51
|
-
const seen = new Set<string>();
|
|
52
|
-
const fields: Field[] = [];
|
|
53
|
-
for (const el of Array.from(document.querySelectorAll(`[${ATTR}]`))) {
|
|
54
|
-
const field = parseField(el.getAttribute(ATTR));
|
|
55
|
-
if (!field) continue;
|
|
56
|
-
const id = `${field.page}:${field.key}`;
|
|
57
|
-
if (seen.has(id)) continue;
|
|
58
|
-
seen.add(id);
|
|
59
|
-
fields.push(field);
|
|
60
|
-
}
|
|
61
|
-
return fields;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
39
|
function currentPath(): string {
|
|
65
40
|
return `${window.location.pathname}${window.location.search}`;
|
|
66
41
|
}
|
|
67
42
|
|
|
68
|
-
function prefersReducedMotion(): boolean {
|
|
69
|
-
try {
|
|
70
|
-
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
71
|
-
} catch {
|
|
72
|
-
return false;
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
// ---------------------------------------------------------------------------
|
|
77
|
-
// Direkt DOM-byte (patch)
|
|
78
|
-
// ---------------------------------------------------------------------------
|
|
79
|
-
|
|
80
|
-
/** Textnoder som patch skapat i tomma element; tas bort när React renderat egna. */
|
|
81
|
-
const createdTextNodes = new Set<Text>();
|
|
82
|
-
|
|
83
|
-
function patchText(el: HTMLElement, value: string) {
|
|
84
|
-
if (el.children.length > 0) return; // bara element utan barnelement
|
|
85
|
-
// Byt nodeValue på befintliga textnoder i stället för textContent, så att
|
|
86
|
-
// React behåller sina referenser och nästa refresh uppdaterar samma noder.
|
|
87
|
-
const texts = Array.from(el.childNodes).filter((n): n is Text => n.nodeType === Node.TEXT_NODE);
|
|
88
|
-
if (texts.length === 0) {
|
|
89
|
-
const node = document.createTextNode(value);
|
|
90
|
-
el.appendChild(node);
|
|
91
|
-
createdTextNodes.add(node);
|
|
92
|
-
return;
|
|
93
|
-
}
|
|
94
|
-
texts[0].nodeValue = value;
|
|
95
|
-
for (const t of texts.slice(1)) t.nodeValue = "";
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
function patchImage(el: HTMLElement, value: string, alt: unknown) {
|
|
99
|
-
const img = el instanceof HTMLImageElement ? el : el.querySelector("img");
|
|
100
|
-
if (!img) return;
|
|
101
|
-
img.removeAttribute("srcset");
|
|
102
|
-
if (img.parentElement?.tagName === "PICTURE") {
|
|
103
|
-
for (const source of Array.from(img.parentElement.querySelectorAll("source"))) source.removeAttribute("srcset");
|
|
104
|
-
}
|
|
105
|
-
if (value) img.setAttribute("src", value);
|
|
106
|
-
else img.removeAttribute("src");
|
|
107
|
-
if (typeof alt === "string") img.alt = alt;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/** Efter en refresh: ta bort textnoder från patch där React nu renderat egen text. */
|
|
111
|
-
function cleanupCreatedTextNodes() {
|
|
112
|
-
for (const node of Array.from(createdTextNodes)) {
|
|
113
|
-
const parent = node.parentNode;
|
|
114
|
-
if (!parent) {
|
|
115
|
-
createdTextNodes.delete(node);
|
|
116
|
-
continue;
|
|
117
|
-
}
|
|
118
|
-
const others = Array.from(parent.childNodes).some((n) => n !== node && n.nodeType === Node.TEXT_NODE);
|
|
119
|
-
if (others) {
|
|
120
|
-
parent.removeChild(node);
|
|
121
|
-
createdTextNodes.delete(node);
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// ---------------------------------------------------------------------------
|
|
127
|
-
// Overlay: hover-ram + etikett, blink vid highlight
|
|
128
|
-
// ---------------------------------------------------------------------------
|
|
129
|
-
|
|
130
|
-
type Overlay = {
|
|
131
|
-
setEnabled(enabled: boolean): void;
|
|
132
|
-
highlight(page: string, key: string): void;
|
|
133
|
-
destroy(): void;
|
|
134
|
-
};
|
|
135
|
-
|
|
136
|
-
function makeBox(): { box: HTMLDivElement; label: HTMLDivElement } {
|
|
137
|
-
const box = document.createElement("div");
|
|
138
|
-
box.setAttribute("aria-hidden", "true");
|
|
139
|
-
box.setAttribute("data-sitecms-overlay", "");
|
|
140
|
-
Object.assign(box.style, {
|
|
141
|
-
position: "fixed",
|
|
142
|
-
top: "0",
|
|
143
|
-
left: "0",
|
|
144
|
-
width: "0",
|
|
145
|
-
height: "0",
|
|
146
|
-
display: "none",
|
|
147
|
-
boxSizing: "border-box",
|
|
148
|
-
border: `2px solid ${BRAND}`,
|
|
149
|
-
borderRadius: "4px",
|
|
150
|
-
boxShadow: "0 0 0 1px rgba(255,255,255,0.85)",
|
|
151
|
-
pointerEvents: "none",
|
|
152
|
-
zIndex: Z,
|
|
153
|
-
margin: "0",
|
|
154
|
-
padding: "0",
|
|
155
|
-
} satisfies Partial<CSSStyleDeclaration>);
|
|
156
|
-
const label = document.createElement("div");
|
|
157
|
-
Object.assign(label.style, {
|
|
158
|
-
position: "absolute",
|
|
159
|
-
left: "-2px",
|
|
160
|
-
top: "-22px",
|
|
161
|
-
maxWidth: "260px",
|
|
162
|
-
overflow: "hidden",
|
|
163
|
-
textOverflow: "ellipsis",
|
|
164
|
-
whiteSpace: "nowrap",
|
|
165
|
-
background: BRAND,
|
|
166
|
-
color: "#fff",
|
|
167
|
-
font: `600 11px/16px ${FONT}`,
|
|
168
|
-
letterSpacing: "0",
|
|
169
|
-
padding: "2px 6px",
|
|
170
|
-
borderRadius: "4px",
|
|
171
|
-
pointerEvents: "none",
|
|
172
|
-
textTransform: "none",
|
|
173
|
-
} satisfies Partial<CSSStyleDeclaration>);
|
|
174
|
-
box.appendChild(label);
|
|
175
|
-
return { box, label };
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
function place(box: HTMLDivElement, label: HTMLDivElement, el: Element) {
|
|
179
|
-
const r = el.getBoundingClientRect();
|
|
180
|
-
const pad = 3;
|
|
181
|
-
box.style.top = `${r.top - pad}px`;
|
|
182
|
-
box.style.left = `${r.left - pad}px`;
|
|
183
|
-
box.style.width = `${r.width + pad * 2}px`;
|
|
184
|
-
box.style.height = `${r.height + pad * 2}px`;
|
|
185
|
-
// Etiketten ovanför ramen, eller innanför om elementet ligger i överkanten.
|
|
186
|
-
label.style.top = r.top < 26 ? "2px" : "-22px";
|
|
187
|
-
label.style.left = r.top < 26 ? "2px" : "-2px";
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
function createOverlay(onFocus: (field: Field) => void): Overlay {
|
|
191
|
-
const hover = makeBox();
|
|
192
|
-
const flash = makeBox();
|
|
193
|
-
flash.box.style.border = `3px solid ${BRAND}`;
|
|
194
|
-
flash.box.style.boxShadow = `0 0 0 4px rgba(36,80,209,0.25)`;
|
|
195
|
-
flash.label.style.display = "none";
|
|
196
|
-
document.body.appendChild(hover.box);
|
|
197
|
-
document.body.appendChild(flash.box);
|
|
198
|
-
|
|
199
|
-
if (!prefersReducedMotion()) {
|
|
200
|
-
hover.box.style.transition = "top 80ms ease-out, left 80ms ease-out, width 80ms ease-out, height 80ms ease-out";
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
let enabled = true;
|
|
204
|
-
let current: HTMLElement | null = null;
|
|
205
|
-
let flashTarget: HTMLElement | null = null;
|
|
206
|
-
let flashTimer: ReturnType<typeof setTimeout> | undefined;
|
|
207
|
-
let frame = 0;
|
|
208
|
-
|
|
209
|
-
const hide = () => {
|
|
210
|
-
current = null;
|
|
211
|
-
hover.box.style.display = "none";
|
|
212
|
-
};
|
|
213
|
-
|
|
214
|
-
const update = () => {
|
|
215
|
-
frame = 0;
|
|
216
|
-
if (current) {
|
|
217
|
-
if (current.isConnected) place(hover.box, hover.label, current);
|
|
218
|
-
else hide();
|
|
219
|
-
}
|
|
220
|
-
if (flashTarget) {
|
|
221
|
-
if (flashTarget.isConnected) place(flash.box, flash.label, flashTarget);
|
|
222
|
-
else flash.box.style.display = "none";
|
|
223
|
-
}
|
|
224
|
-
};
|
|
225
|
-
const schedule = () => {
|
|
226
|
-
if (!frame) frame = window.requestAnimationFrame(update);
|
|
227
|
-
};
|
|
228
|
-
|
|
229
|
-
const target = (e: Event): HTMLElement | null => {
|
|
230
|
-
const t = e.target;
|
|
231
|
-
if (!(t instanceof Element)) return null;
|
|
232
|
-
const el = t.closest<HTMLElement>(`[${ATTR}]`);
|
|
233
|
-
return el && parseField(el.getAttribute(ATTR)) ? el : null;
|
|
234
|
-
};
|
|
235
|
-
|
|
236
|
-
const onOver = (e: MouseEvent) => {
|
|
237
|
-
if (!enabled) return;
|
|
238
|
-
const el = target(e);
|
|
239
|
-
if (!el) return hide();
|
|
240
|
-
if (el === current) return;
|
|
241
|
-
current = el;
|
|
242
|
-
hover.label.textContent = parseField(el.getAttribute(ATTR))!.key;
|
|
243
|
-
hover.box.style.display = "block";
|
|
244
|
-
place(hover.box, hover.label, el);
|
|
245
|
-
};
|
|
246
|
-
const onLeaveDocument = (e: MouseEvent) => {
|
|
247
|
-
if (!e.relatedTarget) hide();
|
|
248
|
-
};
|
|
249
|
-
const onClick = (e: MouseEvent) => {
|
|
250
|
-
if (!enabled || e.button !== 0) return;
|
|
251
|
-
const el = target(e);
|
|
252
|
-
if (!el) return;
|
|
253
|
-
e.preventDefault();
|
|
254
|
-
e.stopPropagation();
|
|
255
|
-
onFocus(parseField(el.getAttribute(ATTR))!);
|
|
256
|
-
};
|
|
257
|
-
|
|
258
|
-
document.addEventListener("mouseover", onOver, { passive: true });
|
|
259
|
-
document.addEventListener("mouseout", onLeaveDocument, { passive: true });
|
|
260
|
-
// Capture på window: körs före sidans egna klick-hanterare (React, länkar).
|
|
261
|
-
window.addEventListener("click", onClick, true);
|
|
262
|
-
window.addEventListener("scroll", schedule, { passive: true, capture: true });
|
|
263
|
-
window.addEventListener("resize", schedule, { passive: true });
|
|
264
|
-
|
|
265
|
-
return {
|
|
266
|
-
setEnabled(value) {
|
|
267
|
-
enabled = value;
|
|
268
|
-
if (!value) hide();
|
|
269
|
-
},
|
|
270
|
-
highlight(page, key) {
|
|
271
|
-
const el = elementsFor(page, key)[0];
|
|
272
|
-
if (!el) return;
|
|
273
|
-
const reduced = prefersReducedMotion();
|
|
274
|
-
try {
|
|
275
|
-
el.scrollIntoView({ behavior: reduced ? "auto" : "smooth", block: "center", inline: "nearest" });
|
|
276
|
-
} catch {
|
|
277
|
-
el.scrollIntoView();
|
|
278
|
-
}
|
|
279
|
-
flashTarget = el;
|
|
280
|
-
flash.box.style.display = "block";
|
|
281
|
-
place(flash.box, flash.label, el);
|
|
282
|
-
clearTimeout(flashTimer);
|
|
283
|
-
if (!reduced && typeof flash.box.animate === "function") {
|
|
284
|
-
flash.box.getAnimations?.().forEach((a) => a.cancel());
|
|
285
|
-
flash.box.animate([{ opacity: 0 }, { opacity: 1 }, { opacity: 0.25 }, { opacity: 1 }, { opacity: 0 }], {
|
|
286
|
-
duration: 1400,
|
|
287
|
-
easing: "ease-in-out",
|
|
288
|
-
fill: "forwards",
|
|
289
|
-
});
|
|
290
|
-
} else {
|
|
291
|
-
flash.box.style.opacity = "1";
|
|
292
|
-
}
|
|
293
|
-
flashTimer = setTimeout(() => {
|
|
294
|
-
flashTarget = null;
|
|
295
|
-
flash.box.style.display = "none";
|
|
296
|
-
}, 1500);
|
|
297
|
-
},
|
|
298
|
-
destroy() {
|
|
299
|
-
document.removeEventListener("mouseover", onOver);
|
|
300
|
-
document.removeEventListener("mouseout", onLeaveDocument);
|
|
301
|
-
window.removeEventListener("click", onClick, true);
|
|
302
|
-
window.removeEventListener("scroll", schedule, true);
|
|
303
|
-
window.removeEventListener("resize", schedule);
|
|
304
|
-
if (frame) window.cancelAnimationFrame(frame);
|
|
305
|
-
clearTimeout(flashTimer);
|
|
306
|
-
hover.box.remove();
|
|
307
|
-
flash.box.remove();
|
|
308
|
-
},
|
|
309
|
-
};
|
|
310
|
-
}
|
|
311
|
-
|
|
312
43
|
// ---------------------------------------------------------------------------
|
|
313
44
|
// Komponenten
|
|
314
45
|
// ---------------------------------------------------------------------------
|
|
315
46
|
|
|
316
|
-
type Incoming = Record<string, unknown> & { source?: unknown; v?: unknown; type?: unknown };
|
|
317
|
-
|
|
318
47
|
export function SitecmsPreviewClient({ panelOrigin, exitHref = "/api/sitecms/preview?disable=1" }: SitecmsPreviewClientProps) {
|
|
319
48
|
const router = useRouter();
|
|
320
49
|
const pathname = usePathname();
|
|
@@ -322,7 +51,7 @@ export function SitecmsPreviewClient({ panelOrigin, exitHref = "/api/sitecms/pre
|
|
|
322
51
|
const [mode, setMode] = useState<"unknown" | "frame" | "top">("unknown");
|
|
323
52
|
const [refreshId, setRefreshId] = useState(0);
|
|
324
53
|
const postedRefresh = useRef(0);
|
|
325
|
-
const overlay = useRef<
|
|
54
|
+
const overlay = useRef<PreviewOverlay | null>(null);
|
|
326
55
|
|
|
327
56
|
useEffect(() => {
|
|
328
57
|
setMode(window.parent !== window ? "frame" : "top");
|
|
@@ -354,28 +83,26 @@ export function SitecmsPreviewClient({ panelOrigin, exitHref = "/api/sitecms/pre
|
|
|
354
83
|
|
|
355
84
|
const onMessage = (event: MessageEvent) => {
|
|
356
85
|
if (event.origin !== panelOrigin || event.source !== window.parent) return;
|
|
357
|
-
const
|
|
358
|
-
if (!
|
|
359
|
-
switch (
|
|
86
|
+
const message = parsePanelMessage(event.data);
|
|
87
|
+
if (!message) return;
|
|
88
|
+
switch (message.type) {
|
|
360
89
|
case "refresh":
|
|
361
90
|
startRefresh(() => {
|
|
362
91
|
router.refresh();
|
|
363
92
|
setRefreshId((n) => n + 1);
|
|
364
93
|
});
|
|
365
94
|
return;
|
|
366
|
-
case "patch":
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
else if (data.kind === "image") patchImage(el, data.value, data.alt);
|
|
95
|
+
case "patch":
|
|
96
|
+
for (const el of elementsFor(message.page, message.key)) {
|
|
97
|
+
if (message.kind === "text") patchText(el, message.value);
|
|
98
|
+
else patchImage(el, message.value, message.alt);
|
|
371
99
|
}
|
|
372
100
|
return;
|
|
373
|
-
}
|
|
374
101
|
case "highlight":
|
|
375
|
-
|
|
102
|
+
ui.highlight(message.page, message.key);
|
|
376
103
|
return;
|
|
377
104
|
case "overlays":
|
|
378
|
-
|
|
105
|
+
ui.setEnabled(message.enabled);
|
|
379
106
|
return;
|
|
380
107
|
}
|
|
381
108
|
};
|
package/src/preview.tsx
CHANGED
|
@@ -21,64 +21,40 @@
|
|
|
21
21
|
* `next/headers` importeras dynamiskt: modulen går att importera utanför
|
|
22
22
|
* Next (t.ex. i next.config) och statiska sidor förblir statiska.
|
|
23
23
|
*/
|
|
24
|
+
import { PREVIEW_COOKIE, PREVIEW_ORIGIN_COOKIE, isPreview } from "./index.js";
|
|
24
25
|
import {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
26
|
+
PREVIEW_LOCALE_COOKIE,
|
|
27
|
+
PREVIEW_LOCALE_PARAM,
|
|
28
|
+
PREVIEW_MAX_AGE,
|
|
29
|
+
PREVIEW_ROUTE_PATH,
|
|
30
|
+
cleanPreviewLocale,
|
|
31
|
+
isLocalHttp,
|
|
32
|
+
normalizeOrigin,
|
|
33
|
+
previewCookieAttributes,
|
|
34
|
+
previewErrorPage,
|
|
35
|
+
previewFrameHeaders,
|
|
36
|
+
previewRedirect,
|
|
37
|
+
safePreviewPath,
|
|
38
|
+
verifyPreviewToken,
|
|
39
|
+
} from "sitecms-js/preview";
|
|
40
|
+
import type { PreviewCookieAttributes } from "sitecms-js/preview";
|
|
32
41
|
import { SitecmsPreviewClient } from "./preview-client.js";
|
|
33
42
|
|
|
34
|
-
export { isPreview };
|
|
43
|
+
export { isPreview, previewFrameHeaders, safePreviewPath, PREVIEW_ROUTE_PATH };
|
|
35
44
|
export type { SitecmsPreviewClientProps } from "./preview-client.js";
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
export const PREVIEW_ROUTE_PATH = "/api/sitecms/preview";
|
|
45
|
+
// Meddelandeprotokollet (v1) — typer för den som vill bygga egen klient/panel.
|
|
46
|
+
export type { PreviewField, PreviewPanelMessage, PreviewSiteMessage } from "sitecms-js/preview";
|
|
39
47
|
|
|
40
48
|
/** Nexts draft mode-cookie. */
|
|
41
49
|
const BYPASS_COOKIE = "__prerender_bypass";
|
|
42
|
-
/** Preview-cookiernas livslängd i sekunder (som sessionen i sitecms). */
|
|
43
|
-
const PREVIEW_MAX_AGE = 7200;
|
|
44
|
-
|
|
45
|
-
// ---------------------------------------------------------------------------
|
|
46
|
-
// Meddelandeprotokoll (v1) — typer för den som vill bygga egen klient/panel
|
|
47
|
-
// ---------------------------------------------------------------------------
|
|
48
|
-
|
|
49
|
-
export type PreviewField = { page: string; key: string };
|
|
50
|
-
|
|
51
|
-
/** Panel → sajt (`source: "sitecms"`). */
|
|
52
|
-
export type PreviewPanelMessage = { source: "sitecms"; v: 1 } & (
|
|
53
|
-
| { type: "refresh" }
|
|
54
|
-
| { type: "patch"; page: string; key: string; kind: "text" | "image"; value: string; alt?: string | null }
|
|
55
|
-
| { type: "highlight"; page: string; key: string }
|
|
56
|
-
| { type: "overlays"; enabled: boolean }
|
|
57
|
-
);
|
|
58
|
-
|
|
59
|
-
/** Sajt → panel (`source: "sitecms-preview"`). */
|
|
60
|
-
export type PreviewSiteMessage = { source: "sitecms-preview"; v: 1 } & (
|
|
61
|
-
| { type: "ready"; path: string; title: string; fields: PreviewField[] }
|
|
62
|
-
| { type: "refreshed"; path: string }
|
|
63
|
-
| { type: "focus"; page: string; key: string }
|
|
64
|
-
);
|
|
65
50
|
|
|
66
51
|
// ---------------------------------------------------------------------------
|
|
67
52
|
// Hjälpfunktioner
|
|
68
53
|
// ---------------------------------------------------------------------------
|
|
69
54
|
|
|
70
|
-
|
|
71
|
-
return (typeof process !== "undefined" && process.env?.[name]?.trim()) || "";
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
type CookieOptions = {
|
|
55
|
+
type CookieOptions = Partial<PreviewCookieAttributes> & {
|
|
75
56
|
name: string;
|
|
76
57
|
value: string;
|
|
77
|
-
httpOnly?: boolean;
|
|
78
|
-
secure?: boolean;
|
|
79
|
-
sameSite?: "lax" | "none" | "strict";
|
|
80
|
-
partitioned?: boolean;
|
|
81
|
-
path?: string;
|
|
82
58
|
maxAge?: number;
|
|
83
59
|
expires?: Date;
|
|
84
60
|
};
|
|
@@ -104,113 +80,6 @@ async function loadNextHeaders(): Promise<NextHeadersLike | null> {
|
|
|
104
80
|
}
|
|
105
81
|
}
|
|
106
82
|
|
|
107
|
-
/**
|
|
108
|
-
* Sökvägen att skicka vidare till efter routen: måste börja med `/` men inte
|
|
109
|
-
* `//` eller `/\` (annars `/`), så att routen aldrig blir en öppen redirect.
|
|
110
|
-
* Behåller query och hash.
|
|
111
|
-
*/
|
|
112
|
-
export function safePreviewPath(raw: string | null | undefined): string {
|
|
113
|
-
const value = (raw ?? "").trim();
|
|
114
|
-
if (!value.startsWith("/") || value.startsWith("//")) return "/";
|
|
115
|
-
// Webbläsare tolkar \ som / och kontrolltecken tas bort: "/\evil.se" blir "//evil.se".
|
|
116
|
-
if (/[\\\u0000-\u001f\u007f]/.test(value)) return "/";
|
|
117
|
-
try {
|
|
118
|
-
const base = "http://sitecms.invalid";
|
|
119
|
-
const url = new URL(value, base);
|
|
120
|
-
if (url.origin !== base) return "/";
|
|
121
|
-
return `${url.pathname}${url.search}${url.hash}`;
|
|
122
|
-
} catch {
|
|
123
|
-
return "/";
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
/** En origin (`https://sitecms.se`) eller null. Accepterar bara http(s) utan sökväg. */
|
|
128
|
-
function normalizeOrigin(value: unknown): string | null {
|
|
129
|
-
if (typeof value !== "string" || !value.trim()) return null;
|
|
130
|
-
try {
|
|
131
|
-
const url = new URL(value.trim());
|
|
132
|
-
if (url.protocol !== "https:" && url.protocol !== "http:") return null;
|
|
133
|
-
if (url.username || url.password) return null;
|
|
134
|
-
if (url.pathname !== "/" || url.search || url.hash) return null;
|
|
135
|
-
return url.origin;
|
|
136
|
-
} catch {
|
|
137
|
-
return null;
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
function isLoopbackHost(hostname: string): boolean {
|
|
142
|
-
const host = hostname.toLowerCase();
|
|
143
|
-
return host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]";
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
/**
|
|
147
|
-
* http://localhost (dev): cookies utan Secure/Partitioned och SameSite=Lax.
|
|
148
|
-
* `next start` bygger request.url från sin egen adress (localhost) om proxyn
|
|
149
|
-
* inte skickar x-forwarded-proto, så även Host/x-forwarded-host måste vara
|
|
150
|
-
* localhost — annars antas en riktig (https-)sajt bakom proxy.
|
|
151
|
-
*/
|
|
152
|
-
function isLocalHttp(url: URL, headers: Headers): boolean {
|
|
153
|
-
if (url.protocol !== "http:" || !isLoopbackHost(url.hostname)) return false;
|
|
154
|
-
const hostHeader = (headers.get("x-forwarded-host") ?? headers.get("host") ?? "").split(",")[0].trim();
|
|
155
|
-
if (!hostHeader) return true;
|
|
156
|
-
try {
|
|
157
|
-
return isLoopbackHost(new URL(`http://${hostHeader}`).hostname);
|
|
158
|
-
} catch {
|
|
159
|
-
return false;
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
function cookieAttributes(localDev: boolean): Omit<CookieOptions, "name" | "value"> {
|
|
164
|
-
return localDev
|
|
165
|
-
? { httpOnly: true, secure: false, sameSite: "lax", path: "/" }
|
|
166
|
-
: { httpOnly: true, secure: true, sameSite: "none", partitioned: true, path: "/" };
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
function escapeHtml(value: string): string {
|
|
170
|
-
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
const NO_STORE = { "Cache-Control": "private, no-store", "Referrer-Policy": "no-referrer" };
|
|
174
|
-
|
|
175
|
-
/** Enkel felsida på svenska. Token ekas aldrig tillbaka. */
|
|
176
|
-
function errorPage(status: number, message: string): Response {
|
|
177
|
-
const html = `<!doctype html>
|
|
178
|
-
<html lang="sv">
|
|
179
|
-
<head>
|
|
180
|
-
<meta charset="utf-8">
|
|
181
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
182
|
-
<meta name="robots" content="noindex">
|
|
183
|
-
<title>Förhandsgranskningen kunde inte startas</title>
|
|
184
|
-
<style>
|
|
185
|
-
:root { color-scheme: light dark; }
|
|
186
|
-
body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px; box-sizing: border-box;
|
|
187
|
-
font: 15px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; background: #f6f7f9; color: #171717; }
|
|
188
|
-
main { max-width: 440px; background: #fff; border: 1px solid #e5e5e5; border-radius: 12px; padding: 24px; }
|
|
189
|
-
h1 { font-size: 17px; margin: 0 0 8px; }
|
|
190
|
-
p { margin: 0; color: #525252; }
|
|
191
|
-
@media (prefers-color-scheme: dark) {
|
|
192
|
-
body { background: #0a0a0a; color: #f5f5f5; }
|
|
193
|
-
main { background: #171717; border-color: #262626; }
|
|
194
|
-
p { color: #a3a3a3; }
|
|
195
|
-
}
|
|
196
|
-
</style>
|
|
197
|
-
</head>
|
|
198
|
-
<body>
|
|
199
|
-
<main>
|
|
200
|
-
<h1>Förhandsgranskningen kunde inte startas</h1>
|
|
201
|
-
<p>${escapeHtml(message)}</p>
|
|
202
|
-
</main>
|
|
203
|
-
</body>
|
|
204
|
-
</html>
|
|
205
|
-
`;
|
|
206
|
-
return new Response(html, { status, headers: { "Content-Type": "text/html; charset=utf-8", ...NO_STORE } });
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
function redirectTo(path: string): Response {
|
|
210
|
-
// Relativ Location: rätt värd även bakom proxy.
|
|
211
|
-
return new Response(null, { status: 307, headers: { Location: path, ...NO_STORE } });
|
|
212
|
-
}
|
|
213
|
-
|
|
214
83
|
// ---------------------------------------------------------------------------
|
|
215
84
|
// Route: GET /api/sitecms/preview
|
|
216
85
|
// ---------------------------------------------------------------------------
|
|
@@ -228,10 +97,6 @@ export type PreviewRouteOptions = {
|
|
|
228
97
|
nextHeaders?: () => Promise<NextHeadersLike | null> | NextHeadersLike | null;
|
|
229
98
|
};
|
|
230
99
|
|
|
231
|
-
const MSG_INVALID = "Länken har gått ut eller är ogiltig. Öppna förhandsgranskningen igen i sitecms.";
|
|
232
|
-
const MSG_UNREACHABLE = "sitecms gick inte att nå just nu. Försök igen om en stund.";
|
|
233
|
-
const MSG_NO_KEY =
|
|
234
|
-
"CMS_API_KEY saknas på sajten. Lägg in den som miljövariabel hos webbhotellet och deploya om.";
|
|
235
100
|
const MSG_NO_NEXT = "Routen kräver Next.js App Router (next/headers saknas).";
|
|
236
101
|
|
|
237
102
|
/**
|
|
@@ -247,10 +112,10 @@ export function createPreviewRoute(options: PreviewRouteOptions = {}) {
|
|
|
247
112
|
return async function GET(request: Request): Promise<Response> {
|
|
248
113
|
const url = new URL(request.url);
|
|
249
114
|
const path = safePreviewPath(url.searchParams.get("path"));
|
|
250
|
-
const attrs =
|
|
115
|
+
const attrs = previewCookieAttributes(isLocalHttp(url, request.headers));
|
|
251
116
|
|
|
252
117
|
const next = await (options.nextHeaders ? options.nextHeaders() : loadNextHeaders());
|
|
253
|
-
if (!next) return
|
|
118
|
+
if (!next) return previewErrorPage(500, MSG_NO_NEXT);
|
|
254
119
|
|
|
255
120
|
if (url.searchParams.has("disable")) {
|
|
256
121
|
const draft = (await next.draftMode()) as DraftModeLike;
|
|
@@ -261,31 +126,14 @@ export function createPreviewRoute(options: PreviewRouteOptions = {}) {
|
|
|
261
126
|
for (const name of [BYPASS_COOKIE, PREVIEW_COOKIE, PREVIEW_ORIGIN_COOKIE]) {
|
|
262
127
|
store.set({ name, value: "", ...attrs, expires: new Date(0) });
|
|
263
128
|
}
|
|
264
|
-
|
|
129
|
+
if (store.get(PREVIEW_LOCALE_COOKIE)) store.set({ name: PREVIEW_LOCALE_COOKIE, value: "", ...attrs, expires: new Date(0) });
|
|
130
|
+
return previewRedirect(path);
|
|
265
131
|
}
|
|
266
132
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
const
|
|
271
|
-
const apiKey = (options.apiKey ?? env("CMS_API_KEY")).trim();
|
|
272
|
-
if (!apiKey) return errorPage(500, MSG_NO_KEY);
|
|
273
|
-
const base = apiBase(options.apiUrl ?? env("CMS_API_URL"), options.site ?? (explicitKey ? "" : env("CMS_SITE")));
|
|
274
|
-
const doFetch = options.fetch ?? globalThis.fetch;
|
|
275
|
-
|
|
276
|
-
let res: Response;
|
|
277
|
-
try {
|
|
278
|
-
res = await doFetch(`${base}/preview`, {
|
|
279
|
-
headers: { "x-api-key": apiKey, [PREVIEW_HEADER]: token },
|
|
280
|
-
cache: "no-store",
|
|
281
|
-
});
|
|
282
|
-
} catch {
|
|
283
|
-
return errorPage(401, MSG_UNREACHABLE);
|
|
284
|
-
}
|
|
285
|
-
if (!res.ok) return errorPage(401, res.status >= 500 ? MSG_UNREACHABLE : MSG_INVALID);
|
|
286
|
-
const body = (await res.json().catch(() => null)) as { ok?: unknown; panelOrigin?: unknown } | null;
|
|
287
|
-
const panelOrigin = normalizeOrigin(body?.panelOrigin);
|
|
288
|
-
if (body?.ok !== true || !panelOrigin) return errorPage(401, MSG_INVALID);
|
|
133
|
+
// Token, nyckel och svaret från sitecms kontrolleras i sitecms-js.
|
|
134
|
+
const verified = await verifyPreviewToken(url.searchParams.get("token"), options);
|
|
135
|
+
if (!verified.ok) return previewErrorPage(verified.status, verified.message);
|
|
136
|
+
const token = url.searchParams.get("token")!.trim();
|
|
289
137
|
|
|
290
138
|
const draft = (await next.draftMode()) as DraftModeLike;
|
|
291
139
|
draft.enable();
|
|
@@ -295,8 +143,12 @@ export function createPreviewRoute(options: PreviewRouteOptions = {}) {
|
|
|
295
143
|
const bypass = store.get(BYPASS_COOKIE)?.value;
|
|
296
144
|
if (bypass) store.set({ name: BYPASS_COOKIE, value: bypass, ...attrs });
|
|
297
145
|
store.set({ name: PREVIEW_COOKIE, value: token, ...attrs, maxAge: PREVIEW_MAX_AGE });
|
|
298
|
-
store.set({ name: PREVIEW_ORIGIN_COOKIE, value: panelOrigin, ...attrs, maxAge: PREVIEW_MAX_AGE });
|
|
299
|
-
|
|
146
|
+
store.set({ name: PREVIEW_ORIGIN_COOKIE, value: verified.panelOrigin, ...attrs, maxAge: PREVIEW_MAX_AGE });
|
|
147
|
+
// Språket som panelen förhandsgranskar (sitecms 1.0); utan → standardspråket.
|
|
148
|
+
const locale = cleanPreviewLocale(url.searchParams.get(PREVIEW_LOCALE_PARAM));
|
|
149
|
+
if (locale) store.set({ name: PREVIEW_LOCALE_COOKIE, value: locale, ...attrs, maxAge: PREVIEW_MAX_AGE });
|
|
150
|
+
else if (store.get(PREVIEW_LOCALE_COOKIE)) store.set({ name: PREVIEW_LOCALE_COOKIE, value: "", ...attrs, expires: new Date(0) });
|
|
151
|
+
return previewRedirect(path);
|
|
300
152
|
};
|
|
301
153
|
}
|
|
302
154
|
|
|
@@ -332,37 +184,3 @@ export async function SitecmsPreview(props: SitecmsPreviewProps = {}) {
|
|
|
332
184
|
const routePath = safePreviewPath(props.routePath ?? PREVIEW_ROUTE_PATH).replace(/[?#].*$/, "");
|
|
333
185
|
return <SitecmsPreviewClient panelOrigin={panelOrigin} exitHref={`${routePath}?disable=1`} />;
|
|
334
186
|
}
|
|
335
|
-
|
|
336
|
-
// ---------------------------------------------------------------------------
|
|
337
|
-
// Frame-headers — i next.config
|
|
338
|
-
// ---------------------------------------------------------------------------
|
|
339
|
-
|
|
340
|
-
const WILDCARD_SOURCE = /^https:\/\/\*\.[a-z0-9-]+(\.[a-z0-9-]+)+(:\d{1,5})?$/i;
|
|
341
|
-
|
|
342
|
-
/**
|
|
343
|
-
* Headers som låter panelen bädda in sajten i en iframe:
|
|
344
|
-
*
|
|
345
|
-
* // next.config.ts
|
|
346
|
-
* async headers() {
|
|
347
|
-
* return [{ source: "/:path*", headers: previewFrameHeaders() }];
|
|
348
|
-
* }
|
|
349
|
-
*
|
|
350
|
-
* Default: origin för CMS_API_URL (annars https://sitecms.se) plus
|
|
351
|
-
* https://www.sitecms.se. Ta bort `X-Frame-Options` på sajten — CSP
|
|
352
|
-
* `frame-ancestors` ersätter den.
|
|
353
|
-
*/
|
|
354
|
-
export function previewFrameHeaders(panelOrigins?: string[]): { key: string; value: string }[] {
|
|
355
|
-
const input =
|
|
356
|
-
panelOrigins ?? [normalizeOrigin(env("CMS_API_URL").replace(/\/+$/, "")) ?? DEFAULT_API_URL, "https://www.sitecms.se"];
|
|
357
|
-
const sources: string[] = [];
|
|
358
|
-
for (const raw of input) {
|
|
359
|
-
const value = String(raw ?? "").trim().replace(/\/+$/, "");
|
|
360
|
-
const source = WILDCARD_SOURCE.test(value) ? value.toLowerCase() : normalizeOrigin(value);
|
|
361
|
-
if (!source) {
|
|
362
|
-
console.warn(`sitecms: previewFrameHeaders hoppar över ${JSON.stringify(raw)} (inte en origin, t.ex. https://sitecms.se).`);
|
|
363
|
-
continue;
|
|
364
|
-
}
|
|
365
|
-
if (!sources.includes(source)) sources.push(source);
|
|
366
|
-
}
|
|
367
|
-
return [{ key: "Content-Security-Policy", value: ["frame-ancestors", "'self'", ...sources].join(" ") }];
|
|
368
|
-
}
|