@parhelia/head 0.0.0-stage → 1.0.12903

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/LICENSE ADDED
@@ -0,0 +1,8 @@
1
+ Parhelia - AI-Powered Content Editor
2
+
3
+ Copyright © 2025 Canvas REPLY GmbH. All rights reserved.
4
+
5
+ For full license terms and legal notice, please visit:
6
+ https://parhelia.ai/license
7
+
8
+ This software is proprietary and confidential.
package/README.md CHANGED
@@ -1,3 +1,195 @@
1
- # Temporary Holding Version
1
+ # @parhelia/head
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Make a rendering head editable in Parhelia, on any framework and without one: Next.js, TanStack Start, React Router, Astro,
4
+ plain server-rendered HTML. Plain JavaScript, no build step, no React: it can be copied into a head that is built elsewhere.
5
+
6
+ | Entry | What it is for |
7
+ |---|---|
8
+ | `@parhelia/head` | the editing bridge (`loadParheliaBridge` in the browser, `parheliaBridgeScriptProps` for the server's `<script>`), the slot markers, the rendered identity, the in-place refresh (`installParheliaRefresh`, `installParheliaDomRefresh`), the build values (`withBasePath`, `parheliaOrigin`, `configureParhelia`) |
9
+ | `@parhelia/head/server` | `isEditingRequest`: is this request the editor? (server-side only) |
10
+ | `@parhelia/head/identity` | the rendered-identity script |
11
+ | `@parhelia/head/refresh` | the in-place refresh loop |
12
+ | `@parhelia/head/rich-text` | `sanitizeRichTextHtml` for CMS rich text |
13
+ | `@parhelia/head/<cms>` | a CMS's own helpers: `contentful` (Live Preview origins), `umbraco`, `magnolia`, `typo3` (marker names) |
14
+ | `@parhelia/head/vite` | `parhelia()`, the Vite build adapter |
15
+
16
+ The framework adapters build on it:
17
+
18
+ | Package | For |
19
+ |---|---|
20
+ | [`@parhelia/react`](../react/README.md) | a React head on any framework: `ParheliaBridge`, `ParheliaBridgeScript`, `ParheliaSlot`, `useParheliaRefresh` |
21
+ | [`@parhelia/astro`](../astro/README.md) | an Astro head: the integration and the slot, bridge and refresh components |
22
+ | [`@parhelia/next`](../next/README.md) | a Next.js head: `withParhelia` (`/config`), re-exporting this package and `@parhelia/react` under the same entries |
23
+
24
+ ## The build: base path and editor origin
25
+
26
+ Two values come from the head's build, because the server render and the browser must agree on them: the base path below
27
+ Parhelia's rendering proxy (`PARHELIA_RENDERING_PROXY_PATH`, `/parhelia/proxy/<head name>`) and the Parhelia editor's origin
28
+ (`PARHELIA_ORIGIN`, for a head the editor frames directly). `withBasePath`, `ParheliaBridge` and
29
+ `contentfulLivePreviewOrigins` read them. A framework adapter puts them into the build:
30
+
31
+ ```ts
32
+ // vite.config.ts (TanStack Start, React Router, any Vite build): before the framework's own plugin
33
+ import { parhelia } from '@parhelia/head/vite';
34
+ import { tanstackStart } from '@tanstack/react-start/plugin/vite';
35
+ import viteReact from '@vitejs/plugin-react';
36
+
37
+ export default defineConfig({ plugins: [parhelia(), tanstackStart(), viteReact()] });
38
+ ```
39
+
40
+ `parhelia()` sets Vite's `base` to the proxy path (assets included; TanStack Start derives its router's base path from it),
41
+ inlines the two values into the browser's and the server's code, and bundles this package for the server so the values reach
42
+ it. Only these two: the editor secret and the preview key stay server-side environment variables. A Next.js head uses
43
+ `withParhelia` from `@parhelia/next/config` instead. Any other build calls `configureParhelia({ origin, basePath })` in a
44
+ module both the server and the browser load.
45
+
46
+ A directly framed head also lets the editor frame it: add `PARHELIA_ORIGIN` to the CSP `frame-ancestors` of the head's
47
+ responses (`withParhelia` does this for Next.js's `headers()`).
48
+
49
+ ## The editing bridge
50
+
51
+ A head the editor frames directly (its own URL, another origin than the editor's) loads Parhelia's editing bridge itself: a
52
+ cross-origin frame cannot be given the bridge by its parent. Below Parhelia's rendering proxy the editor injects it.
53
+ `loadParheliaBridge()` adds the script in the browser, only in a frame of another origin on `?parhelia=1`;
54
+ `parheliaBridgeScriptProps(options)` is the `<script>`'s attributes for a server that renders it into the HTML (a CSP nonce,
55
+ `integrity`), with `shouldRenderParheliaBridgeScript({ searchParams | requestUrl })` as the request check. The bridge loads from
56
+ `/parhelia/editor-bridge/v1/parhelia-bridge.js` on the Parhelia origin (`origin`, default `parheliaOrigin()`), which is named as
57
+ its parent; a `bridgeOrigin` (a CMS authoring host proxying Parhelia's routes) only serves it. `@parhelia/react` and
58
+ `@parhelia/astro` wrap both as components.
59
+
60
+ The editor loads its edit mode and its preview mode with the same request (`?parhelia=1`, and a CMS preview flag such as
61
+ `?preview=1`), so the head's server cannot tell them apart. The document can: while the editing bridge runs, the root
62
+ element names the editor's mode, `<html data-parhelia-editor-mode="edit|preview|suggestions">`, set as soon as the bridge
63
+ runs and updated in place when the person switches modes. Outside the editor's frames it is absent. Scope what only editing
64
+ shows (an empty field's hint, the box that makes an empty field clickable) to it, and preview shows the page as visitors see
65
+ it:
66
+
67
+ ```css
68
+ html[data-parhelia-editor-mode]:not([data-parhelia-editor-mode="preview"]) [data-empty-hint]:empty::before {
69
+ content: attr(data-empty-hint);
70
+ opacity: 0.45;
71
+ }
72
+ /* preview: the empty element takes no space, as on the published page */
73
+ html[data-parhelia-editor-mode="preview"] [data-empty-hint]:empty {
74
+ display: none;
75
+ }
76
+ ```
77
+
78
+ `PARHELIA_EDITING_SELECTOR` is that selector (edit and suggestions mode) and `PARHELIA_EDITOR_MODE_ATTRIBUTE` the attribute,
79
+ for CSS-in-JS. The same marker is set on every head that loads the bridge, whatever loads it (`ParheliaBridge`, Parhelia's
80
+ proxy, the Umbraco package, the Magnolia connector). See
81
+ [Render empty components in edit mode](../../../docs/integration/render-empty-components.md).
82
+
83
+ ## Empty slots
84
+
85
+ A slot's rendering (a reference-array field such as a page's `topSection`) is marked for the editor in Parhelia's frames, also
86
+ when it holds nothing, so the canvas offers a drop zone for it: an inert `<script>` with `slotStartAttributes(name,
87
+ description)` before the slot's content, one with `slotEndAttributes(name)` after it, and for an empty slot a block with
88
+ `emptySlotAttributes(name)` and a `min-height` (`EMPTY_SLOT_MIN_HEIGHT`) between them. `ParheliaSlot` of `@parhelia/react` and
89
+ `@parhelia/astro` renders exactly that.
90
+
91
+ ## What a render shows: `@parhelia/head/identity`
92
+
93
+ Parhelia's capture (agent screenshots, DOM captures, component thumbnails) only captures a document whose renderer states
94
+ what it rendered. In Parhelia's frames (`?parhelia=1`, `isParheliaFrameRequest`) render one inert script from the data
95
+ the page itself read, never from the request's query:
96
+
97
+ ```tsx
98
+ // getServerSideProps (or a server component): the entry this render shows, by its own id
99
+ import { parheliaStore, renderedIdentityScriptProps } from '@parhelia/head/identity';
100
+ const identity = { store: parheliaStore(), itemId: page.sys.id, language: locale };
101
+
102
+ // the page
103
+ <script {...renderedIdentityScriptProps(identity)} />
104
+ ```
105
+
106
+ | Part | Value |
107
+ |---|---|
108
+ | `store` | the Parhelia store the head renders: `PARHELIA_STORE` (e.g. `contentful:<space>/<concrete environment>`) |
109
+ | `itemId` | the item's id as its CMS spells it: a Contentful entry's `sys.id`, a Sitecore item's Guid |
110
+ | `language` | the locale rendered |
111
+ | `version` | the version rendered where the CMS keeps numbered versions; omitted for Contentful |
112
+
113
+ A pages-router head can let `frameRenderedIdentity` do the gating: it answers the identity in Parhelia's frames and null
114
+ elsewhere, when the render produced no item, or when `PARHELIA_STORE` is unset (the server log says so once):
115
+
116
+ ```tsx
117
+ // getServerSideProps
118
+ import { frameRenderedIdentity } from '@parhelia/head';
119
+ return { props: { ..., parheliaIdentity: frameRenderedIdentity(query, { itemId: page?.sys.id, language: locale }) } };
120
+
121
+ // _app.tsx
122
+ {pageProps.parheliaIdentity && <script {...renderedIdentityScriptProps(pageProps.parheliaIdentity)} />}
123
+ ```
124
+
125
+ The Contentful Marketing starter does exactly this (P7, `docs/migration/w12-cfsite-starter-changes.md`). Settings ›
126
+ Rendering Hosts › the head's settings lists the `PARHELIA_STORE` line for a head of a Contentful mount.
127
+
128
+ The module imports nothing (no React, no Next.js), so a head that links this package from a checkout never resolves a
129
+ second React through it; `renderedIdentityScriptHtml` writes the same script as HTML. Without the script a capture is
130
+ refused with "the rendered document did not confirm the exact store, item, locale, and version".
131
+
132
+ ## Is this the editor? `@parhelia/head/server`
133
+
134
+ `?parhelia=1` says which editor request a request is, never whether it is one: a visitor can type it. A head's server
135
+ decides with `isEditingRequest` before it renders markers, empty components or the identity script:
136
+
137
+ ```ts
138
+ // getServerSideProps (Pages Router); a route handler or server component passes the Request / headers() and searchParams
139
+ import { isEditingRequest } from '@parhelia/head/server';
140
+ import { readPreviewSessionFor } from '@parhelia/preview-ticket/next';
141
+
142
+ const session = await readPreviewSessionFor(req, res);
143
+ const edit = isEditingRequest(req, query, session !== null);
144
+ ```
145
+
146
+ A fetch-handler server (TanStack Start, React Router, Hono) passes its Web `Request` and reads the session with
147
+ `@parhelia/preview-ticket/fetch`:
148
+
149
+ ```ts
150
+ import { isEditingRequest } from '@parhelia/head/server';
151
+ import { readPreviewSession } from '@parhelia/preview-ticket/fetch';
152
+
153
+ const session = await readPreviewSession(request);
154
+ const edit = isEditingRequest(request, query, session !== null);
155
+ ```
156
+
157
+ It is true for one of Parhelia's frames (`parhelia=1`, which every edit URL the editor builds carries) that either carries the rendering proxy's
158
+ `X-Parhelia-Editor` header equal to `PARHELIA_EDITOR_SECRET` (the host entry's `editorSecret=`; the proxy drops whatever the
159
+ browser sent under that name) or has a live per-person preview session (`@parhelia/preview-ticket`). No secret configured and
160
+ no session: never the editor. `hasEditorSignal(request)` and `editorSignalAccepted(value, secret)` are the parts; the
161
+ comparison is constant-time and runs on Node and the Edge alike.
162
+
163
+ ## CMS rich text: `@parhelia/head/rich-text`
164
+
165
+ Below Parhelia's rendering proxy the head is served from the editor's origin, so a script, event handler or `javascript:` link
166
+ in a stored rich-text value would run with the editing person's session. Write CMS rich text only through
167
+ `sanitizeRichTextHtml`:
168
+
169
+ ```tsx
170
+ import { sanitizeRichTextHtml } from '@parhelia/head/rich-text';
171
+
172
+ <div {...fieldMarkers} dangerouslySetInnerHTML={{ __html: sanitizeRichTextHtml(storedHtml) }} />;
173
+ ```
174
+
175
+ It keeps formatting (headings, paragraphs, lists, tables, links, images, quotes, a fixed set of style properties) and Parhelia's
176
+ own placeholder and internal-link markers; it removes scripts, styles, frames, objects, forms' lists, SVG and MathML with their
177
+ content, every event handler, other `data-*` attributes, URLs other than `http(s)`, `mailto`, `tel` (an image also raster
178
+ `data:image/…`, a link also `parhelia:`), and ids that would shadow a page global. It needs no DOM (a server component,
179
+ `getServerSideProps`) and no dependency. The editing bridge applies the same rule (`richTextElementAction`,
180
+ `sanitizeRichTextAttribute`) to the values it writes into the canvas.
181
+
182
+ ## In-place refresh
183
+
184
+ The editor calls `window.requestRefresh(newUri?)` after a save. `installParheliaRefresh({ refetch, signature, deadlineMs })`
185
+ installs it: `refetch` reads the page again the head's way, `signature()` is a stable string of what the page rendered, and the
186
+ loop reads again once a second until it changed and settled, or the deadline passed. The answer removes it again.
187
+ `useParheliaRefresh` of `@parhelia/react` is the React hook around it. A head without a client framework uses
188
+ `installParheliaDomRefresh()`: it reads the page again and patches what changed into the live document, keeping every node the
189
+ new render left alone (and what the editing bridge added to it), inside the element marked `data-parhelia-refresh-root`;
190
+ `ParheliaRefresh` of `@parhelia/astro` renders that element and installs it.
191
+
192
+ ## See also
193
+
194
+ - [Render empty components in edit mode](../../../docs/integration/render-empty-components.md): a recommendation (never a
195
+ requirement) so that an empty component is on the canvas and editable in place.
package/package.json CHANGED
@@ -1,6 +1,121 @@
1
1
  {
2
2
  "name": "@parhelia/head",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.12903",
4
+ "description": "Make a rendering head editable in Parhelia, on any framework and without one: the editing bridge, slot markers, the in-place refresh (with a DOM-patching one for heads without a client framework), the rendered-content identity capture reads, the editor signal a head's server checks (/server), rich-text sanitising (/rich-text), per-CMS marker helpers (/contentful, /umbraco, /magnolia, /typo3), the build values and the Vite build adapter (/vite). No React: React heads add @parhelia/react, Next.js heads @parhelia/next, Astro heads @parhelia/astro.",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "type": "module",
10
+ "main": "./src/index.js",
11
+ "types": "./src/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./src/index.d.ts",
15
+ "default": "./src/index.js"
16
+ },
17
+ "./server": {
18
+ "types": "./src/server.d.ts",
19
+ "default": "./src/server.js"
20
+ },
21
+ "./identity": {
22
+ "types": "./src/identity.d.ts",
23
+ "default": "./src/identity.js"
24
+ },
25
+ "./refresh": {
26
+ "types": "./src/refresh.d.ts",
27
+ "default": "./src/refresh.js"
28
+ },
29
+ "./rich-text": {
30
+ "types": "./src/rich-text.d.ts",
31
+ "default": "./src/rich-text.js"
32
+ },
33
+ "./contentful": {
34
+ "types": "./src/contentful.d.ts",
35
+ "default": "./src/contentful.js"
36
+ },
37
+ "./umbraco": {
38
+ "types": "./src/umbraco.d.ts",
39
+ "default": "./src/umbraco.js"
40
+ },
41
+ "./magnolia": {
42
+ "types": "./src/magnolia.d.ts",
43
+ "default": "./src/magnolia.js"
44
+ },
45
+ "./typo3": {
46
+ "types": "./src/typo3.d.ts",
47
+ "default": "./src/typo3.js"
48
+ },
49
+ "./vite": {
50
+ "types": "./src/vite.d.ts",
51
+ "default": "./src/vite.js"
52
+ },
53
+ "./settings": {
54
+ "types": "./src/settings.d.cts",
55
+ "default": "./src/settings.cjs"
56
+ }
57
+ },
58
+ "typesVersions": {
59
+ "*": {
60
+ "server": [
61
+ "./src/server.d.ts"
62
+ ],
63
+ "identity": [
64
+ "./src/identity.d.ts"
65
+ ],
66
+ "refresh": [
67
+ "./src/refresh.d.ts"
68
+ ],
69
+ "rich-text": [
70
+ "./src/rich-text.d.ts"
71
+ ],
72
+ "contentful": [
73
+ "./src/contentful.d.ts"
74
+ ],
75
+ "umbraco": [
76
+ "./src/umbraco.d.ts"
77
+ ],
78
+ "magnolia": [
79
+ "./src/magnolia.d.ts"
80
+ ],
81
+ "typo3": [
82
+ "./src/typo3.d.ts"
83
+ ],
84
+ "vite": [
85
+ "./src/vite.d.ts"
86
+ ],
87
+ "settings": [
88
+ "./src/settings.d.cts"
89
+ ]
90
+ }
91
+ },
92
+ "files": [
93
+ "src/*.js",
94
+ "src/*.cjs",
95
+ "src/*.d.ts",
96
+ "src/*.d.cts",
97
+ "README.md",
98
+ "LICENSE"
99
+ ],
100
+ "sideEffects": false,
101
+ "scripts": {
102
+ "check-types": "tsc --noEmit -p tsconfig.json",
103
+ "test": "vitest run"
104
+ },
105
+ "peerDependencies": {
106
+ "vite": ">=5"
107
+ },
108
+ "peerDependenciesMeta": {
109
+ "vite": {
110
+ "optional": true
111
+ }
112
+ },
113
+ "devDependencies": {
114
+ "@types/node": "*",
115
+ "@types/react": "19.2.18",
116
+ "jsdom": "^30.0.1",
117
+ "typescript": "npm:@typescript/typescript6@6.0.2",
118
+ "vitest": "^4.1.11",
119
+ "vite": "*"
120
+ }
121
+ }
@@ -0,0 +1,97 @@
1
+ /** The script's `crossorigin` and `referrerpolicy` values (as the DOM spells them). */
2
+ export type ParheliaBridgeCrossOrigin = "" | "anonymous" | "use-credentials";
3
+ export type ParheliaBridgeReferrerPolicy =
4
+ | ""
5
+ | "no-referrer"
6
+ | "no-referrer-when-downgrade"
7
+ | "origin"
8
+ | "origin-when-cross-origin"
9
+ | "same-origin"
10
+ | "strict-origin"
11
+ | "strict-origin-when-cross-origin"
12
+ | "unsafe-url";
13
+
14
+ export declare const PARHELIA_BRIDGE_PATH: "/parhelia/editor-bridge/v1/parhelia-bridge.js";
15
+
16
+ /** The frame-mode marker the bridge keeps on the framed document's root: the editor's mode (edit, preview, suggestions). */
17
+ export declare const PARHELIA_EDITOR_MODE_ATTRIBUTE: "data-parhelia-editor-mode";
18
+
19
+ /** The selector of a document the editor is editing in (edit or suggestions mode); scope editing-only styling to it. */
20
+ export declare const PARHELIA_EDITING_SELECTOR: 'html[data-parhelia-editor-mode]:not([data-parhelia-editor-mode="preview"])';
21
+
22
+ export type ParheliaBridgeSearchParams = URLSearchParams | Record<string, string | string[] | null | undefined>;
23
+
24
+ /** Which requests are the editor's. */
25
+ export interface ParheliaBridgeActivationOptions {
26
+ /** Decides alone when given, instead of the query. */
27
+ enabled?: boolean;
28
+ /** The frame-URL marker the editor adds (default `parhelia`). */
29
+ queryParam?: string;
30
+ /** Its value (default `1`); `null` accepts any value. */
31
+ queryValue?: string | null;
32
+ /** The request's URL, when no `searchParams` are given. */
33
+ requestUrl?: string | URL;
34
+ /** The request's query (a page's `searchParams`); without it and `requestUrl`, the browser's URL. */
35
+ searchParams?: ParheliaBridgeSearchParams;
36
+ }
37
+
38
+ /** Where the bridge loads from, and the script's own attributes. */
39
+ export interface ParheliaBridgeScriptOptions {
40
+ /**
41
+ * The Parhelia editor origin (default: `parheliaOrigin()`, the build's `PARHELIA_ORIGIN`, unless `bridgeOrigin` is
42
+ * given). The bridge loads from it and treats it as its only parent.
43
+ */
44
+ origin?: string;
45
+ /** Same as `origin` (the name `@parhelia/editor-bridge-react` used). */
46
+ parheliaOrigin?: string;
47
+ /**
48
+ * The origin serving the bridge when it is not the editor itself (e.g. a CMS's authoring host that proxies Parhelia);
49
+ * never named as the bridge's parent. Default: `PARHELIA_BRIDGE_ORIGIN`, then `NEXT_PUBLIC_PARHELIA_BRIDGE_ORIGIN`.
50
+ */
51
+ bridgeOrigin?: string;
52
+ id?: string;
53
+ /** The response's CSP nonce. */
54
+ nonce?: string;
55
+ async?: boolean;
56
+ defer?: boolean;
57
+ crossOrigin?: ParheliaBridgeCrossOrigin;
58
+ integrity?: string;
59
+ referrerPolicy?: ParheliaBridgeReferrerPolicy;
60
+ }
61
+
62
+ export type ParheliaBridgeScriptProps = ParheliaBridgeActivationOptions & ParheliaBridgeScriptOptions;
63
+
64
+ /** The attributes of the bridge's `<script>`. */
65
+ export interface ParheliaBridgeScriptAttributes {
66
+ id?: string;
67
+ src: string;
68
+ async: boolean;
69
+ defer: boolean;
70
+ nonce?: string;
71
+ crossOrigin?: ParheliaBridgeCrossOrigin;
72
+ integrity?: string;
73
+ referrerPolicy?: ParheliaBridgeReferrerPolicy;
74
+ "data-parhelia-editor-bridge": "runtime";
75
+ /** The Parhelia origin when it serves the bridge; absent for a bridge origin. */
76
+ "data-parhelia-parent-origin"?: string;
77
+ }
78
+
79
+ /** The bridge's URL on `origin`; without one, on the Parhelia origin, then on the environment's bridge origin. */
80
+ export declare function resolveParheliaBridgeUrl(origin?: string): string | undefined;
81
+
82
+ /** Whether the request is one of the editor's (`?parhelia=1`); `enabled` decides alone when given. Framing is not looked at. */
83
+ export declare function shouldRenderParheliaBridgeScript(options?: ParheliaBridgeActivationOptions): boolean;
84
+
85
+ /** The bridge script's attributes, or null without an origin to load it from. */
86
+ export declare function parheliaBridgeScriptProps(options?: ParheliaBridgeScriptOptions): ParheliaBridgeScriptAttributes | null;
87
+
88
+ /** Whether this document should load the bridge: in a frame of another origin, on the editor's `?parhelia=1` URL. */
89
+ export declare function shouldLoadParheliaBridge(queryParam?: string): boolean;
90
+
91
+ export interface ParheliaBridgeLoadOptions extends Omit<ParheliaBridgeScriptOptions, "async" | "defer"> {
92
+ /** The frame-URL marker the editor adds (default `parhelia`, value `1`). */
93
+ queryParam?: string;
94
+ }
95
+
96
+ /** Adds the bridge's script when the editor frames this document directly and it has none yet; answers whether it did. */
97
+ export declare function loadParheliaBridge(options?: ParheliaBridgeLoadOptions): boolean;
@@ -0,0 +1,173 @@
1
+ /**
2
+ * The editing bridge without a framework: its URL and `<script>` attributes, whether a request or a document is one of
3
+ * the editor's, and `loadParheliaBridge`, which adds the script in the browser. `ParheliaBridgeScript` and `ParheliaBridge` of
4
+ * `@parhelia/react` are React's two ways to use it; a head without React (Astro, plain HTML) uses these directly.
5
+ */
6
+ import { parheliaOrigin } from "./env.js";
7
+
8
+ export const PARHELIA_BRIDGE_PATH = "/parhelia/editor-bridge/v1/parhelia-bridge.js";
9
+
10
+ /**
11
+ * The frame-mode marker: while the bridge runs, the framed document's root names the editor's mode
12
+ * (`<html data-parhelia-editor-mode="edit|preview|suggestions">`), kept current in place when the person switches modes.
13
+ * Outside the editor's frames it is absent. A request's own flags (`?preview=1`, `?parhelia=1`) are the same in edit and
14
+ * preview mode; this marker is how a head's CSS tells them apart.
15
+ */
16
+ export const PARHELIA_EDITOR_MODE_ATTRIBUTE = "data-parhelia-editor-mode";
17
+
18
+ /**
19
+ * The selector of a document the editor is editing in (edit or suggestions mode, never preview, never outside the editor).
20
+ * Scope editing-only styling to it, such as an empty field's hint and box:
21
+ * `html[data-parhelia-editor-mode]:not([data-parhelia-editor-mode="preview"]) [data-empty-hint]:empty::before`.
22
+ */
23
+ export const PARHELIA_EDITING_SELECTOR = 'html[data-parhelia-editor-mode]:not([data-parhelia-editor-mode="preview"])';
24
+
25
+ /** @param {() => string | undefined} value */
26
+ const read = (value) => {
27
+ try {
28
+ return value() || "";
29
+ } catch {
30
+ return ""; // no `process` in this bundle and nothing inlined
31
+ }
32
+ };
33
+
34
+ /**
35
+ * The origin serving the bridge when it is not the editor (a CMS's authoring host that proxies Parhelia's routes):
36
+ * `PARHELIA_BRIDGE_ORIGIN`, then the public `NEXT_PUBLIC_PARHELIA_BRIDGE_ORIGIN`.
37
+ */
38
+ const bridgeOriginFromEnvironment = () =>
39
+ read(() => process.env.PARHELIA_BRIDGE_ORIGIN) || read(() => process.env.NEXT_PUBLIC_PARHELIA_BRIDGE_ORIGIN);
40
+
41
+ /**
42
+ * The bridge's URL on `origin`; without one, on the Parhelia origin, then on the environment's bridge origin.
43
+ * @param {string} [origin]
44
+ */
45
+ export function resolveParheliaBridgeUrl(origin) {
46
+ origin ||= parheliaOrigin() || bridgeOriginFromEnvironment();
47
+ if (!origin) return undefined;
48
+ try {
49
+ return new URL(PARHELIA_BRIDGE_PATH, origin).toString();
50
+ } catch {
51
+ return undefined;
52
+ }
53
+ }
54
+
55
+ /**
56
+ * @param {import("./bridge-core.js").ParheliaBridgeSearchParams | undefined} searchParams
57
+ * @param {string | URL | undefined} requestUrl
58
+ */
59
+ function resolveSearchParams(searchParams, requestUrl) {
60
+ if (searchParams instanceof URLSearchParams) return searchParams;
61
+ if (searchParams) {
62
+ const params = new URLSearchParams();
63
+ for (const [key, value] of Object.entries(searchParams)) {
64
+ if (Array.isArray(value)) for (const entry of value) params.append(key, entry);
65
+ else if (value !== undefined && value !== null) params.append(key, value);
66
+ }
67
+ return params;
68
+ }
69
+ if (requestUrl) {
70
+ try {
71
+ return new URL(requestUrl).searchParams;
72
+ } catch {
73
+ return new URL(requestUrl, "http://parhelia.local").searchParams;
74
+ }
75
+ }
76
+ if (typeof window !== "undefined") return new URLSearchParams(window.location.search);
77
+ return undefined;
78
+ }
79
+
80
+ /**
81
+ * Whether the request is one of the editor's (`?parhelia=1`): from `searchParams`, else `requestUrl`, else (in the
82
+ * browser) the document's URL. `enabled` decides alone when given. Framing is not looked at (`shouldLoadParheliaBridge`).
83
+ * @param {import("./bridge-core.js").ParheliaBridgeActivationOptions} [options]
84
+ */
85
+ export function shouldRenderParheliaBridgeScript({
86
+ enabled,
87
+ queryParam = "parhelia",
88
+ queryValue = "1",
89
+ requestUrl,
90
+ searchParams,
91
+ } = {}) {
92
+ if (enabled !== undefined) return enabled;
93
+ const params = resolveSearchParams(searchParams, requestUrl);
94
+ if (!params || !params.has(queryParam)) return false;
95
+ if (queryValue === null) return true;
96
+ return params.getAll(queryParam).some((value) => value === queryValue);
97
+ }
98
+
99
+ /**
100
+ * The bridge script's attributes, or null without an origin to load it from. The Parhelia origin (`origin`, else
101
+ * `parheliaOrigin()` unless a `bridgeOrigin` is given) serves the bridge and is named as its parent: an HTTPS editor
102
+ * framing an HTTP head sends no referrer to derive the parent from. A bridge origin (`bridgeOrigin`, else
103
+ * `PARHELIA_BRIDGE_ORIGIN` / `NEXT_PUBLIC_PARHELIA_BRIDGE_ORIGIN`) only serves it and is never named as the parent: the
104
+ * bridge keeps deriving its parent from the referrer. The origins come from trusted configuration, never from the request.
105
+ * @param {import("./bridge-core.js").ParheliaBridgeScriptOptions} [options]
106
+ */
107
+ export function parheliaBridgeScriptProps({
108
+ origin,
109
+ parheliaOrigin: originAlias,
110
+ bridgeOrigin,
111
+ id,
112
+ nonce,
113
+ async = false,
114
+ defer = true,
115
+ crossOrigin,
116
+ integrity,
117
+ referrerPolicy,
118
+ } = {}) {
119
+ const editorOrigin = origin || originAlias || (bridgeOrigin ? "" : parheliaOrigin());
120
+ const src = resolveParheliaBridgeUrl(editorOrigin || bridgeOrigin);
121
+ if (!src) return null;
122
+ return {
123
+ id,
124
+ src,
125
+ async,
126
+ defer,
127
+ nonce,
128
+ crossOrigin,
129
+ integrity,
130
+ referrerPolicy,
131
+ "data-parhelia-editor-bridge": "runtime",
132
+ "data-parhelia-parent-origin": editorOrigin ? new URL(src).origin : undefined,
133
+ };
134
+ }
135
+
136
+ const sameOriginParent = () => {
137
+ try {
138
+ return window.parent.location.origin === window.location.origin;
139
+ } catch {
140
+ return false;
141
+ }
142
+ };
143
+
144
+ /** Whether this document should load the bridge: in a frame of another origin, on the editor's `?parhelia=1` URL. */
145
+ export function shouldLoadParheliaBridge(queryParam = "parhelia") {
146
+ if (typeof window === "undefined" || window.parent === window || sameOriginParent()) return false;
147
+ return shouldRenderParheliaBridgeScript({ queryParam });
148
+ }
149
+
150
+ /**
151
+ * Adds the bridge's script to the document when the editor frames it directly (`shouldLoadParheliaBridge`) and the
152
+ * document has none yet. Answers whether it added one. Call it after the page's own markup is in place.
153
+ * @param {import("./bridge-core.js").ParheliaBridgeLoadOptions} [options]
154
+ */
155
+ export function loadParheliaBridge({ queryParam = "parhelia", ...options } = {}) {
156
+ if (!shouldLoadParheliaBridge(queryParam)) return false;
157
+ if (document.querySelector("script[data-parhelia-editor-bridge]")) return false;
158
+ const props = parheliaBridgeScriptProps(options);
159
+ if (!props) return false;
160
+ const script = document.createElement("script");
161
+ script.src = props.src;
162
+ script.async = true;
163
+ if (props.id) script.id = props.id;
164
+ if (props.nonce) script.nonce = props.nonce;
165
+ if (props.crossOrigin !== undefined) script.crossOrigin = props.crossOrigin;
166
+ if (props.integrity) script.integrity = props.integrity;
167
+ if (props.referrerPolicy) script.referrerPolicy = props.referrerPolicy;
168
+ script.setAttribute("data-parhelia-editor-bridge", props["data-parhelia-editor-bridge"]);
169
+ const parent = props["data-parhelia-parent-origin"];
170
+ if (parent) script.setAttribute("data-parhelia-parent-origin", parent);
171
+ document.body.appendChild(script);
172
+ return true;
173
+ }
@@ -0,0 +1,5 @@
1
+ /** The origins of Contentful's own web app. */
2
+ export declare const CONTENTFUL_APP_ORIGINS: readonly string[];
3
+
4
+ /** The `targetOrigin` list for `ContentfulLivePreviewProvider`: Contentful's app, this page's origin, Parhelia's. */
5
+ export declare function contentfulLivePreviewOrigins(): string[];
@@ -0,0 +1,28 @@
1
+ /**
2
+ * `@parhelia/head/contentful` — a Contentful head's helpers (Umbraco program thirdcms-frontend: the vendor's own entry; the
3
+ * package root stays CMS-neutral. `@parhelia/next`'s root still re-exports these for heads built before the entry existed,
4
+ * until @parhelia/next 2.0).
5
+ */
6
+ import { parheliaOrigin } from "./env.js";
7
+
8
+ /** The origins of Contentful's own web app, whose Live Preview keeps working. */
9
+ export const CONTENTFUL_APP_ORIGINS = Object.freeze(["https://app.contentful.com", "https://app.eu.contentful.com"]);
10
+
11
+ /** @type {string[] | undefined} */
12
+ let browserOrigins;
13
+
14
+ /**
15
+ * The `targetOrigin` list for Contentful's `ContentfulLivePreviewProvider`: Contentful's own app, the page's own origin
16
+ * (the editor frames a proxied head from its own origin) and the configured Parhelia origin (a head the editor frames
17
+ * directly). Computed in the browser, so moving the editor needs no rebuild of a proxied head. Without a targetOrigin
18
+ * the SDK throws in every frame but Contentful's.
19
+ */
20
+ export function contentfulLivePreviewOrigins() {
21
+ const origins = [...CONTENTFUL_APP_ORIGINS];
22
+ if (typeof window === "undefined") return unique([...origins, parheliaOrigin()]);
23
+ // One array per page load: the provider sees the same value on every render.
24
+ return (browserOrigins ??= unique([...origins, window.location.origin, parheliaOrigin()]));
25
+ }
26
+
27
+ /** @param {string[]} values */
28
+ const unique = (values) => [...new Set(values.filter(Boolean))];
package/src/env.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /** Sets the origin and base path explicitly, for a framework whose build inlines nothing; wins over inlined values. */
2
+ export declare function configureParhelia(values: { origin?: string; basePath?: string }): void;
3
+
4
+ /** The Parhelia editor origin (`PARHELIA_ORIGIN`); "" when unset. */
5
+ export declare function parheliaOrigin(): string;
6
+
7
+ /** The head's base path below the rendering proxy (`PARHELIA_BASE_PATH`); "" when none. */
8
+ export declare function parheliaBasePath(): string;
9
+
10
+ /** A root-relative path below the head's basePath. */
11
+ export declare function withBasePath(path: string): string;