@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/src/env.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The two values of a head's build that the browser needs as much as the server: the base path below Parhelia's
3
+ * rendering proxy (`PARHELIA_BASE_PATH`) and the Parhelia editor's origin (`PARHELIA_ORIGIN`). A server render and
4
+ * hydration must read the same values, so they come from the build, not from the server's environment:
5
+ *
6
+ * - Next.js: `withParhelia` (`@parhelia/next/config`) puts them into `env`, which Next.js inlines.
7
+ * - Vite (TanStack Start, React Router, …): the `parhelia()` plugin (`@parhelia/head/vite`, used by `@parhelia/astro` too) defines them.
8
+ * - Anything else: call `configureParhelia({ origin, basePath })` in a module both the server and the browser load.
9
+ *
10
+ * The reads are literal `process.env.X` expressions, which is what a bundler's inlining replaces.
11
+ */
12
+
13
+ /** @type {{ origin?: string, basePath?: string }} */
14
+ let configured = {};
15
+
16
+ /** @param {() => string | undefined} value */
17
+ const read = (value) => {
18
+ try {
19
+ return value() || "";
20
+ } catch {
21
+ return ""; // no `process` in this bundle and nothing inlined
22
+ }
23
+ };
24
+
25
+ /**
26
+ * Sets the values explicitly, for a framework whose build inlines nothing. A value given here wins over the inlined one.
27
+ * @param {{ origin?: string, basePath?: string }} values
28
+ */
29
+ export function configureParhelia(values) {
30
+ const origin = values.origin === undefined ? undefined : String(values.origin).trim().replace(/\/+$/, "");
31
+ const basePath = values.basePath === undefined ? undefined : String(values.basePath).trim().replace(/\/+$/, "");
32
+ configured = {
33
+ ...configured,
34
+ ...(origin === undefined ? {} : { origin }),
35
+ ...(basePath === undefined ? {} : { basePath }),
36
+ };
37
+ }
38
+
39
+ /** The Parhelia editor origin (`PARHELIA_ORIGIN`); "" when unset. */
40
+ export const parheliaOrigin = () => configured.origin ?? read(() => process.env.PARHELIA_ORIGIN);
41
+
42
+ /** The head's base path below the rendering proxy (`PARHELIA_BASE_PATH`); "" when none. */
43
+ export const parheliaBasePath = () => configured.basePath ?? read(() => process.env.PARHELIA_BASE_PATH);
44
+
45
+ /** A root-relative path below the head's basePath: `fetch(withBasePath("/api/content"))`. */
46
+ /** @param {string} path */
47
+ export const withBasePath = (path) => `${parheliaBasePath()}${path.startsWith("/") ? path : `/${path}`}`;
@@ -0,0 +1,45 @@
1
+ /** The attribute of the inert JSON script that states what a render produced. */
2
+ export declare const RENDERED_IDENTITY_ATTRIBUTE: "data-parhelia-rendered-coordinate";
3
+
4
+ /**
5
+ * What THIS render produced, as the head's own data names it: the Parhelia store the head renders, the item's id as its
6
+ * CMS spells it (a Contentful entry's `sys.id`, a Sitecore item's Guid), the locale, and the version where the CMS keeps
7
+ * numbered versions (omitted where it keeps none).
8
+ */
9
+ export interface RenderedIdentity {
10
+ store: string;
11
+ itemId: string;
12
+ language: string;
13
+ version?: number;
14
+ }
15
+
16
+ /** The Parhelia store this head renders (`PARHELIA_STORE`), trimmed; "" when unset. Server-side. */
17
+ export declare function parheliaStore(): string;
18
+
19
+ /** The identity as HTML-escaped inert JSON. Throws a TypeError for a blank part or an invalid version. */
20
+ export declare function renderedIdentityJson(identity: RenderedIdentity): string;
21
+
22
+ /** The props of a React `<script>` that states the identity: `<script {...renderedIdentityScriptProps(identity)} />`. */
23
+ export declare function renderedIdentityScriptProps(identity: RenderedIdentity): {
24
+ type: "application/json";
25
+ "data-parhelia-rendered-coordinate": "";
26
+ dangerouslySetInnerHTML: { __html: string };
27
+ };
28
+
29
+ /** The script element as HTML, for a head that writes its markup itself. */
30
+ export declare function renderedIdentityScriptHtml(identity: RenderedIdentity): string;
31
+
32
+ /**
33
+ * The identity a render states, or null: in Parhelia's frames only, with the head's store (`PARHELIA_STORE`) and the ids
34
+ * of the data the page itself read. Null outside Parhelia's frames, when the render produced no item, and when the head
35
+ * names no store (logged once). Throws a TypeError for a malformed part.
36
+ */
37
+ export declare function frameRenderedIdentity(
38
+ query: URLSearchParams | Record<string, string | string[] | undefined> | null | undefined,
39
+ rendered: { itemId?: string | null; language?: string | null; version?: number },
40
+ ): RenderedIdentity | null;
41
+
42
+ /** Whether a request is one of Parhelia's frames (`parhelia=1`): pages-router `query`, App Router `searchParams`, or URLSearchParams. */
43
+ export declare function isParheliaFrameRequest(
44
+ query: URLSearchParams | Record<string, string | string[] | undefined> | null | undefined,
45
+ ): boolean;
@@ -0,0 +1,137 @@
1
+ /**
2
+ * `@parhelia/head/identity` — the renderer-owned content identity (W11 A3 `w11-a3-capture-rendered-identity.md`, multi-cms
3
+ * capturemcms): the one inert JSON script `data-parhelia-rendered-coordinate` in which a head states the item THIS render
4
+ * produced. Parhelia's capture (agent screenshots, DOM captures, component thumbnails) reads it from the rendered document
5
+ * and refuses a document that does not state exactly the target it asked for.
6
+ *
7
+ * - `store`: the Parhelia store the head renders. A Contentful head is configured with it (`PARHELIA_STORE`, see
8
+ * `parheliaStore`): Parhelia names a space by its concrete environment, which an aliased environment does not show.
9
+ * - `itemId`: the item's id as its CMS spells it, from the data the head rendered: a Contentful entry's `sys.id`, a
10
+ * Sitecore item's Guid. Never the request's query or the editor's selection.
11
+ * - `language`: the locale the head rendered.
12
+ * - `version`: the version rendered, where the CMS keeps numbered versions (Sitecore); omitted where it keeps none
13
+ * (Contentful).
14
+ *
15
+ * No React and no Next.js import: any head can call it, and a head that links this package from a checkout (a `file:`
16
+ * dependency) never resolves a second React through it. Render the script only in Parhelia's frames
17
+ * (`isParheliaFrameRequest`), where the editor's capture reads it.
18
+ */
19
+
20
+ export const RENDERED_IDENTITY_ATTRIBUTE = "data-parhelia-rendered-coordinate";
21
+
22
+ /** @param {() => string | undefined} value */
23
+ const read = (value) => {
24
+ try {
25
+ return value() || "";
26
+ } catch {
27
+ return ""; // no `process` in this bundle
28
+ }
29
+ };
30
+
31
+ /**
32
+ * The Parhelia store this head renders (`PARHELIA_STORE`, e.g. `contentful:<space>/<environment>`), trimmed; "" when unset.
33
+ * Server-side: read it where the page's data is read (getServerSideProps, a server component) and hand the identity to
34
+ * the component that renders it, so the server's and the browser's render state the same.
35
+ */
36
+ export const parheliaStore = () => read(() => process.env.PARHELIA_STORE).trim();
37
+
38
+ /** @param {string} name @param {unknown} value */
39
+ const requireText = (name, value) => {
40
+ if (typeof value !== "string" || !value || value !== value.trim() || value.includes("\0")) {
41
+ throw new TypeError(`A rendered identity needs a non-empty ${name} without surrounding blanks; got ${JSON.stringify(value)}.`);
42
+ }
43
+ return value;
44
+ };
45
+
46
+ /**
47
+ * The identity as the inert JSON a `<script type="application/json">` carries, HTML-escaped so the script stays data
48
+ * whatever the values contain.
49
+ * @param {{ store: string, itemId: string, language: string, version?: number }} identity
50
+ * @returns {string}
51
+ */
52
+ export function renderedIdentityJson(identity) {
53
+ if (!identity || typeof identity !== "object") throw new TypeError("A rendered identity is an object.");
54
+ const { store, itemId, language, version } = identity;
55
+ if (version !== undefined && !(typeof version === "number" && Number.isInteger(version) && version >= 0)) {
56
+ throw new TypeError(`A rendered identity's version is a non-negative integer or absent; got ${JSON.stringify(version)}.`);
57
+ }
58
+ const coordinate = {
59
+ coordinateVersion: 1,
60
+ store: requireText("store", store),
61
+ itemId: requireText("itemId", itemId),
62
+ language: requireText("language", language),
63
+ ...(version === undefined ? {} : { version }),
64
+ };
65
+ return JSON.stringify(coordinate)
66
+ .replace(/</g, "\\u003c")
67
+ .replace(/>/g, "\\u003e")
68
+ .replace(/&/g, "\\u0026");
69
+ }
70
+
71
+ /**
72
+ * The props of a React `<script>` element that states the identity: `<script {...renderedIdentityScriptProps(identity)} />`.
73
+ * @param {{ store: string, itemId: string, language: string, version?: number }} identity
74
+ */
75
+ export function renderedIdentityScriptProps(identity) {
76
+ return {
77
+ type: "application/json",
78
+ [RENDERED_IDENTITY_ATTRIBUTE]: "",
79
+ dangerouslySetInnerHTML: { __html: renderedIdentityJson(identity) },
80
+ };
81
+ }
82
+
83
+ /**
84
+ * The script element as HTML, for a head that writes its markup itself.
85
+ * @param {{ store: string, itemId: string, language: string, version?: number }} identity
86
+ */
87
+ export function renderedIdentityScriptHtml(identity) {
88
+ return `<script type="application/json" ${RENDERED_IDENTITY_ATTRIBUTE}>${renderedIdentityJson(identity)}</script>`;
89
+ }
90
+
91
+ let warnedNoStore = false;
92
+
93
+ /**
94
+ * The identity a render states, or null: in Parhelia's frames (`isParheliaFrameRequest(query)`) only, with the head's
95
+ * store (`PARHELIA_STORE`) and the ids of the data the page itself read (`itemId`: the item's own id as its CMS spells
96
+ * it; `language`; `version` where the CMS keeps numbered versions). Null outside Parhelia's frames and when the render
97
+ * produced no item. In a frame of a head that names no store it is null too, and the server log says once why
98
+ * Parhelia's capture refuses the head's renders.
99
+ *
100
+ * For a pages-router head: call it in getServerSideProps, pass the result as a page prop, and render
101
+ * `<script {...renderedIdentityScriptProps(identity)} />` where it is not null.
102
+ * @param {URLSearchParams | Record<string, string | string[] | undefined> | null | undefined} query
103
+ * @param {{ itemId?: string | null, language?: string | null, version?: number }} rendered
104
+ * @returns {{ store: string, itemId: string, language: string, version?: number } | null}
105
+ */
106
+ export function frameRenderedIdentity(query, rendered) {
107
+ if (!isParheliaFrameRequest(query)) return null;
108
+ const itemId = rendered?.itemId;
109
+ const language = rendered?.language;
110
+ if (!itemId || !language) return null;
111
+ const store = parheliaStore();
112
+ if (!store) {
113
+ if (!warnedNoStore) {
114
+ warnedNoStore = true;
115
+ console.warn(
116
+ "@parhelia/head: PARHELIA_STORE is not set, so this head states no rendered identity and Parhelia's capture " +
117
+ "(agent screenshots, component thumbnails) refuses its renders. Set it to the store the head renders " +
118
+ "(Settings > Rendering Hosts > the head's settings).",
119
+ );
120
+ }
121
+ return null;
122
+ }
123
+ const identity = { store, itemId, language, ...(rendered.version === undefined ? {} : { version: rendered.version }) };
124
+ renderedIdentityJson(identity); // refuses a malformed part by name here, not later at render
125
+ return identity;
126
+ }
127
+
128
+ /**
129
+ * Whether a request is one of Parhelia's frames: the editor's canvas and its offscreen capture render with `parhelia=1`.
130
+ * Takes the pages router's `query`, the App Router's `searchParams` object, or a `URLSearchParams`.
131
+ * @param {URLSearchParams | Record<string, string | string[] | undefined> | null | undefined} query
132
+ */
133
+ export function isParheliaFrameRequest(query) {
134
+ if (!query) return false;
135
+ const value = typeof query.get === "function" ? query.get("parhelia") : /** @type {Record<string, unknown>} */ (query).parhelia;
136
+ return Array.isArray(value) ? value.length === 1 && value[0] === "1" : value === "1";
137
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./bridge-core.js";
2
+ export * from "./slot-markup.js";
3
+ export * from "./identity.js";
4
+ export { installParheliaRefresh } from "./refresh.js";
5
+ export * from "./refresh-dom.js";
6
+ export { configureParhelia, parheliaOrigin, parheliaBasePath, withBasePath } from "./env.js";
package/src/index.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `@parhelia/head` — what any rendering head needs to be edited in Parhelia, on any framework and without one (Astro, plain
3
+ * HTML, any server templating; React heads add `@parhelia/react`, Next.js heads `@parhelia/next`, Astro heads `@parhelia/astro`):
4
+ * the build's base path and origin, the editing bridge (its `<script>` attributes, `loadParheliaBridge` for the browser),
5
+ * the slot markers, the rendered-content identity and the in-place refresh. Server-only: `@parhelia/head/server`; a CMS's
6
+ * own markers: `@parhelia/head/<cms>`; rich text: `@parhelia/head/rich-text`. Nothing here imports React.
7
+ */
8
+ export * from "./bridge-core.js";
9
+ export * from "./slot-markup.js";
10
+ export * from "./identity.js";
11
+ export { installParheliaRefresh } from "./refresh.js";
12
+ export * from "./refresh-dom.js";
13
+ export { configureParhelia, parheliaOrigin, parheliaBasePath, withBasePath } from "./env.js";
@@ -0,0 +1,60 @@
1
+ /** One rendered field's identity, as a Magnolia render knows it. */
2
+ export type MgnlFieldRef = {
3
+ /** The node's workspace (`website`, `dam`, a content-type workspace). */
4
+ workspace: string;
5
+ /** The node's `jcr:uuid`. */
6
+ uuid: string;
7
+ /** The form field's name (the property it stores, without a locale suffix). */
8
+ property: string;
9
+ /** The rendered locale for a field stored per locale; null for a field every locale shares (`*`). */
10
+ locale: string | null;
11
+ /** The locale whose value is shown instead, when the node holds none in the rendered locale. */
12
+ fallbackFrom?: string | null;
13
+ /** The field's element holds rich text. */
14
+ richText?: boolean;
15
+ /** A composite's sub-field: the part it belongs to, `{anchor uuid}/{path}` (lane mg-structured). */
16
+ part?: string | null;
17
+ };
18
+
19
+ /** The vocabulary's wire name. */
20
+ export declare const MAGNOLIA_MARKER_VOCABULARY: "magnolia";
21
+ /** The entity kind of a field marker naming a node. */
22
+ export declare const MGNL_NODE_KIND: "node";
23
+ /** The entity kind of a field marker naming a structured field's part. */
24
+ export declare const MGNL_PART_KIND: "part";
25
+ export declare const MGNL_NODE_ATTRIBUTE: string;
26
+ export declare const MGNL_WORKSPACE_ATTRIBUTE: string;
27
+ export declare const MGNL_PROPERTY_ATTRIBUTE: string;
28
+ export declare const MGNL_LOCALE_ATTRIBUTE: string;
29
+ export declare const MGNL_FALLBACK_ATTRIBUTE: string;
30
+ export declare const MGNL_RICHTEXT_ATTRIBUTE: string;
31
+ export declare const MGNL_CONTENT_TYPE_ATTRIBUTE: string;
32
+ export declare const MGNL_PART_ATTRIBUTE: string;
33
+ /** The locale a field marker states for a field every locale shares. */
34
+ export declare const MGNL_SHARED_LOCALE: "*";
35
+ /** Parhelia addresses a Magnolia node as its current state. */
36
+ export declare const PARHELIA_MAGNOLIA_VERSION: "0";
37
+ /** The block an empty slot renders in an editing render: `ParheliaSlot`'s own. */
38
+ export { EMPTY_SLOT_ATTRIBUTE } from "./slot-markup.js";
39
+
40
+ /** The key of a node marker, `{workspace}:{uuid}`; undefined for a malformed workspace or uuid. */
41
+ export declare function mgnlNodeKey(workspace: string, uuid: string): string | undefined;
42
+ /** Reads a node key `{workspace}:{uuid}`; undefined when it is not one. */
43
+ export declare function parseMgnlNodeKey(key: string): { workspace: string; uuid: string } | undefined;
44
+ /** The key of a part marker, `{workspace}:{anchor uuid}/{path}`; undefined when it is not one. */
45
+ export declare function mgnlPartKey(workspace: string, part: string): string | undefined;
46
+ /** Reads a part key `{workspace}:{anchor uuid}/{path}`; undefined when it is not one. */
47
+ export declare function parseMgnlPartKey(key: string): { workspace: string; anchor: string; path: string } | undefined;
48
+ /** The field marker attributes of one rendered field; `{}` outside the editor. */
49
+ export declare function mgnlFieldAttributes(ref: MgnlFieldRef, edit: boolean): Record<string, string>;
50
+ /** The slot key of an area: `{areaName}_{OWNER-UUID}`. */
51
+ export declare function mgnlSlotKey(areaName: string, ownerUuid: string): string;
52
+ /** The attributes of a component's start sentinel, as the connector's classic editing render spells them. */
53
+ export declare function mgnlComponentStartAttributes(
54
+ uuid: string,
55
+ template: string | null | undefined,
56
+ language: string | null | undefined,
57
+ workspace?: string,
58
+ ): Record<string, string>;
59
+ /** The attributes of a component's end sentinel. */
60
+ export declare function mgnlComponentEndAttributes(uuid: string): Record<string, string>;
@@ -0,0 +1,199 @@
1
+ /**
2
+ * `@parhelia/head/magnolia` — **the Magnolia marker names, and the helpers a head renders them with** (Magnolia MG7a,
3
+ * plan MG-D11). This module is the one JavaScript source: the editor's `magnolia` vocabulary (`@parhelia/core`,
4
+ * `bridge/vocabularies/magnolia/`) reads them by importing this module, a headless Magnolia head (MG7b) renders them, the
5
+ * Parhelia connector inside Magnolia writes them in its editing renders (`FieldMarker`, `ComponentSentinel`,
6
+ * `SlotSentinel`), and the Magnolia store answers them (`Parhelia.Magnolia.Protocol.MarkerNames`, `NodeAddress`). All of
7
+ * them are pinned to one test vector, `magnolia.markers.json` beside this file: a renamed attribute fails a test in each
8
+ * language.
9
+ *
10
+ * Fields carry the **Magnolia vocabulary** (store-resolved: a render knows the node and the form field's name, never
11
+ * Parhelia's field ids, so the page's store answers which item and field a marker names):
12
+ *
13
+ * data-mgnl-node="<jcr:uuid>" data-mgnl-workspace="<workspace>" the node (entity kind `node`, key `{workspace}:{uuid}`)
14
+ * data-mgnl-property="<form field name>" the field (the property it stores, no locale suffix)
15
+ * data-mgnl-locale="<locale>" | "*" where an edit writes; `*` for a field every locale shares
16
+ * data-mgnl-fallback="<locale>" only when the value shown is that locale's (the node holds none in the render's locale)
17
+ * data-mgnl-richtext on a rich text field's element
18
+ * data-mgnl-part="<anchor uuid>/<path>" on a composite's sub-field (lane mg-structured): the part it belongs to, one in every
19
+ * locale (entity kind `part`, key `{workspace}:{anchor uuid}/{path}`); the node attribute still
20
+ * names the node that holds the value
21
+ *
22
+ * Components and slots use Parhelia's own sentinels: a component is a `data-component-start` / `-end` script pair carrying
23
+ * the component node's uuid (its Parhelia item id) and `data-mgnl-content-type` (its template); an area is the slot
24
+ * `{areaName}_{OWNER-UUID}` (the page or component owning the area, uppercase), an area without components carries the
25
+ * empty slot's block (`data-parhelia-empty-slot`).
26
+ *
27
+ * Markers appear in Parhelia's editing renders only; every other render is Magnolia's own markup.
28
+ */
29
+
30
+ /** The vocabulary's wire name: what the canvas sends with the markers it found, and what the Magnolia store states. */
31
+ export const MAGNOLIA_MARKER_VOCABULARY = "magnolia";
32
+
33
+ /** The entity kind of a field marker naming a JCR node. */
34
+ export const MGNL_NODE_KIND = "node";
35
+
36
+ /** The entity kind of a field marker naming a structured field's part (a composite, one in every locale; lane mg-structured). */
37
+ export const MGNL_PART_KIND = "part";
38
+
39
+ export const MGNL_NODE_ATTRIBUTE = "data-mgnl-node";
40
+ export const MGNL_WORKSPACE_ATTRIBUTE = "data-mgnl-workspace";
41
+ export const MGNL_PROPERTY_ATTRIBUTE = "data-mgnl-property";
42
+ export const MGNL_LOCALE_ATTRIBUTE = "data-mgnl-locale";
43
+ export const MGNL_FALLBACK_ATTRIBUTE = "data-mgnl-fallback";
44
+ export const MGNL_RICHTEXT_ATTRIBUTE = "data-mgnl-richtext";
45
+ export const MGNL_CONTENT_TYPE_ATTRIBUTE = "data-mgnl-content-type";
46
+ export const MGNL_PART_ATTRIBUTE = "data-mgnl-part";
47
+
48
+ /** The locale a field marker states for a field every locale shares. */
49
+ export const MGNL_SHARED_LOCALE = "*";
50
+
51
+ /** Parhelia addresses a Magnolia node as its current state (version 0). */
52
+ export const PARHELIA_MAGNOLIA_VERSION = "0";
53
+
54
+ /** The block an empty slot renders in an editing render (its value: the slot's key): `ParheliaSlot`'s own. */
55
+ export { EMPTY_SLOT_ATTRIBUTE } from "./slot-markup.js";
56
+
57
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
58
+ const WORKSPACE = /^[A-Za-z][A-Za-z0-9._-]*$/;
59
+
60
+ /**
61
+ * The key of a node marker, `{workspace}:{uuid}` (the uuid lowercase, as JCR spells it); undefined for a malformed workspace or
62
+ * uuid.
63
+ * @param {string} workspace
64
+ * @param {string} uuid
65
+ * @returns {string | undefined}
66
+ */
67
+ export const mgnlNodeKey = (workspace, uuid) =>
68
+ typeof workspace === "string" && typeof uuid === "string" && WORKSPACE.test(workspace) && UUID.test(uuid)
69
+ ? `${workspace}:${uuid.toLowerCase()}`
70
+ : undefined;
71
+
72
+ /**
73
+ * Reads a node key `{workspace}:{uuid}` (the last colon separates them); undefined when it is not one.
74
+ * @param {string} key
75
+ * @returns {{ workspace: string; uuid: string } | undefined}
76
+ */
77
+ export const parseMgnlNodeKey = key => {
78
+ if (typeof key !== "string") return undefined;
79
+ const colon = key.lastIndexOf(":");
80
+ if (colon <= 0) return undefined;
81
+ const workspace = key.slice(0, colon);
82
+ const uuid = key.slice(colon + 1);
83
+ return mgnlNodeKey(workspace, uuid) ? { workspace, uuid: uuid.toLowerCase() } : undefined;
84
+ };
85
+
86
+ const PART_SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
87
+
88
+ /**
89
+ * The key of a part marker, `{workspace}:{anchor uuid}/{path}` (the uuid lowercase; the path one or more field names joined by
90
+ * `/`), from the marker's workspace and its `data-mgnl-part` value; undefined when it is not one.
91
+ * @param {string} workspace
92
+ * @param {string} part
93
+ * @returns {string | undefined}
94
+ */
95
+ export const mgnlPartKey = (workspace, part) => {
96
+ if (typeof part !== "string") return undefined;
97
+ const slash = part.indexOf("/");
98
+ if (slash <= 0) return undefined;
99
+ const anchor = mgnlNodeKey(workspace, part.slice(0, slash));
100
+ const segments = part.slice(slash + 1).split("/");
101
+ if (!anchor || segments.some(segment => !PART_SEGMENT.test(segment) || segment === "..")) return undefined;
102
+ return `${anchor}/${segments.join("/")}`;
103
+ };
104
+
105
+ /**
106
+ * Reads a part key `{workspace}:{anchor uuid}/{path}` (as `mgnlPartKey` spells it); undefined when it is not one.
107
+ * @param {string} key
108
+ * @returns {{ workspace: string; anchor: string; path: string } | undefined}
109
+ */
110
+ export const parseMgnlPartKey = key => {
111
+ if (typeof key !== "string") return undefined;
112
+ const colon = key.indexOf(":");
113
+ if (colon <= 0) return undefined;
114
+ const workspace = key.slice(0, colon);
115
+ const rest = key.slice(colon + 1);
116
+ if (mgnlPartKey(workspace, rest) !== key) return undefined;
117
+ const slash = rest.indexOf("/");
118
+ return { workspace, anchor: rest.slice(0, slash), path: rest.slice(slash + 1) };
119
+ };
120
+
121
+ /**
122
+ * The field marker attributes of one rendered field; `{}` outside the editor. Throws for a malformed node or field name.
123
+ * @param {import("./magnolia.js").MgnlFieldRef} ref
124
+ * @param {boolean} edit
125
+ * @returns {Record<string, string>}
126
+ */
127
+ export const mgnlFieldAttributes = (ref, edit) => {
128
+ if (!edit) return {};
129
+ if (!mgnlNodeKey(ref.workspace, ref.uuid))
130
+ throw new TypeError(`A Magnolia field marker needs a workspace and a uuid; got ${JSON.stringify([ref.workspace, ref.uuid])}.`);
131
+ if (!ref.property) throw new TypeError("A Magnolia field marker needs the form field's name.");
132
+ const locale = ref.locale ?? MGNL_SHARED_LOCALE;
133
+ /** @type {Record<string, string>} */
134
+ const attributes = {
135
+ [MGNL_NODE_ATTRIBUTE]: ref.uuid.toLowerCase(),
136
+ [MGNL_WORKSPACE_ATTRIBUTE]: ref.workspace,
137
+ [MGNL_PROPERTY_ATTRIBUTE]: ref.property,
138
+ [MGNL_LOCALE_ATTRIBUTE]: locale,
139
+ };
140
+ if (ref.fallbackFrom && ref.fallbackFrom !== locale) attributes[MGNL_FALLBACK_ATTRIBUTE] = ref.fallbackFrom;
141
+ if (ref.part) {
142
+ if (!mgnlPartKey(ref.workspace, ref.part))
143
+ throw new TypeError(`A Magnolia part marker needs {anchor uuid}/{path}; got ${JSON.stringify(ref.part)}.`);
144
+ attributes[MGNL_PART_ATTRIBUTE] = ref.part;
145
+ }
146
+ if (ref.richText) attributes[MGNL_RICHTEXT_ATTRIBUTE] = "";
147
+ return attributes;
148
+ };
149
+
150
+ /**
151
+ * The slot key of an area: `{areaName}_{OWNER-UUID}` (the owning page's or component's uuid, uppercase).
152
+ * @param {string} areaName
153
+ * @param {string} ownerUuid
154
+ * @returns {string}
155
+ */
156
+ export const mgnlSlotKey = (areaName, ownerUuid) => {
157
+ if (!areaName) throw new TypeError("A slot key needs the area's name.");
158
+ if (!UUID.test(ownerUuid ?? "")) throw new TypeError(`A slot key needs the owner's uuid; got ${JSON.stringify(ownerUuid)}.`);
159
+ return `${areaName}_${ownerUuid.toUpperCase()}`;
160
+ };
161
+
162
+ /**
163
+ * The attributes of a component's start sentinel (an empty `<script>`), spelled as the connector's classic editing render writes
164
+ * them (`ComponentSentinel.start`): the component node's uuid as its key and item id, its template as its name and content type,
165
+ * its workspace, the rendered locale and the version Parhelia addresses (MG7b: a headless head renders the same sentinels).
166
+ * Throws for a malformed uuid or workspace.
167
+ * @param {string} uuid
168
+ * @param {string | null | undefined} template
169
+ * @param {string | null | undefined} language
170
+ * @param {string} [workspace]
171
+ * @returns {Record<string, string>}
172
+ */
173
+ export const mgnlComponentStartAttributes = (uuid, template, language, workspace = "website") => {
174
+ if (!mgnlNodeKey(workspace, uuid))
175
+ throw new TypeError(`A component sentinel needs a workspace and a uuid; got ${JSON.stringify([workspace, uuid])}.`);
176
+ const key = uuid.toLowerCase();
177
+ const type = template ?? "";
178
+ /** @type {Record<string, string>} */
179
+ const attributes = {
180
+ "data-component-start": key,
181
+ "data-itemid": key,
182
+ "data-component-name": type,
183
+ [MGNL_CONTENT_TYPE_ATTRIBUTE]: type,
184
+ [MGNL_WORKSPACE_ATTRIBUTE]: workspace,
185
+ };
186
+ if (language) attributes["data-language"] = language;
187
+ attributes["data-version"] = PARHELIA_MAGNOLIA_VERSION;
188
+ return attributes;
189
+ };
190
+
191
+ /**
192
+ * The attributes of a component's end sentinel (`ComponentSentinel.end`). Throws for a malformed uuid.
193
+ * @param {string} uuid
194
+ * @returns {Record<string, string>}
195
+ */
196
+ export const mgnlComponentEndAttributes = uuid => {
197
+ if (!UUID.test(uuid ?? "")) throw new TypeError(`A component sentinel needs the component's uuid; got ${JSON.stringify(uuid)}.`);
198
+ return { "data-component-end": uuid.toLowerCase() };
199
+ };
@@ -0,0 +1,9 @@
1
+ export declare const REFRESH_ROOT_ATTRIBUTE: "data-parhelia-refresh-root";
2
+ export declare const REFRESH_SIGNATURE_ATTRIBUTE: "data-parhelia-refresh-signature";
3
+ export declare const REFRESH_DEADLINE_ATTRIBUTE: "data-parhelia-refresh-deadline";
4
+
5
+ /** Patches `live` from the render it showed (`before`) to the new render (`after`), touching only what differs. */
6
+ export declare function patchRendered(live: Node, before: Node, after: Node): Node;
7
+
8
+ /** Installs `window.requestRefresh` for the document's refresh root (read again, patch in place); answers the uninstall. */
9
+ export declare function installParheliaDomRefresh(options?: { deadlineMs?: number }): () => void;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The in-place refresh for a head without a client framework (Astro, server-rendered HTML): `window.requestRefresh` reads the
3
+ * page again and patches what changed into the live document, as React's reconciliation does for a React head. Nodes the new
4
+ * render did not change stay the very same nodes, with whatever the editing bridge added to them (an inline edit in progress,
5
+ * its own attributes); changed text and attributes update in place; an element whose children changed in number gets the new
6
+ * children. Wrap what the editor shows in an element with `data-parhelia-refresh-root` (and its render's
7
+ * `data-parhelia-refresh-signature`); `ParheliaRefresh` of `@parhelia/astro` renders it.
8
+ */
9
+ import { installParheliaRefresh } from "./refresh.js";
10
+
11
+ export const REFRESH_ROOT_ATTRIBUTE = "data-parhelia-refresh-root";
12
+ export const REFRESH_SIGNATURE_ATTRIBUTE = "data-parhelia-refresh-signature";
13
+ export const REFRESH_DEADLINE_ATTRIBUTE = "data-parhelia-refresh-deadline";
14
+
15
+ const ELEMENT = 1;
16
+ const TEXT = 3;
17
+ const COMMENT = 8;
18
+
19
+ /**
20
+ * Patches `live` (in the document) from the render it showed (`before`) to the new render (`after`): only what differs between
21
+ * the two renders is touched. Answers the node now in `live`'s place.
22
+ * @param {Node} live @param {Node} before @param {Node} after
23
+ * @returns {Node}
24
+ */
25
+ export function patchRendered(live, before, after) {
26
+ if (before.isEqualNode(after)) return live;
27
+ const document = /** @type {Document} */ (live.ownerDocument);
28
+ if (before.nodeType !== after.nodeType || before.nodeName !== after.nodeName || live.nodeName !== before.nodeName) {
29
+ const next = document.importNode(after, true);
30
+ /** @type {ChildNode} */ (live).replaceWith(next);
31
+ return next;
32
+ }
33
+ if (after.nodeType === TEXT || after.nodeType === COMMENT) {
34
+ if (live.nodeValue !== after.nodeValue) live.nodeValue = after.nodeValue;
35
+ return live;
36
+ }
37
+ if (after.nodeType !== ELEMENT) return live;
38
+ const [element, was, now] = /** @type {[Element, Element, Element]} */ ([live, before, after]);
39
+ for (const { name, value } of [...now.attributes]) if (was.getAttribute(name) !== value) element.setAttribute(name, value);
40
+ for (const { name } of [...was.attributes]) if (!now.hasAttribute(name)) element.removeAttribute(name);
41
+ const [liveChildren, wasChildren, nowChildren] = [[...element.childNodes], [...was.childNodes], [...now.childNodes]];
42
+ if (wasChildren.length === nowChildren.length && liveChildren.length === wasChildren.length) {
43
+ nowChildren.forEach((child, index) => patchRendered(/** @type {Node} */ (liveChildren[index]), /** @type {Node} */ (wasChildren[index]), child));
44
+ } else {
45
+ element.replaceChildren(...nowChildren.map((child) => document.importNode(child, true)));
46
+ }
47
+ return live;
48
+ }
49
+
50
+ /** Whether `url` names the document shown (its `edit_rev` aside). @param {URL} url */
51
+ const showsDocument = (url) => {
52
+ const here = new URL(window.location.href);
53
+ const there = new URL(url);
54
+ here.searchParams.delete("edit_rev");
55
+ there.searchParams.delete("edit_rev");
56
+ return here.href === there.href;
57
+ };
58
+
59
+ /**
60
+ * Installs `window.requestRefresh` for the document's refresh root; the answer removes it again. A refresh reads the page again
61
+ * (the same URL with a fresh `edit_rev`) and patches the root until its signature changed and settled; a new URI on this
62
+ * origin is navigated to.
63
+ * @param {{ deadlineMs?: number }} [options]
64
+ * @returns {() => void}
65
+ */
66
+ export function installParheliaDomRefresh({ deadlineMs } = {}) {
67
+ const selector = `[${REFRESH_ROOT_ATTRIBUTE}]`;
68
+ const root = () => document.querySelector(selector);
69
+ /** What the server rendered last, as it rendered it (the live root may carry the bridge's additions). */
70
+ let rendered = root()?.cloneNode(true) ?? null;
71
+ return installParheliaRefresh({
72
+ deadlineMs: deadlineMs ?? (Number(root()?.getAttribute(REFRESH_DEADLINE_ATTRIBUTE)) || undefined),
73
+ signature: () => root()?.getAttribute(REFRESH_SIGNATURE_ATTRIBUTE) ?? "",
74
+ refetch: async (newUri) => {
75
+ const target = new URL(newUri ?? window.location.href, window.location.href);
76
+ if (target.origin !== window.location.origin) return;
77
+ if (!showsDocument(target)) {
78
+ window.location.replace(target.href);
79
+ return;
80
+ }
81
+ target.searchParams.set("edit_rev", `${Date.now()}-${Math.random().toString(36).slice(2)}`);
82
+ const response = await fetch(target, { credentials: "same-origin", headers: { Accept: "text/html" } });
83
+ if (!response.ok) return;
84
+ const next = new DOMParser().parseFromString(await response.text(), "text/html").querySelector(selector);
85
+ const live = root();
86
+ if (!next || !live) return;
87
+ if (rendered) patchRendered(live, rendered, next);
88
+ else live.replaceWith(document.importNode(next, true));
89
+ rendered = next;
90
+ },
91
+ });
92
+ }
@@ -0,0 +1,14 @@
1
+ export interface ParheliaRefreshInstall {
2
+ /** Reads the page again: the editor's `newUri` when it named one (every read of one request gets the same). */
3
+ refetch: (newUri?: string) => unknown;
4
+ /** A stable string of what the page rendered now; the loop stops once it changed and read the same twice. */
5
+ signature: () => string | undefined;
6
+ /** How long one request keeps reading again (default 8000). */
7
+ deadlineMs?: number;
8
+ }
9
+
10
+ /**
11
+ * Installs `window.requestRefresh(newUri?)`, which reads the page again through `refetch` once a second until the signature
12
+ * changed and settled, or the deadline passed. The answer removes it again and stops a running loop. Imports no React.
13
+ */
14
+ export declare function installParheliaRefresh(options: ParheliaRefreshInstall): () => void;