@aglyn/plugins-ai 1.33.2 → 1.34.1
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/package.json +17 -17
- package/src/lib/declarations.server.js +5 -0
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/jobs/ai-job-template-step.js +1 -1
- package/src/lib/jobs/ai-job-template-step.js.map +1 -1
- package/src/lib/runtime/ai-eval-live.js +118 -0
- package/src/lib/runtime/ai-eval-live.js.map +1 -1
- package/src/lib/runtime/ai-node-tree.d.ts +9 -0
- package/src/lib/runtime/ai-node-tree.js +25 -5
- package/src/lib/runtime/ai-node-tree.js.map +1 -1
- package/src/lib/runtime/ai-palette.generated.js +5 -1
- package/src/lib/runtime/ai-palette.generated.js.map +1 -1
- package/src/lib/server/ai-page-content.js +30 -3
- package/src/lib/server/ai-page-content.js.map +1 -1
- package/src/lib/server/assist-edit.js +91 -7
- package/src/lib/server/assist-edit.js.map +1 -1
- package/src/lib/site-style-starters/index.d.ts +32 -0
- package/src/lib/site-style-starters/index.js +12 -0
- package/src/lib/site-style-starters/index.js.map +1 -1
- package/src/lib/site-style-starters/records.server.d.ts +65 -0
- package/src/lib/site-style-starters/records.server.js +212 -0
- package/src/lib/site-style-starters/records.server.js.map +1 -0
|
@@ -16,12 +16,13 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { createHash } from "node:crypto";
|
|
18
18
|
import { NODE_MAP_MAX_BYTES } from "@aglyn/aglyn/app-utils/measure-node-map";
|
|
19
|
-
import { screenClaimsToBeAPage } from "@aglyn/aglyn/app-utils/screen-route";
|
|
19
|
+
import { SCREEN_KIND_TEMPLATE, screenClaimsToBeAPage } from "@aglyn/aglyn/app-utils/screen-route";
|
|
20
20
|
import { CANVAS_ROOT_ELEMENT_ID } from "@aglyn/aglyn/foundation/constants/canvas";
|
|
21
21
|
import { aiEditBase, aiEditDatasetScope, clearAiEditMirror, draftRef, writeAiEdit } from "../jobs/ai-job-edit-step.js";
|
|
22
22
|
import { AI_EDIT_GONE_COPY, AI_EDIT_NO_NODES_COPY, AI_EDIT_STALE_COPY, AI_EDIT_TOO_LARGE_COPY, AI_EDIT_VERSION_GONE_COPY, aiDocumentElements } from "../model/ai-edit-job.js";
|
|
23
23
|
import { ASSIST_EDIT_ACTION_ID, summarizeAssistEditOps } from "../model/assist-edit.js";
|
|
24
24
|
import { AI_REPEAT_DATASET_PROP, AI_SX_ALLOWED_KEYS, aiPaletteEntryWithCapabilities, aiPropIsIconPick } from "../runtime/ai-node-tree.js";
|
|
25
|
+
import { AI_COMPONENT_VISIBILITY_PROPS } from "../runtime/ai-component-bindings.js";
|
|
25
26
|
import { AI_PALETTE } from "../runtime/ai-palette.generated.js";
|
|
26
27
|
import { readAiSiteDatasets } from "../runtime/site-inventory.js";
|
|
27
28
|
import { ASSIST_EDIT_MAX_INSERT_NODES, ASSIST_EDIT_MAX_OPS, ASSIST_EDIT_MOTION_SETTINGS, assistEditClosedWorld, assistEditLayerNameRefusal, validatePendingEdit } from "./assist-edit.js";
|
|
@@ -103,6 +104,12 @@ const refusal = (status, code, message, fields)=>_extends({
|
|
|
103
104
|
role: 'dataset',
|
|
104
105
|
type: 'string'
|
|
105
106
|
};
|
|
107
|
+
// Hides the element by a record's field (AGL-4261), held to a whole
|
|
108
|
+
// `{{item.<field>}}` where a record fills it.
|
|
109
|
+
for (const name of AI_COMPONENT_VISIBILITY_PROPS)props[name] = {
|
|
110
|
+
role: 'visibility',
|
|
111
|
+
type: 'string'
|
|
112
|
+
};
|
|
106
113
|
return props;
|
|
107
114
|
}
|
|
108
115
|
/** What the palette knows of one kind of element. */ export function aiPageContentKind(kind, options = {}) {
|
|
@@ -209,11 +216,30 @@ const refusal = (status, code, message, fields)=>_extends({
|
|
|
209
216
|
// ── Reading the page ──────────────────────────────────────────────────────
|
|
210
217
|
const NO_PAGE = ()=>refusal(404, 'page_not_found', 'No such page');
|
|
211
218
|
const EMPTY_PAGE = ()=>refusal(404, 'page_empty', 'That page has no saved content to read or edit yet. Open it in the editor first.');
|
|
219
|
+
/**
|
|
220
|
+
* The data plugin's record-page bindings, `hosts/{hostId}/recordPages/{screenId}`
|
|
221
|
+
* (`DATASET_RECORD_PAGES_COLLECTION`): the document id is the template
|
|
222
|
+
* screen's. Named here rather than imported, because one plugin never
|
|
223
|
+
* imports another. Persisted — never rename.
|
|
224
|
+
*/ const RECORD_PAGES_COLLECTION = 'recordPages';
|
|
225
|
+
/**
|
|
226
|
+
* Whether a `kind: 'template'` screen is a dataset's record template
|
|
227
|
+
* (AGL-4261): a page an author builds like any other, served once per
|
|
228
|
+
* record. A blog's entry template and the store's product template are
|
|
229
|
+
* templates too, and stay out.
|
|
230
|
+
*/ async function isRecordTemplate(hostRef, page) {
|
|
231
|
+
if (page.get('kind') !== SCREEN_KIND_TEMPLATE || page.get('deletedAt') != null) return false;
|
|
232
|
+
const binding = await hostRef.collection(RECORD_PAGES_COLLECTION).doc(page.id).get();
|
|
233
|
+
const datasetId = binding.exists ? binding.get('datasetId') : null;
|
|
234
|
+
return typeof datasetId === 'string' && datasetId !== '';
|
|
235
|
+
}
|
|
212
236
|
/**
|
|
213
237
|
* An ordinary page of the site — not deleted, not an email design, a
|
|
214
238
|
* template, an error page or a folder (`screenClaimsToBeAPage`, the rule
|
|
215
239
|
* every page list holds to), and a layout is not in this collection at all —
|
|
216
|
-
* with its current version and that version's draft.
|
|
240
|
+
* with its current version and that version's draft. A dataset's record
|
|
241
|
+
* template is the one template admitted (AGL-4261): it is a page of the
|
|
242
|
+
* site, served once per record.
|
|
217
243
|
*/ async function readPage(firestore, input) {
|
|
218
244
|
const hostRef = firestore.collection('hosts').doc(input.hostId);
|
|
219
245
|
const pageRef = hostRef.collection('screens').doc(input.pageId);
|
|
@@ -224,7 +250,8 @@ const EMPTY_PAGE = ()=>refusal(404, 'page_empty', 'That page has no saved conten
|
|
|
224
250
|
// A site of another workspace holds no page of this one. The door that
|
|
225
251
|
// calls has admitted the site already, so this only guards the pairing.
|
|
226
252
|
if (!host.exists || host.get('orgId') !== input.orgId) return NO_PAGE();
|
|
227
|
-
if (!page.exists
|
|
253
|
+
if (!page.exists) return NO_PAGE();
|
|
254
|
+
if (!screenClaimsToBeAPage(page.data()) && !await isRecordTemplate(hostRef, page)) return NO_PAGE();
|
|
228
255
|
const versionId = typeof page.get('versionId') === 'string' ? page.get('versionId') : '';
|
|
229
256
|
if (!versionId) return EMPTY_PAGE();
|
|
230
257
|
const versions = pageRef.collection('versions');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-page-content.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHash } from 'node:crypto'\nimport { NODE_MAP_MAX_BYTES } from '@aglyn/aglyn/app-utils/measure-node-map'\nimport { screenClaimsToBeAPage } from '@aglyn/aglyn/app-utils/screen-route'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type {\n PageContentEdit,\n PageContentEditInput,\n PageContentEditResult,\n PageContentElement,\n PageContentKind,\n PageContentKindProp,\n PageContentNewElement,\n PageContentRead,\n PageContentReadInput,\n PageContentRefusal,\n PageContentService,\n} from '@aglyn/aglyn/plugin-manager/plugin-page-content'\nimport {\n aiEditBase,\n aiEditDatasetScope,\n clearAiEditMirror,\n draftRef,\n writeAiEdit,\n type AiEditWriteBase,\n} from '../jobs/ai-job-edit-step'\nimport {\n AI_EDIT_GONE_COPY,\n AI_EDIT_NO_NODES_COPY,\n AI_EDIT_STALE_COPY,\n AI_EDIT_TOO_LARGE_COPY,\n AI_EDIT_VERSION_GONE_COPY,\n aiDocumentElements,\n type AiDocumentElement,\n} from '../model/ai-edit-job'\nimport {\n ASSIST_EDIT_ACTION_ID,\n summarizeAssistEditOps,\n type AssistEditCanvasContext,\n type AssistEditCanvasNode,\n type AssistEditProposal,\n} from '../model/assist-edit'\nimport {\n AI_REPEAT_DATASET_PROP,\n AI_SX_ALLOWED_KEYS,\n aiPaletteEntryWithCapabilities,\n aiPropIsIconPick,\n} from '../runtime/ai-node-tree'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport { readAiSiteDatasets } from '../runtime/site-inventory'\nimport {\n ASSIST_EDIT_MAX_INSERT_NODES,\n ASSIST_EDIT_MAX_OPS,\n ASSIST_EDIT_MOTION_SETTINGS,\n assistEditClosedWorld,\n assistEditLayerNameRefusal,\n validatePendingEdit,\n type AssistEditClosedWorldRefusal,\n type AssistEditViolation,\n type PendingEditOp,\n} from './assist-edit'\n\n/**\n * The platform's `core.page-content` contract, answered by the one server\n * page editor there is (AGL-4235): the Assist edit rung the AI edit job runs.\n *\n * A read shows a page as the next edit will find it — the waiting draft when\n * the Besigner would still offer it, otherwise the version the page points at\n * — with every element, complete. An edit is held to the editor's own closed\n * world and validators, as STRICTLY as a caller that is not a model needs:\n * where the rung repairs a model's answer (a setting dropped, text cut, a\n * value coerced), this refuses and names the problem. It lands through the\n * job's own write, always in the page's DRAFT: the live version, the version\n * document and the page document are never touched, and nothing a visitor\n * sees changes until the page is published.\n *\n * ## What `revision` is\n *\n * A digest of the base tree exactly as stored — the `nodes` field's bytes —\n * with which tree it is (the draft or the saved version) and the version's\n * id. It changes whenever that tree changes, and only then: a save that\n * stores the same tree leaves it, and a draft that stops being offered moves\n * the base to the saved version and so moves it too. Read off the content\n * rather than `updatedAt`, which a version written before stamps existed does\n * not carry, so the check an edit makes with `ifRevision` cannot pass on a\n * tree it has not seen.\n *\n * ## What is not editable here, shown as such\n *\n * Each element's `props` and `style` carry only what an edit can set: the\n * settings its kind declares in the palette (with the ones every element\n * takes — repeating, motion), and the style keys the validator admits.\n * Everything else the element stores — rich text (`html`), a class name, an\n * icon the owner picks, references only the editor writes, styles past the\n * key set, interactions, overrides — is under `readOnly`, so a caller can\n * read it and is not invited to send it back.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The id a write made with no person behind it is attributed to, beside its label. */\nexport const AI_PAGE_CONTENT_API_ACTOR = 'api'\n\n/** What a write's summary says, in the draft's history. */\nconst API_EDIT_SUMMARY = 'Edited through the API'\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst refusal = (\n status: PageContentRefusal['status'],\n code: string,\n message: string,\n fields?: Record<string, string>,\n): PageContentRefusal => ({ ok: false, status, code, message, ...(fields && Object.keys(fields).length ? { fields } : {}) })\n\n// ── The revision ──────────────────────────────────────────────────────────\n\n/** A stored value as text that does not depend on key order. */\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`\n if (isRecord(value)) {\n return `{${Object.keys(value)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)\n .join(',')}}`\n }\n return JSON.stringify(value ?? null)\n}\n\n/**\n * The base tree's revision (see the module head): which tree, of which\n * version, and a digest of its `nodes` field as stored — the bytes a\n * current document stores, or a legacy map in a key-order-free form.\n */\nexport function aiPageContentRevision(from: 'draft' | 'saved', versionId: string, stored: unknown): string {\n const hash = createHash('sha256').update(`${from}:${versionId}:`)\n if (stored instanceof Uint8Array) hash.update(stored)\n else hash.update(canonicalJson(stored))\n return `${from === 'draft' ? 'd' : 's'}_${hash.digest('base64url').slice(0, 22)}`\n}\n\n// ── What an element shows ────────────────────────────────────────────────\n\n/** The kind an element is stored as; the document root's wrapper when it names none. */\nconst kindOf = (node: Record<string, unknown>): string =>\n typeof node['componentId'] === 'string' && node['componentId'] ? node['componentId'] : 'div'\n\n/**\n * The settings an edit can set on an element of this kind, by name: the\n * palette's declarations with the ones every element takes, less an icon the\n * site owner picks, then the motion settings and the repeat's dataset. Empty\n * for a kind the palette does not list, whose settings the validator cannot\n * check.\n */\nexport function aiPageContentKindProps(kind: string): Record<string, PageContentKindProp> {\n const entry = aiPaletteEntryWithCapabilities(kind)\n if (!entry) return {}\n const props: Record<string, PageContentKindProp> = {}\n for (const [name, schema] of Object.entries(entry.propsSchema.properties)) {\n if (aiPropIsIconPick(entry, name)) continue\n const role = entry.propRoles[name]\n const maxLength = role === 'text' ? (entry.textLimits[name] ?? schema.maxLength) : schema.maxLength\n props[name] = {\n ...(role ? { role } : {}),\n type: schema.type ?? 'string',\n ...(schema.enum?.length ? { values: [...schema.enum] } : {}),\n ...(maxLength !== undefined ? { maxLength } : {}),\n }\n }\n for (const [name, allowed] of Object.entries(ASSIST_EDIT_MOTION_SETTINGS)) {\n props[name] =\n allowed === 'switch'\n ? { role: 'motion', type: 'boolean' }\n : typeof allowed === 'number'\n ? { role: 'motion', type: 'integer' }\n : { role: 'motion', type: 'string', values: [...allowed] }\n }\n props[AI_REPEAT_DATASET_PROP] = { role: 'dataset', type: 'string' }\n return props\n}\n\n/** What the palette knows of one kind of element. */\nexport function aiPageContentKind(kind: string, options: { root?: boolean } = {}): PageContentKind {\n const entry = AI_PALETTE[kind]\n return {\n label: options.root ? 'Page' : (entry?.displayName ?? kind),\n acceptsChildren: options.root === true || entry?.acceptsChildren === true,\n props: options.root ? {} : aiPageContentKindProps(kind),\n }\n}\n\n/** Node fields an edit here never writes, which an element shows read-only. */\nconst READ_ONLY_NODE_FIELDS = ['className', 'styleOverrides', 'attrOverrides', 'presetRef', 'layoutStyleOverrides'] as const\n\n/** One stored element as a read answers it: what an edit can set, and the rest read-only. */\nfunction elementView(element: AiDocumentElement, settable: ReadonlySet<string>): PageContentElement {\n const { node } = element\n const kind = kindOf(node)\n const props: Record<string, unknown> = {}\n const readOnlyProps: Record<string, unknown> = {}\n for (const [name, value] of Object.entries(isRecord(node['props']) ? node['props'] : {})) {\n if (value === undefined) continue\n if (settable.has(name)) props[name] = value\n else readOnlyProps[name] = value\n }\n const style: Record<string, unknown> = {}\n const readOnlyStyle: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(isRecord(node['sx']) ? node['sx'] : {})) {\n if (AI_SX_ALLOWED_KEYS.has(key)) style[key] = value\n else readOnlyStyle[key] = value\n }\n const readOnly: NonNullable<PageContentElement['readOnly']> = {}\n if (Object.keys(readOnlyProps).length) readOnly.props = readOnlyProps\n if (Object.keys(readOnlyStyle).length) readOnly.style = readOnlyStyle\n if (Array.isArray(node['interactions']) && node['interactions'].length) readOnly.interactions = node['interactions'].length\n const fields = READ_ONLY_NODE_FIELDS.filter((field) => node[field] !== undefined && node[field] !== null)\n if (fields.length) readOnly.fields = fields\n return {\n id: element.id,\n kind,\n ...(typeof node['pluginId'] === 'string' && node['pluginId'] ? { pluginId: node['pluginId'] } : {}),\n ...(typeof node['name'] === 'string' && node['name'] ? { name: node['name'] } : {}),\n parentId: element.parentId,\n children: [...element.children],\n props,\n ...(Object.keys(style).length ? { style } : {}),\n ...(node['hidden'] === true ? { hidden: true } : {}),\n ...(Object.keys(readOnly).length ? { readOnly } : {}),\n }\n}\n\n/**\n * A page's elements as a read answers them, every one, depth first in the\n * order the page reads, with what each kind takes. With `elementId`, that\n * element and everything inside it; null when it is not on the page.\n */\nexport function aiPageContentElements(\n nodes: Readonly<Record<string, unknown>>,\n elementId?: string,\n): { total: number; elements: PageContentElement[]; kinds: Record<string, PageContentKind> } | null {\n const order = aiDocumentElements(nodes)\n if (!order) return null\n let chosen = order\n if (elementId !== undefined) {\n const start = order.findIndex((element) => element.id === elementId)\n if (start < 0) return null\n // Depth first, so a branch is the run of elements from its root until\n // the walk leaves it.\n const inside = new Set([elementId])\n chosen = [order[start]]\n for (const element of order.slice(start + 1)) {\n if (element.parentId === null || !inside.has(element.parentId)) break\n inside.add(element.id)\n chosen.push(element)\n }\n }\n const kinds: Record<string, PageContentKind> = {}\n const settable = new Map<string, ReadonlySet<string>>()\n const elements = chosen.map((element) => {\n const kind = kindOf(element.node)\n const root = element.id === CANVAS_ROOT_ELEMENT_ID\n if (!kinds[kind]) kinds[kind] = aiPageContentKind(kind, { root })\n if (!settable.has(kind)) settable.set(kind, new Set(Object.keys(kinds[kind].props)))\n return elementView(element, settable.get(kind) as ReadonlySet<string>)\n })\n return { total: order.length, elements, kinds }\n}\n\n// ── Reading the page ──────────────────────────────────────────────────────\n\nconst NO_PAGE = (): PageContentRefusal => refusal(404, 'page_not_found', 'No such page')\nconst EMPTY_PAGE = (): PageContentRefusal =>\n refusal(404, 'page_empty', 'That page has no saved content to read or edit yet. Open it in the editor first.')\n\n/** The page a read or an edit names, with the version it points at. */\ninterface PageInHand {\n pageRef: FirebaseFirestore.DocumentReference\n versionId: string\n version: FirebaseFirestore.DocumentSnapshot\n draft: FirebaseFirestore.DocumentSnapshot\n}\n\n/**\n * An ordinary page of the site — not deleted, not an email design, a\n * template, an error page or a folder (`screenClaimsToBeAPage`, the rule\n * every page list holds to), and a layout is not in this collection at all —\n * with its current version and that version's draft.\n */\nasync function readPage(\n firestore: Firestore,\n input: { orgId: string; hostId: string; pageId: string },\n): Promise<PageInHand | PageContentRefusal> {\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n const pageRef = hostRef.collection('screens').doc(input.pageId)\n const [host, page] = await Promise.all([hostRef.get(), pageRef.get()])\n // A site of another workspace holds no page of this one. The door that\n // calls has admitted the site already, so this only guards the pairing.\n if (!host.exists || host.get('orgId') !== input.orgId) return NO_PAGE()\n if (!page.exists || !screenClaimsToBeAPage(page.data() as never)) return NO_PAGE()\n const versionId = typeof page.get('versionId') === 'string' ? (page.get('versionId') as string) : ''\n if (!versionId) return EMPTY_PAGE()\n const versions = pageRef.collection('versions')\n const [version, draft] = await Promise.all([versions.doc(versionId).get(), draftRef(versions, versionId).get()])\n if (!version.exists) return EMPTY_PAGE()\n return { pageRef, versionId, version, draft }\n}\n\nexport async function readAiPageContent(input: PageContentReadInput): Promise<PageContentRead | PageContentRefusal> {\n const firestore = input.firestore as Firestore\n const page = await readPage(firestore, input)\n if ('ok' in page) return page\n const base = aiEditBase(page.draft, page.version)\n if (!base) return EMPTY_PAGE()\n const content = aiPageContentElements(base.nodes, input.elementId)\n if (!content) {\n return input.elementId !== undefined && aiDocumentElements(base.nodes)\n ? refusal(404, 'element_not_found', 'No such element on this page', { elementId: 'is not an element of this page' })\n : EMPTY_PAGE()\n }\n return {\n ok: true,\n pageId: input.pageId,\n versionId: page.versionId,\n base: base.from,\n revision: aiPageContentRevision(base.from, page.versionId, base.stored),\n rootId: CANVAS_ROOT_ELEMENT_ID,\n total: content.total,\n elements: content.elements,\n kinds: content.kinds,\n }\n}\n\n// ── Edits, held to the editor's rules ─────────────────────────────────────\n\n/** Props an edit here never names: markup, styles and handlers, which no field of an element offers. */\nconst UNSETTABLE_PROP = /^(html|sx|style|className|dangerouslySetInnerHTML|on[A-Z].*)$/\n\n/** The words a refused element is named with. */\nconst ELEMENT_REFUSALS: Readonly<Record<AssistEditClosedWorldRefusal, string>> = {\n unknown: 'is not an element of this page',\n root: 'is the page’s root, which cannot be changed, moved or removed',\n removed: 'is inside an element an earlier edit removes',\n}\n\nconst UNSETTABLE_WORDS = 'cannot be set through the API; send text in `children` to replace rich text'\n\n/** The whole page as the editor's closed world: every element, its kind, its place and its settings. */\nfunction wholeContext(order: readonly AiDocumentElement[]): AssistEditCanvasContext {\n const nodes: AssistEditCanvasNode[] = order.map(({ id, parentId, index, childCount, node }) => ({\n id,\n componentId: typeof node['componentId'] === 'string' ? node['componentId'] : '',\n parentId,\n index,\n childCount,\n ...(isRecord(node['props']) ? { props: node['props'] as AssistEditCanvasNode['props'] } : {}),\n }))\n return { selectedId: null, total: nodes.length, nodes, whole: true }\n}\n\n/** Where each element of one insert sits in the request, by the local id it is validated under. */\ntype InsertPaths = Map<string, { path: string; kind: string }>\n\ninterface ParsedApiEdits {\n pending: PendingEditOp[]\n /** The edit each pending op came from. */\n edits: number[]\n /** Each insert's element paths, by the edit's index. */\n inserts: Map<number, InsertPaths>\n fields: Record<string, string>\n}\n\n/** The local id an inserted element is validated under: its path among the request's nested elements. */\nconst localId = (steps: readonly number[]) => ['el', ...steps].join('-')\n\n/**\n * The API's edits as the editor's pending ops, through the one closed world\n * (`assistEditClosedWorld`), with every problem the request itself carries\n * named by edit and member.\n */\nfunction parseApiEdits(edits: readonly PageContentEdit[], context: AssistEditCanvasContext): ParsedApiEdits {\n const world = assistEditClosedWorld(context)\n const parsed: ParsedApiEdits = { pending: [], edits: [], inserts: new Map(), fields: {} }\n const { fields } = parsed\n const element = (at: string, nodeId: unknown): AssistEditCanvasNode | null => {\n const found = world.element(nodeId)\n if (typeof found !== 'string') return found\n fields[at] = ELEMENT_REFUSALS[found]\n return null\n }\n const parent = (at: string, parentId: unknown): AssistEditCanvasNode | null => {\n const found = world.parent(parentId)\n if (!found) fields[at] = typeof parentId === 'string' && world.byId.has(parentId) ? ELEMENT_REFUSALS.removed : ELEMENT_REFUSALS.unknown\n return found\n }\n const unsettable = (at: string, props: Record<string, unknown>): boolean => {\n let found = false\n for (const name of Object.keys(props)) {\n if (!UNSETTABLE_PROP.test(name)) continue\n fields[`${at}.${name}`] = UNSETTABLE_WORDS\n found = true\n }\n return found\n }\n const push = (index: number, op: PendingEditOp) => {\n parsed.pending.push(op)\n parsed.edits.push(index)\n }\n\n edits.forEach((edit, index) => {\n const at = `edits[${index}]`\n switch (edit.op) {\n case 'updateProps': {\n const node = element(`${at}.elementId`, edit.elementId)\n const props = isRecord(edit.props) ? edit.props : {}\n if (!Object.keys(props).length) fields[`${at}.props`] = 'sets no property'\n if (unsettable(`${at}.props`, props) || !node || !Object.keys(props).length) return\n push(index, { op: 'updateProps', nodeId: node.id, componentId: node.componentId, props })\n return\n }\n case 'updateStyle': {\n const node = element(`${at}.elementId`, edit.elementId)\n const style = isRecord(edit.style) ? edit.style : {}\n if (!Object.keys(style).length) fields[`${at}.style`] = 'sets no style'\n if (!node || !Object.keys(style).length) return\n push(index, { op: 'updateSx', nodeId: node.id, componentId: node.componentId, sx: style })\n return\n }\n case 'rename': {\n const node = element(`${at}.elementId`, edit.elementId)\n const named = typeof edit.name === 'string' ? assistEditLayerNameRefusal(edit.name) : 'is not text'\n if (named) fields[`${at}.name`] = named\n if (!node || named) return\n push(index, { op: 'rename', nodeId: node.id, componentId: node.componentId, name: edit.name })\n return\n }\n case 'remove': {\n const node = element(`${at}.elementId`, edit.elementId)\n if (!node) return\n world.remove(node.id)\n push(index, { op: 'remove', nodeId: node.id, componentId: node.componentId })\n return\n }\n case 'move': {\n const node = element(`${at}.elementId`, edit.elementId)\n const into = parent(`${at}.parentId`, edit.parentId)\n if (!node || !into) return\n if (world.movesInsideItself(node.id, into.id)) {\n fields[`${at}.parentId`] = 'is inside the element being moved'\n return\n }\n world.move(node.id, into.id)\n push(index, {\n op: 'move',\n nodeId: node.id,\n componentId: node.componentId,\n parentId: into.id,\n parentComponentId: into.componentId,\n index: edit.index,\n })\n return\n }\n case 'insert': {\n const into = parent(`${at}.parentId`, edit.parentId)\n const paths: InsertPaths = new Map()\n const nodes: Record<string, Record<string, unknown>> = {}\n let refused = false\n const visit = (raw: PageContentNewElement, steps: number[], path: string) => {\n const id = localId(steps)\n paths.set(id, { path, kind: raw.kind })\n const props = isRecord(raw.props) ? raw.props : {}\n if (unsettable(`${path}.props`, props)) refused = true\n if (raw.name !== undefined) {\n const named = assistEditLayerNameRefusal(raw.name)\n if (named) {\n fields[`${path}.name`] = named\n refused = true\n }\n }\n const children = Array.isArray(raw.children) ? raw.children : []\n nodes[id] = {\n $id: id,\n componentId: raw.kind,\n nodes: children.map((_, child) => localId([...steps, child])),\n props,\n ...(raw.style !== undefined ? { sx: raw.style } : {}),\n ...(raw.name !== undefined ? { name: raw.name } : {}),\n }\n children.forEach((child, position) => visit(child, [...steps, position], `${path}.children[${position}]`))\n }\n visit(edit.element, [], `${at}.element`)\n if (paths.size > ASSIST_EDIT_MAX_INSERT_NODES) {\n fields[`${at}.element`] = `adds ${paths.size} elements; one insert adds at most ${ASSIST_EDIT_MAX_INSERT_NODES}`\n return\n }\n if (!into || refused) return\n parsed.inserts.set(index, paths)\n push(index, {\n op: 'insertSubtree',\n parentId: into.id,\n parentComponentId: into.componentId,\n index: typeof edit.index === 'number' ? edit.index : null,\n tree: { rootId: localId([]), nodes },\n })\n return\n }\n default:\n fields[`${at}.op`] = 'is not an edit this API makes: updateProps, updateStyle, rename, insert, move or remove'\n }\n })\n return parsed\n}\n\n/** The validator's line, in the words a field is named with. */\nfunction reasonOf(text: string): string {\n return text\n .replace(/; (dropped|truncated|recomputed)$/, '')\n .replace(/^was over (\\d+) characters$/, 'is longer than $1 characters')\n .replace(/^is not a prop of /, 'is not a property of ')\n .replace(/; normalized to \"([^\"]*)\"$/, '; write \"$1\"')\n .trim()\n}\n\nconst escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n/**\n * One violation, named by the edit and the member it is in. A repair line\n * names the element the validator was given — the kind, for a patch; the\n * local id, for an inserted element — and the setting, which is read back\n * off it.\n */\nfunction placeViolation(\n violation: AssistEditViolation,\n edit: PageContentEdit,\n at: string,\n paths: InsertPaths | undefined,\n kindOfElement: (elementId: string) => string,\n): [member: string, reason: string] {\n const { message } = violation\n if (edit.op === 'updateProps') {\n const subject = `${escapeRegExp(kindOfElement(edit.elementId))}\\\\.`\n const names = Object.keys(edit.props ?? {}).sort((a, b) => b.length - a.length)\n for (const name of names) {\n const repaired = new RegExp(`^${subject}${escapeRegExp(name)}:? (.*)$`).exec(message)\n if (repaired) return [`${at}.props.${name}`, reasonOf(repaired[1])]\n if (message.startsWith(`${name} `)) return [`${at}.props.${name}`, reasonOf(message.slice(name.length + 1))]\n }\n return [`${at}.props`, reasonOf(message)]\n }\n if (edit.op === 'updateStyle') {\n const repaired = /: sx\\.([A-Za-z]+)((?:\\.[A-Za-z]+)?) (.*)$/.exec(message)\n if (repaired) return [`${at}.style.${repaired[1]}${repaired[2]}`, reasonOf(repaired[3])]\n return [`${at}.style`, reasonOf(message)]\n }\n if (edit.op === 'move') return [`${at}.parentId`, reasonOf(message)]\n if (edit.op === 'insert' && paths) {\n const ids = [...paths.keys()].sort((a, b) => b.length - a.length)\n const named = (text: string) =>\n ids\n .reduce((out, id) => out.replace(new RegExp(`\\\\b${escapeRegExp(id)}\\\\b(?!-)`, 'g'), paths.get(id)?.path ?? id), text)\n .replace(/\\bchain-\\d+\\b/g, 'the element it is added into')\n .replace(new RegExp(escapeRegExp(CANVAS_ROOT_ELEMENT_ID), 'g'), 'the page’s root')\n for (const id of ids) {\n const path = paths.get(id)?.path as string\n const prop = new RegExp(`^${escapeRegExp(id)}\\\\.([A-Za-z_][A-Za-z0-9_]*)(?:\\\\.[A-Za-z0-9_]+)?:? (.*)$`).exec(message)\n if (prop) return [`${path}.${prop[1] === 'hidden' ? 'hidden' : `props.${prop[1]}`}`, reasonOf(named(prop[2]))]\n const style = new RegExp(`^${escapeRegExp(id)}: sx\\\\.([A-Za-z]+)((?:\\\\.[A-Za-z]+)?) (.*)$`).exec(message)\n if (style) return [`${path}.style.${style[1]}${style[2]}`, reasonOf(named(style[3]))]\n if (new RegExp(`\\\\(${escapeRegExp(id)}\\\\)|^${escapeRegExp(id)}\\\\b(?!-)`).test(message)) return [path, reasonOf(named(message))]\n }\n // An element the page's palette does not offer, as the palette or the\n // sanitizer under it words it.\n const component = /^Component \"([^\"]+)\" (?:is not in the palette|cannot be published)/.exec(message)\n if (component) {\n const found = [...paths.values()].find((entry) => entry.kind === component[1])\n if (found) return [`${found.path}.kind`, 'is not a kind of element a page takes']\n }\n return [`${at}.element`, reasonOf(named(message))]\n }\n return [at, reasonOf(message)]\n}\n\n/** What a built change is, or why the edits were refused. */\ntype BuiltEdit = { proposal: AssistEditProposal } | { refused: PageContentRefusal }\n\n/**\n * The edits validated against one tree and built into the editor's proposal,\n * or refused with every problem named. Pure: the write calls it with the tree\n * its transaction read, so what is checked is what is written.\n */\nexport function buildAiPageContentEdit(input: {\n base: Pick<AiEditWriteBase, 'from' | 'nodes' | 'stored'>\n pageId: string\n hostId: string\n versionId: string\n edits: readonly PageContentEdit[]\n ifRevision?: string\n screenIds: Iterable<string>\n mediaScopes: Iterable<string>\n datasets?: ReturnType<typeof aiEditDatasetScope>\n}): BuiltEdit {\n if (input.ifRevision !== undefined) {\n const current = aiPageContentRevision(input.base.from, input.versionId, input.base.stored)\n if (current !== input.ifRevision) {\n return {\n refused: refusal(409, 'stale', 'The page changed since that revision was read, so nothing was saved. Read it again.', {\n ifRevision: `is not the page’s current revision, ${current}`,\n }),\n }\n }\n }\n if (!input.edits.length || input.edits.length > ASSIST_EDIT_MAX_OPS) {\n return {\n refused: refusal(422, 'edit_refused', 'The edits could not be saved, so none were.', {\n edits: `holds ${input.edits.length}; send 1 to ${ASSIST_EDIT_MAX_OPS} edits`,\n }),\n }\n }\n const order = aiDocumentElements(input.base.nodes)\n if (!order) return { refused: EMPTY_PAGE() }\n const context = wholeContext(order)\n // The kind each element was validated as, which a patch's repair lines name.\n const kinds = new Map(context.nodes.map((node) => [node.id, node.componentId]))\n const parsed = parseApiEdits(input.edits, context)\n const validated = validatePendingEdit({\n surface: 'screen',\n context,\n pending: parsed.pending,\n strict: true,\n references: { screenIds: input.screenIds, mediaScopes: input.mediaScopes },\n ...(input.datasets ? { datasets: input.datasets } : {}),\n })\n const fields = { ...parsed.fields }\n for (const violation of validated.violations) {\n const index = parsed.edits[violation.position]\n const [member, reason] = placeViolation(violation, input.edits[index], `edits[${index}]`, parsed.inserts.get(index), (id) =>\n kinds.get(id) ?? '',\n )\n fields[member] = fields[member] ? `${fields[member]}; ${reason}` : reason\n }\n if (Object.keys(fields).length || validated.ops.length !== input.edits.length) {\n return { refused: refusal(422, 'edit_refused', 'The edits could not be saved, so none were. `fields` names each problem.', fields) }\n }\n return {\n proposal: {\n id: ASSIST_EDIT_ACTION_ID,\n summary: API_EDIT_SUMMARY,\n ops: validated.ops,\n diff: summarizeAssistEditOps(validated.ops),\n dropped: [],\n target: { kind: 'screen', documentId: input.pageId, versionId: input.versionId, hostId: input.hostId },\n },\n }\n}\n\n// ── Writing them ──────────────────────────────────────────────────────────\n\nexport interface AiPageContentDeps {\n writeEdit?: typeof writeAiEdit\n readDatasets?: typeof readAiSiteDatasets\n clearMirror?: typeof clearAiEditMirror\n now?: () => Date\n}\n\n/** The site's pages a link may name: every ordinary page, as a page list holds them. */\nasync function sitePageIds(firestore: Firestore, hostId: string): Promise<string[]> {\n const pages = await firestore.collection('hosts').doc(hostId).collection('screens').select('deletedAt', 'kind').get()\n return pages.docs.filter((page) => screenClaimsToBeAPage(page.data() as never)).map((page) => page.id)\n}\n\n/** A write's own failures, as the statuses an API answers. */\nfunction writeRefusal(error: string, tooLarge?: { bytes: number }): PageContentRefusal {\n if (tooLarge) {\n return refusal(413, 'page_too_large', `${AI_EDIT_TOO_LARGE_COPY} It would be ${tooLarge.bytes} bytes; a page holds at most ${NODE_MAP_MAX_BYTES}.`)\n }\n if (error === AI_EDIT_GONE_COPY) return NO_PAGE()\n if (error === AI_EDIT_NO_NODES_COPY) return EMPTY_PAGE()\n if (error === AI_EDIT_STALE_COPY || error === AI_EDIT_VERSION_GONE_COPY) {\n return refusal(409, 'stale', 'The page changed while the edits were being saved, so nothing was saved. Read it again.')\n }\n return refusal(422, 'edit_refused', 'The editor refused part of these edits, so none were saved.')\n}\n\nexport function createAiPageContentEditor(deps: AiPageContentDeps = {}) {\n const writeEdit = deps.writeEdit ?? writeAiEdit\n const readDatasets = deps.readDatasets ?? readAiSiteDatasets\n const clearMirror = deps.clearMirror ?? clearAiEditMirror\n return async function editAiPageContent(input: PageContentEditInput): Promise<PageContentEditResult | PageContentRefusal> {\n const firestore = input.firestore as Firestore\n if (!Array.isArray(input.edits) || !input.edits.length || input.edits.length > ASSIST_EDIT_MAX_OPS) {\n return refusal(422, 'edit_refused', 'The edits could not be saved, so none were.', {\n edits: `send 1 to ${ASSIST_EDIT_MAX_OPS} edits`,\n })\n }\n const page = await readPage(firestore, input)\n if ('ok' in page) return page\n const [screenIds, datasets] = await Promise.all([\n sitePageIds(firestore, input.hostId),\n readDatasets(input.orgId, input.hostId),\n ])\n const scope = aiEditDatasetScope(datasets, { kind: 'screen', id: input.pageId })\n const write = await writeEdit<PageContentRefusal>(firestore, {\n hostId: input.hostId,\n kind: 'screen',\n id: input.pageId,\n sourceVersionId: page.versionId,\n jobVersionId: input.editId,\n // Always the version's draft: never a new version, never the search\n // fields, so nothing a visitor sees and nothing on the page moves.\n versioning: false,\n newVersion: false,\n writeSeo: false,\n versionName: API_EDIT_SUMMARY,\n uid: input.actor.uid ?? AI_PAGE_CONTENT_API_ACTOR,\n updatedByLabel: input.actor.label,\n updatedVia: input.actor.via ?? 'api',\n maxNodeBytes: NODE_MAP_MAX_BYTES,\n aiJobId: input.editId,\n now: (deps.now ?? (() => new Date()))(),\n proposal: (base) => {\n // The version the page points at moved since the read: the draft the\n // edits were asked of is no longer the page's.\n if (base.pointerVersionId !== page.versionId) {\n return { refused: refusal(409, 'stale', 'The page changed since it was read, so nothing was saved. Read it again.') }\n }\n const built = buildAiPageContentEdit({\n base,\n pageId: input.pageId,\n hostId: input.hostId,\n versionId: page.versionId,\n edits: input.edits,\n ...(input.ifRevision !== undefined ? { ifRevision: input.ifRevision } : {}),\n screenIds,\n mediaScopes: input.mediaScopes,\n datasets: scope,\n })\n return 'proposal' in built ? built.proposal : built\n },\n })\n if (write.ok === false) return write.refused ?? writeRefusal(write.error, write.tooLarge)\n if (write.placement === 'draft') {\n await clearMirror({ orgId: input.orgId, hostId: input.hostId, kind: 'screen', id: input.pageId, versionId: write.versionId }).catch(\n (error: unknown) => console.warn('[page content] the co-edit mirror could not be cleared', { pageId: input.pageId, error }),\n )\n }\n // A write asked again finds what it wrote and writes nothing; its\n // revision is the draft's as it stands.\n const revision = write.written\n ? aiPageContentRevision('draft', write.versionId, write.written.stored)\n : await readAiPageContent({ firestore, orgId: input.orgId, hostId: input.hostId, pageId: input.pageId }).then((read) =>\n read.ok ? read.revision : '',\n )\n return {\n ok: true,\n pageId: input.pageId,\n versionId: write.versionId,\n revision,\n applied: input.edits.length,\n created: (write.written?.inserted ?? []).map(({ op, ids }) => ({ index: op, id: ids[0], ids })),\n }\n }\n}\n\n/** The contract's implementation, as the plugin registers it. */\nexport const aiPageContentService: PageContentService = {\n read: readAiPageContent,\n editDraft: createAiPageContentEditor(),\n}\n\n"],"names":["createHash","NODE_MAP_MAX_BYTES","screenClaimsToBeAPage","CANVAS_ROOT_ELEMENT_ID","aiEditBase","aiEditDatasetScope","clearAiEditMirror","draftRef","writeAiEdit","AI_EDIT_GONE_COPY","AI_EDIT_NO_NODES_COPY","AI_EDIT_STALE_COPY","AI_EDIT_TOO_LARGE_COPY","AI_EDIT_VERSION_GONE_COPY","aiDocumentElements","ASSIST_EDIT_ACTION_ID","summarizeAssistEditOps","AI_REPEAT_DATASET_PROP","AI_SX_ALLOWED_KEYS","aiPaletteEntryWithCapabilities","aiPropIsIconPick","AI_PALETTE","readAiSiteDatasets","ASSIST_EDIT_MAX_INSERT_NODES","ASSIST_EDIT_MAX_OPS","ASSIST_EDIT_MOTION_SETTINGS","assistEditClosedWorld","assistEditLayerNameRefusal","validatePendingEdit","AI_PAGE_CONTENT_API_ACTOR","API_EDIT_SUMMARY","isRecord","value","Array","isArray","refusal","status","code","message","fields","ok","Object","keys","length","canonicalJson","map","join","sort","key","JSON","stringify","aiPageContentRevision","from","versionId","stored","hash","update","Uint8Array","digest","slice","kindOf","node","aiPageContentKindProps","kind","entry","props","name","schema","entries","propsSchema","properties","role","propRoles","maxLength","textLimits","type","enum","values","undefined","allowed","aiPageContentKind","options","label","root","displayName","acceptsChildren","READ_ONLY_NODE_FIELDS","elementView","element","settable","readOnlyProps","has","style","readOnlyStyle","readOnly","interactions","filter","field","id","pluginId","parentId","children","hidden","aiPageContentElements","nodes","elementId","order","chosen","start","findIndex","inside","Set","add","push","kinds","Map","elements","set","get","total","NO_PAGE","EMPTY_PAGE","readPage","firestore","input","hostRef","collection","doc","hostId","pageRef","pageId","host","page","Promise","all","exists","orgId","data","versions","version","draft","readAiPageContent","base","content","revision","rootId","UNSETTABLE_PROP","ELEMENT_REFUSALS","unknown","removed","UNSETTABLE_WORDS","wholeContext","index","childCount","componentId","selectedId","whole","localId","steps","parseApiEdits","edits","context","world","parsed","pending","inserts","at","nodeId","found","parent","byId","unsettable","test","op","forEach","edit","sx","named","remove","into","movesInsideItself","move","parentComponentId","paths","refused","visit","raw","path","$id","_","child","position","size","tree","reasonOf","text","replace","trim","escapeRegExp","placeViolation","violation","kindOfElement","subject","names","a","b","repaired","RegExp","exec","startsWith","ids","reduce","out","prop","component","find","buildAiPageContentEdit","ifRevision","current","validated","surface","strict","references","screenIds","mediaScopes","datasets","violations","member","reason","ops","proposal","summary","diff","dropped","target","documentId","sitePageIds","pages","select","docs","writeRefusal","error","tooLarge","bytes","createAiPageContentEditor","deps","writeEdit","readDatasets","clearMirror","editAiPageContent","write","scope","sourceVersionId","jobVersionId","editId","versioning","newVersion","writeSeo","versionName","uid","actor","updatedByLabel","updatedVia","via","maxNodeBytes","aiJobId","now","Date","pointerVersionId","built","placement","catch","console","warn","written","then","read","applied","created","inserted","aiPageContentService","editDraft"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,cAAa;AACxC,SAASC,kBAAkB,QAAQ,0CAAyC;AAC5E,SAASC,qBAAqB,QAAQ,sCAAqC;AAC3E,SAASC,sBAAsB,QAAQ,2CAA0C;AAcjF,SACEC,UAAU,EACVC,kBAAkB,EAClBC,iBAAiB,EACjBC,QAAQ,EACRC,WAAW,QAEN,8BAA0B;AACjC,SACEC,iBAAiB,EACjBC,qBAAqB,EACrBC,kBAAkB,EAClBC,sBAAsB,EACtBC,yBAAyB,EACzB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,MAAMI,MAAM;gBAAEjE,MAAM;gBAAUmC,IAAI0B,MAAMM,MAAM;gBAAE7E,WAAWqM,MAAMrM,SAAS;YAAC,GAAG0N,KAAK,CACjI,CAAC9B,QAAmB+B,QAAQC,IAAI,CAAC,0DAA0D;oBAAE/I,QAAQN,MAAMM,MAAM;oBAAE+G;gBAAM;QAE7H;QACA,kEAAkE;QAClE,wCAAwC;QACxC,MAAMjG,WAAW0G,MAAMwB,OAAO,GAC1B/N,sBAAsB,SAASuM,MAAMrM,SAAS,EAAEqM,MAAMwB,OAAO,CAAC5N,MAAM,IACpE,MAAMuF,kBAAkB;YAAElB;YAAWa,OAAOZ,MAAMY,KAAK;YAAER,QAAQJ,MAAMI,MAAM;YAAEE,QAAQN,MAAMM,MAAM;QAAC,GAAGiJ,IAAI,CAAC,CAACC,OAC3GA,KAAK5O,EAAE,GAAG4O,KAAKpI,QAAQ,GAAG;QAEhC,OAAO;YACLxG,IAAI;YACJ0F,QAAQN,MAAMM,MAAM;YACpB7E,WAAWqM,MAAMrM,SAAS;YAC1B2F;YACAqI,SAASzJ,MAAMoC,KAAK,CAACrH,MAAM;YAC3B2O,SAAS,UAAC5B,iBAAAA,MAAMwB,OAAO,qBAAbxB,eAAe6B,QAAQ,mBAAI,EAAE,EAAE1O,GAAG,CAAC,CAAC,EAAEgI,EAAE,EAAEqC,GAAG,EAAE,GAAM,CAAA;oBAAE1D,OAAOqB;oBAAI3E,IAAIgH,GAAG,CAAC,EAAE;oBAAEA;gBAAI,CAAA;QAC9F;IACF;AACF;AAEA,+DAA+D,GAC/D,OAAO,MAAMsE,uBAA2C;IACtDJ,MAAMvI;IACN4I,WAAWrC;AACb,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-page-content.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHash } from 'node:crypto'\nimport { NODE_MAP_MAX_BYTES } from '@aglyn/aglyn/app-utils/measure-node-map'\nimport { SCREEN_KIND_TEMPLATE, screenClaimsToBeAPage } from '@aglyn/aglyn/app-utils/screen-route'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type {\n PageContentEdit,\n PageContentEditInput,\n PageContentEditResult,\n PageContentElement,\n PageContentKind,\n PageContentKindProp,\n PageContentNewElement,\n PageContentRead,\n PageContentReadInput,\n PageContentRefusal,\n PageContentService,\n} from '@aglyn/aglyn/plugin-manager/plugin-page-content'\nimport {\n aiEditBase,\n aiEditDatasetScope,\n clearAiEditMirror,\n draftRef,\n writeAiEdit,\n type AiEditWriteBase,\n} from '../jobs/ai-job-edit-step'\nimport {\n AI_EDIT_GONE_COPY,\n AI_EDIT_NO_NODES_COPY,\n AI_EDIT_STALE_COPY,\n AI_EDIT_TOO_LARGE_COPY,\n AI_EDIT_VERSION_GONE_COPY,\n aiDocumentElements,\n type AiDocumentElement,\n} from '../model/ai-edit-job'\nimport {\n ASSIST_EDIT_ACTION_ID,\n summarizeAssistEditOps,\n type AssistEditCanvasContext,\n type AssistEditCanvasNode,\n type AssistEditProposal,\n} from '../model/assist-edit'\nimport {\n AI_REPEAT_DATASET_PROP,\n AI_SX_ALLOWED_KEYS,\n aiPaletteEntryWithCapabilities,\n aiPropIsIconPick,\n} from '../runtime/ai-node-tree'\nimport { AI_COMPONENT_VISIBILITY_PROPS } from '../runtime/ai-component-bindings'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport { readAiSiteDatasets } from '../runtime/site-inventory'\nimport {\n ASSIST_EDIT_MAX_INSERT_NODES,\n ASSIST_EDIT_MAX_OPS,\n ASSIST_EDIT_MOTION_SETTINGS,\n assistEditClosedWorld,\n assistEditLayerNameRefusal,\n validatePendingEdit,\n type AssistEditClosedWorldRefusal,\n type AssistEditViolation,\n type PendingEditOp,\n} from './assist-edit'\n\n/**\n * The platform's `core.page-content` contract, answered by the one server\n * page editor there is (AGL-4235): the Assist edit rung the AI edit job runs.\n *\n * A read shows a page as the next edit will find it — the waiting draft when\n * the Besigner would still offer it, otherwise the version the page points at\n * — with every element, complete. An edit is held to the editor's own closed\n * world and validators, as STRICTLY as a caller that is not a model needs:\n * where the rung repairs a model's answer (a setting dropped, text cut, a\n * value coerced), this refuses and names the problem. It lands through the\n * job's own write, always in the page's DRAFT: the live version, the version\n * document and the page document are never touched, and nothing a visitor\n * sees changes until the page is published.\n *\n * ## What `revision` is\n *\n * A digest of the base tree exactly as stored — the `nodes` field's bytes —\n * with which tree it is (the draft or the saved version) and the version's\n * id. It changes whenever that tree changes, and only then: a save that\n * stores the same tree leaves it, and a draft that stops being offered moves\n * the base to the saved version and so moves it too. Read off the content\n * rather than `updatedAt`, which a version written before stamps existed does\n * not carry, so the check an edit makes with `ifRevision` cannot pass on a\n * tree it has not seen.\n *\n * ## What is not editable here, shown as such\n *\n * Each element's `props` and `style` carry only what an edit can set: the\n * settings its kind declares in the palette (with the ones every element\n * takes — repeating, motion), and the style keys the validator admits.\n * Everything else the element stores — rich text (`html`), a class name, an\n * icon the owner picks, references only the editor writes, styles past the\n * key set, interactions, overrides — is under `readOnly`, so a caller can\n * read it and is not invited to send it back.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The id a write made with no person behind it is attributed to, beside its label. */\nexport const AI_PAGE_CONTENT_API_ACTOR = 'api'\n\n/** What a write's summary says, in the draft's history. */\nconst API_EDIT_SUMMARY = 'Edited through the API'\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst refusal = (\n status: PageContentRefusal['status'],\n code: string,\n message: string,\n fields?: Record<string, string>,\n): PageContentRefusal => ({ ok: false, status, code, message, ...(fields && Object.keys(fields).length ? { fields } : {}) })\n\n// ── The revision ──────────────────────────────────────────────────────────\n\n/** A stored value as text that does not depend on key order. */\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`\n if (isRecord(value)) {\n return `{${Object.keys(value)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)\n .join(',')}}`\n }\n return JSON.stringify(value ?? null)\n}\n\n/**\n * The base tree's revision (see the module head): which tree, of which\n * version, and a digest of its `nodes` field as stored — the bytes a\n * current document stores, or a legacy map in a key-order-free form.\n */\nexport function aiPageContentRevision(from: 'draft' | 'saved', versionId: string, stored: unknown): string {\n const hash = createHash('sha256').update(`${from}:${versionId}:`)\n if (stored instanceof Uint8Array) hash.update(stored)\n else hash.update(canonicalJson(stored))\n return `${from === 'draft' ? 'd' : 's'}_${hash.digest('base64url').slice(0, 22)}`\n}\n\n// ── What an element shows ────────────────────────────────────────────────\n\n/** The kind an element is stored as; the document root's wrapper when it names none. */\nconst kindOf = (node: Record<string, unknown>): string =>\n typeof node['componentId'] === 'string' && node['componentId'] ? node['componentId'] : 'div'\n\n/**\n * The settings an edit can set on an element of this kind, by name: the\n * palette's declarations with the ones every element takes, less an icon the\n * site owner picks, then the motion settings and the repeat's dataset. Empty\n * for a kind the palette does not list, whose settings the validator cannot\n * check.\n */\nexport function aiPageContentKindProps(kind: string): Record<string, PageContentKindProp> {\n const entry = aiPaletteEntryWithCapabilities(kind)\n if (!entry) return {}\n const props: Record<string, PageContentKindProp> = {}\n for (const [name, schema] of Object.entries(entry.propsSchema.properties)) {\n if (aiPropIsIconPick(entry, name)) continue\n const role = entry.propRoles[name]\n const maxLength = role === 'text' ? (entry.textLimits[name] ?? schema.maxLength) : schema.maxLength\n props[name] = {\n ...(role ? { role } : {}),\n type: schema.type ?? 'string',\n ...(schema.enum?.length ? { values: [...schema.enum] } : {}),\n ...(maxLength !== undefined ? { maxLength } : {}),\n }\n }\n for (const [name, allowed] of Object.entries(ASSIST_EDIT_MOTION_SETTINGS)) {\n props[name] =\n allowed === 'switch'\n ? { role: 'motion', type: 'boolean' }\n : typeof allowed === 'number'\n ? { role: 'motion', type: 'integer' }\n : { role: 'motion', type: 'string', values: [...allowed] }\n }\n props[AI_REPEAT_DATASET_PROP] = { role: 'dataset', type: 'string' }\n // Hides the element by a record's field (AGL-4261), held to a whole\n // `{{item.<field>}}` where a record fills it.\n for (const name of AI_COMPONENT_VISIBILITY_PROPS) props[name] = { role: 'visibility', type: 'string' }\n return props\n}\n\n/** What the palette knows of one kind of element. */\nexport function aiPageContentKind(kind: string, options: { root?: boolean } = {}): PageContentKind {\n const entry = AI_PALETTE[kind]\n return {\n label: options.root ? 'Page' : (entry?.displayName ?? kind),\n acceptsChildren: options.root === true || entry?.acceptsChildren === true,\n props: options.root ? {} : aiPageContentKindProps(kind),\n }\n}\n\n/** Node fields an edit here never writes, which an element shows read-only. */\nconst READ_ONLY_NODE_FIELDS = ['className', 'styleOverrides', 'attrOverrides', 'presetRef', 'layoutStyleOverrides'] as const\n\n/** One stored element as a read answers it: what an edit can set, and the rest read-only. */\nfunction elementView(element: AiDocumentElement, settable: ReadonlySet<string>): PageContentElement {\n const { node } = element\n const kind = kindOf(node)\n const props: Record<string, unknown> = {}\n const readOnlyProps: Record<string, unknown> = {}\n for (const [name, value] of Object.entries(isRecord(node['props']) ? node['props'] : {})) {\n if (value === undefined) continue\n if (settable.has(name)) props[name] = value\n else readOnlyProps[name] = value\n }\n const style: Record<string, unknown> = {}\n const readOnlyStyle: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(isRecord(node['sx']) ? node['sx'] : {})) {\n if (AI_SX_ALLOWED_KEYS.has(key)) style[key] = value\n else readOnlyStyle[key] = value\n }\n const readOnly: NonNullable<PageContentElement['readOnly']> = {}\n if (Object.keys(readOnlyProps).length) readOnly.props = readOnlyProps\n if (Object.keys(readOnlyStyle).length) readOnly.style = readOnlyStyle\n if (Array.isArray(node['interactions']) && node['interactions'].length) readOnly.interactions = node['interactions'].length\n const fields = READ_ONLY_NODE_FIELDS.filter((field) => node[field] !== undefined && node[field] !== null)\n if (fields.length) readOnly.fields = fields\n return {\n id: element.id,\n kind,\n ...(typeof node['pluginId'] === 'string' && node['pluginId'] ? { pluginId: node['pluginId'] } : {}),\n ...(typeof node['name'] === 'string' && node['name'] ? { name: node['name'] } : {}),\n parentId: element.parentId,\n children: [...element.children],\n props,\n ...(Object.keys(style).length ? { style } : {}),\n ...(node['hidden'] === true ? { hidden: true } : {}),\n ...(Object.keys(readOnly).length ? { readOnly } : {}),\n }\n}\n\n/**\n * A page's elements as a read answers them, every one, depth first in the\n * order the page reads, with what each kind takes. With `elementId`, that\n * element and everything inside it; null when it is not on the page.\n */\nexport function aiPageContentElements(\n nodes: Readonly<Record<string, unknown>>,\n elementId?: string,\n): { total: number; elements: PageContentElement[]; kinds: Record<string, PageContentKind> } | null {\n const order = aiDocumentElements(nodes)\n if (!order) return null\n let chosen = order\n if (elementId !== undefined) {\n const start = order.findIndex((element) => element.id === elementId)\n if (start < 0) return null\n // Depth first, so a branch is the run of elements from its root until\n // the walk leaves it.\n const inside = new Set([elementId])\n chosen = [order[start]]\n for (const element of order.slice(start + 1)) {\n if (element.parentId === null || !inside.has(element.parentId)) break\n inside.add(element.id)\n chosen.push(element)\n }\n }\n const kinds: Record<string, PageContentKind> = {}\n const settable = new Map<string, ReadonlySet<string>>()\n const elements = chosen.map((element) => {\n const kind = kindOf(element.node)\n const root = element.id === CANVAS_ROOT_ELEMENT_ID\n if (!kinds[kind]) kinds[kind] = aiPageContentKind(kind, { root })\n if (!settable.has(kind)) settable.set(kind, new Set(Object.keys(kinds[kind].props)))\n return elementView(element, settable.get(kind) as ReadonlySet<string>)\n })\n return { total: order.length, elements, kinds }\n}\n\n// ── Reading the page ──────────────────────────────────────────────────────\n\nconst NO_PAGE = (): PageContentRefusal => refusal(404, 'page_not_found', 'No such page')\nconst EMPTY_PAGE = (): PageContentRefusal =>\n refusal(404, 'page_empty', 'That page has no saved content to read or edit yet. Open it in the editor first.')\n\n/** The page a read or an edit names, with the version it points at. */\ninterface PageInHand {\n pageRef: FirebaseFirestore.DocumentReference\n versionId: string\n version: FirebaseFirestore.DocumentSnapshot\n draft: FirebaseFirestore.DocumentSnapshot\n}\n\n/**\n * The data plugin's record-page bindings, `hosts/{hostId}/recordPages/{screenId}`\n * (`DATASET_RECORD_PAGES_COLLECTION`): the document id is the template\n * screen's. Named here rather than imported, because one plugin never\n * imports another. Persisted — never rename.\n */\nconst RECORD_PAGES_COLLECTION = 'recordPages'\n\n/**\n * Whether a `kind: 'template'` screen is a dataset's record template\n * (AGL-4261): a page an author builds like any other, served once per\n * record. A blog's entry template and the store's product template are\n * templates too, and stay out.\n */\nasync function isRecordTemplate(\n hostRef: FirebaseFirestore.DocumentReference,\n page: FirebaseFirestore.DocumentSnapshot,\n): Promise<boolean> {\n if (page.get('kind') !== SCREEN_KIND_TEMPLATE || page.get('deletedAt') != null) return false\n const binding = await hostRef.collection(RECORD_PAGES_COLLECTION).doc(page.id).get()\n const datasetId = binding.exists ? binding.get('datasetId') : null\n return typeof datasetId === 'string' && datasetId !== ''\n}\n\n/**\n * An ordinary page of the site — not deleted, not an email design, a\n * template, an error page or a folder (`screenClaimsToBeAPage`, the rule\n * every page list holds to), and a layout is not in this collection at all —\n * with its current version and that version's draft. A dataset's record\n * template is the one template admitted (AGL-4261): it is a page of the\n * site, served once per record.\n */\nasync function readPage(\n firestore: Firestore,\n input: { orgId: string; hostId: string; pageId: string },\n): Promise<PageInHand | PageContentRefusal> {\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n const pageRef = hostRef.collection('screens').doc(input.pageId)\n const [host, page] = await Promise.all([hostRef.get(), pageRef.get()])\n // A site of another workspace holds no page of this one. The door that\n // calls has admitted the site already, so this only guards the pairing.\n if (!host.exists || host.get('orgId') !== input.orgId) return NO_PAGE()\n if (!page.exists) return NO_PAGE()\n if (!screenClaimsToBeAPage(page.data() as never) && !(await isRecordTemplate(hostRef, page))) return NO_PAGE()\n const versionId = typeof page.get('versionId') === 'string' ? (page.get('versionId') as string) : ''\n if (!versionId) return EMPTY_PAGE()\n const versions = pageRef.collection('versions')\n const [version, draft] = await Promise.all([versions.doc(versionId).get(), draftRef(versions, versionId).get()])\n if (!version.exists) return EMPTY_PAGE()\n return { pageRef, versionId, version, draft }\n}\n\nexport async function readAiPageContent(input: PageContentReadInput): Promise<PageContentRead | PageContentRefusal> {\n const firestore = input.firestore as Firestore\n const page = await readPage(firestore, input)\n if ('ok' in page) return page\n const base = aiEditBase(page.draft, page.version)\n if (!base) return EMPTY_PAGE()\n const content = aiPageContentElements(base.nodes, input.elementId)\n if (!content) {\n return input.elementId !== undefined && aiDocumentElements(base.nodes)\n ? refusal(404, 'element_not_found', 'No such element on this page', { elementId: 'is not an element of this page' })\n : EMPTY_PAGE()\n }\n return {\n ok: true,\n pageId: input.pageId,\n versionId: page.versionId,\n base: base.from,\n revision: aiPageContentRevision(base.from, page.versionId, base.stored),\n rootId: CANVAS_ROOT_ELEMENT_ID,\n total: content.total,\n elements: content.elements,\n kinds: content.kinds,\n }\n}\n\n// ── Edits, held to the editor's rules ─────────────────────────────────────\n\n/** Props an edit here never names: markup, styles and handlers, which no field of an element offers. */\nconst UNSETTABLE_PROP = /^(html|sx|style|className|dangerouslySetInnerHTML|on[A-Z].*)$/\n\n/** The words a refused element is named with. */\nconst ELEMENT_REFUSALS: Readonly<Record<AssistEditClosedWorldRefusal, string>> = {\n unknown: 'is not an element of this page',\n root: 'is the page’s root, which cannot be changed, moved or removed',\n removed: 'is inside an element an earlier edit removes',\n}\n\nconst UNSETTABLE_WORDS = 'cannot be set through the API; send text in `children` to replace rich text'\n\n/** The whole page as the editor's closed world: every element, its kind, its place and its settings. */\nfunction wholeContext(order: readonly AiDocumentElement[]): AssistEditCanvasContext {\n const nodes: AssistEditCanvasNode[] = order.map(({ id, parentId, index, childCount, node }) => ({\n id,\n componentId: typeof node['componentId'] === 'string' ? node['componentId'] : '',\n parentId,\n index,\n childCount,\n ...(isRecord(node['props']) ? { props: node['props'] as AssistEditCanvasNode['props'] } : {}),\n }))\n return { selectedId: null, total: nodes.length, nodes, whole: true }\n}\n\n/** Where each element of one insert sits in the request, by the local id it is validated under. */\ntype InsertPaths = Map<string, { path: string; kind: string }>\n\ninterface ParsedApiEdits {\n pending: PendingEditOp[]\n /** The edit each pending op came from. */\n edits: number[]\n /** Each insert's element paths, by the edit's index. */\n inserts: Map<number, InsertPaths>\n fields: Record<string, string>\n}\n\n/** The local id an inserted element is validated under: its path among the request's nested elements. */\nconst localId = (steps: readonly number[]) => ['el', ...steps].join('-')\n\n/**\n * The API's edits as the editor's pending ops, through the one closed world\n * (`assistEditClosedWorld`), with every problem the request itself carries\n * named by edit and member.\n */\nfunction parseApiEdits(edits: readonly PageContentEdit[], context: AssistEditCanvasContext): ParsedApiEdits {\n const world = assistEditClosedWorld(context)\n const parsed: ParsedApiEdits = { pending: [], edits: [], inserts: new Map(), fields: {} }\n const { fields } = parsed\n const element = (at: string, nodeId: unknown): AssistEditCanvasNode | null => {\n const found = world.element(nodeId)\n if (typeof found !== 'string') return found\n fields[at] = ELEMENT_REFUSALS[found]\n return null\n }\n const parent = (at: string, parentId: unknown): AssistEditCanvasNode | null => {\n const found = world.parent(parentId)\n if (!found) fields[at] = typeof parentId === 'string' && world.byId.has(parentId) ? ELEMENT_REFUSALS.removed : ELEMENT_REFUSALS.unknown\n return found\n }\n const unsettable = (at: string, props: Record<string, unknown>): boolean => {\n let found = false\n for (const name of Object.keys(props)) {\n if (!UNSETTABLE_PROP.test(name)) continue\n fields[`${at}.${name}`] = UNSETTABLE_WORDS\n found = true\n }\n return found\n }\n const push = (index: number, op: PendingEditOp) => {\n parsed.pending.push(op)\n parsed.edits.push(index)\n }\n\n edits.forEach((edit, index) => {\n const at = `edits[${index}]`\n switch (edit.op) {\n case 'updateProps': {\n const node = element(`${at}.elementId`, edit.elementId)\n const props = isRecord(edit.props) ? edit.props : {}\n if (!Object.keys(props).length) fields[`${at}.props`] = 'sets no property'\n if (unsettable(`${at}.props`, props) || !node || !Object.keys(props).length) return\n push(index, { op: 'updateProps', nodeId: node.id, componentId: node.componentId, props })\n return\n }\n case 'updateStyle': {\n const node = element(`${at}.elementId`, edit.elementId)\n const style = isRecord(edit.style) ? edit.style : {}\n if (!Object.keys(style).length) fields[`${at}.style`] = 'sets no style'\n if (!node || !Object.keys(style).length) return\n push(index, { op: 'updateSx', nodeId: node.id, componentId: node.componentId, sx: style })\n return\n }\n case 'rename': {\n const node = element(`${at}.elementId`, edit.elementId)\n const named = typeof edit.name === 'string' ? assistEditLayerNameRefusal(edit.name) : 'is not text'\n if (named) fields[`${at}.name`] = named\n if (!node || named) return\n push(index, { op: 'rename', nodeId: node.id, componentId: node.componentId, name: edit.name })\n return\n }\n case 'remove': {\n const node = element(`${at}.elementId`, edit.elementId)\n if (!node) return\n world.remove(node.id)\n push(index, { op: 'remove', nodeId: node.id, componentId: node.componentId })\n return\n }\n case 'move': {\n const node = element(`${at}.elementId`, edit.elementId)\n const into = parent(`${at}.parentId`, edit.parentId)\n if (!node || !into) return\n if (world.movesInsideItself(node.id, into.id)) {\n fields[`${at}.parentId`] = 'is inside the element being moved'\n return\n }\n world.move(node.id, into.id)\n push(index, {\n op: 'move',\n nodeId: node.id,\n componentId: node.componentId,\n parentId: into.id,\n parentComponentId: into.componentId,\n index: edit.index,\n })\n return\n }\n case 'insert': {\n const into = parent(`${at}.parentId`, edit.parentId)\n const paths: InsertPaths = new Map()\n const nodes: Record<string, Record<string, unknown>> = {}\n let refused = false\n const visit = (raw: PageContentNewElement, steps: number[], path: string) => {\n const id = localId(steps)\n paths.set(id, { path, kind: raw.kind })\n const props = isRecord(raw.props) ? raw.props : {}\n if (unsettable(`${path}.props`, props)) refused = true\n if (raw.name !== undefined) {\n const named = assistEditLayerNameRefusal(raw.name)\n if (named) {\n fields[`${path}.name`] = named\n refused = true\n }\n }\n const children = Array.isArray(raw.children) ? raw.children : []\n nodes[id] = {\n $id: id,\n componentId: raw.kind,\n nodes: children.map((_, child) => localId([...steps, child])),\n props,\n ...(raw.style !== undefined ? { sx: raw.style } : {}),\n ...(raw.name !== undefined ? { name: raw.name } : {}),\n }\n children.forEach((child, position) => visit(child, [...steps, position], `${path}.children[${position}]`))\n }\n visit(edit.element, [], `${at}.element`)\n if (paths.size > ASSIST_EDIT_MAX_INSERT_NODES) {\n fields[`${at}.element`] = `adds ${paths.size} elements; one insert adds at most ${ASSIST_EDIT_MAX_INSERT_NODES}`\n return\n }\n if (!into || refused) return\n parsed.inserts.set(index, paths)\n push(index, {\n op: 'insertSubtree',\n parentId: into.id,\n parentComponentId: into.componentId,\n index: typeof edit.index === 'number' ? edit.index : null,\n tree: { rootId: localId([]), nodes },\n })\n return\n }\n default:\n fields[`${at}.op`] = 'is not an edit this API makes: updateProps, updateStyle, rename, insert, move or remove'\n }\n })\n return parsed\n}\n\n/** The validator's line, in the words a field is named with. */\nfunction reasonOf(text: string): string {\n return text\n .replace(/; (dropped|truncated|recomputed)$/, '')\n .replace(/^was over (\\d+) characters$/, 'is longer than $1 characters')\n .replace(/^is not a prop of /, 'is not a property of ')\n .replace(/; normalized to \"([^\"]*)\"$/, '; write \"$1\"')\n .trim()\n}\n\nconst escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n/**\n * One violation, named by the edit and the member it is in. A repair line\n * names the element the validator was given — the kind, for a patch; the\n * local id, for an inserted element — and the setting, which is read back\n * off it.\n */\nfunction placeViolation(\n violation: AssistEditViolation,\n edit: PageContentEdit,\n at: string,\n paths: InsertPaths | undefined,\n kindOfElement: (elementId: string) => string,\n): [member: string, reason: string] {\n const { message } = violation\n if (edit.op === 'updateProps') {\n const subject = `${escapeRegExp(kindOfElement(edit.elementId))}\\\\.`\n const names = Object.keys(edit.props ?? {}).sort((a, b) => b.length - a.length)\n for (const name of names) {\n const repaired = new RegExp(`^${subject}${escapeRegExp(name)}:? (.*)$`).exec(message)\n if (repaired) return [`${at}.props.${name}`, reasonOf(repaired[1])]\n if (message.startsWith(`${name} `)) return [`${at}.props.${name}`, reasonOf(message.slice(name.length + 1))]\n }\n return [`${at}.props`, reasonOf(message)]\n }\n if (edit.op === 'updateStyle') {\n const repaired = /: sx\\.([A-Za-z]+)((?:\\.[A-Za-z]+)?) (.*)$/.exec(message)\n if (repaired) return [`${at}.style.${repaired[1]}${repaired[2]}`, reasonOf(repaired[3])]\n return [`${at}.style`, reasonOf(message)]\n }\n if (edit.op === 'move') return [`${at}.parentId`, reasonOf(message)]\n if (edit.op === 'insert' && paths) {\n const ids = [...paths.keys()].sort((a, b) => b.length - a.length)\n const named = (text: string) =>\n ids\n .reduce((out, id) => out.replace(new RegExp(`\\\\b${escapeRegExp(id)}\\\\b(?!-)`, 'g'), paths.get(id)?.path ?? id), text)\n .replace(/\\bchain-\\d+\\b/g, 'the element it is added into')\n .replace(new RegExp(escapeRegExp(CANVAS_ROOT_ELEMENT_ID), 'g'), 'the page’s root')\n for (const id of ids) {\n const path = paths.get(id)?.path as string\n const prop = new RegExp(`^${escapeRegExp(id)}\\\\.([A-Za-z_][A-Za-z0-9_]*)(?:\\\\.[A-Za-z0-9_]+)?:? (.*)$`).exec(message)\n if (prop) return [`${path}.${prop[1] === 'hidden' ? 'hidden' : `props.${prop[1]}`}`, reasonOf(named(prop[2]))]\n const style = new RegExp(`^${escapeRegExp(id)}: sx\\\\.([A-Za-z]+)((?:\\\\.[A-Za-z]+)?) (.*)$`).exec(message)\n if (style) return [`${path}.style.${style[1]}${style[2]}`, reasonOf(named(style[3]))]\n if (new RegExp(`\\\\(${escapeRegExp(id)}\\\\)|^${escapeRegExp(id)}\\\\b(?!-)`).test(message)) return [path, reasonOf(named(message))]\n }\n // An element the page's palette does not offer, as the palette or the\n // sanitizer under it words it.\n const component = /^Component \"([^\"]+)\" (?:is not in the palette|cannot be published)/.exec(message)\n if (component) {\n const found = [...paths.values()].find((entry) => entry.kind === component[1])\n if (found) return [`${found.path}.kind`, 'is not a kind of element a page takes']\n }\n return [`${at}.element`, reasonOf(named(message))]\n }\n return [at, reasonOf(message)]\n}\n\n/** What a built change is, or why the edits were refused. */\ntype BuiltEdit = { proposal: AssistEditProposal } | { refused: PageContentRefusal }\n\n/**\n * The edits validated against one tree and built into the editor's proposal,\n * or refused with every problem named. Pure: the write calls it with the tree\n * its transaction read, so what is checked is what is written.\n */\nexport function buildAiPageContentEdit(input: {\n base: Pick<AiEditWriteBase, 'from' | 'nodes' | 'stored'>\n pageId: string\n hostId: string\n versionId: string\n edits: readonly PageContentEdit[]\n ifRevision?: string\n screenIds: Iterable<string>\n mediaScopes: Iterable<string>\n datasets?: ReturnType<typeof aiEditDatasetScope>\n}): BuiltEdit {\n if (input.ifRevision !== undefined) {\n const current = aiPageContentRevision(input.base.from, input.versionId, input.base.stored)\n if (current !== input.ifRevision) {\n return {\n refused: refusal(409, 'stale', 'The page changed since that revision was read, so nothing was saved. Read it again.', {\n ifRevision: `is not the page’s current revision, ${current}`,\n }),\n }\n }\n }\n if (!input.edits.length || input.edits.length > ASSIST_EDIT_MAX_OPS) {\n return {\n refused: refusal(422, 'edit_refused', 'The edits could not be saved, so none were.', {\n edits: `holds ${input.edits.length}; send 1 to ${ASSIST_EDIT_MAX_OPS} edits`,\n }),\n }\n }\n const order = aiDocumentElements(input.base.nodes)\n if (!order) return { refused: EMPTY_PAGE() }\n const context = wholeContext(order)\n // The kind each element was validated as, which a patch's repair lines name.\n const kinds = new Map(context.nodes.map((node) => [node.id, node.componentId]))\n const parsed = parseApiEdits(input.edits, context)\n const validated = validatePendingEdit({\n surface: 'screen',\n context,\n pending: parsed.pending,\n strict: true,\n references: { screenIds: input.screenIds, mediaScopes: input.mediaScopes },\n ...(input.datasets ? { datasets: input.datasets } : {}),\n })\n const fields = { ...parsed.fields }\n for (const violation of validated.violations) {\n const index = parsed.edits[violation.position]\n const [member, reason] = placeViolation(violation, input.edits[index], `edits[${index}]`, parsed.inserts.get(index), (id) =>\n kinds.get(id) ?? '',\n )\n fields[member] = fields[member] ? `${fields[member]}; ${reason}` : reason\n }\n if (Object.keys(fields).length || validated.ops.length !== input.edits.length) {\n return { refused: refusal(422, 'edit_refused', 'The edits could not be saved, so none were. `fields` names each problem.', fields) }\n }\n return {\n proposal: {\n id: ASSIST_EDIT_ACTION_ID,\n summary: API_EDIT_SUMMARY,\n ops: validated.ops,\n diff: summarizeAssistEditOps(validated.ops),\n dropped: [],\n target: { kind: 'screen', documentId: input.pageId, versionId: input.versionId, hostId: input.hostId },\n },\n }\n}\n\n// ── Writing them ──────────────────────────────────────────────────────────\n\nexport interface AiPageContentDeps {\n writeEdit?: typeof writeAiEdit\n readDatasets?: typeof readAiSiteDatasets\n clearMirror?: typeof clearAiEditMirror\n now?: () => Date\n}\n\n/** The site's pages a link may name: every ordinary page, as a page list holds them. */\nasync function sitePageIds(firestore: Firestore, hostId: string): Promise<string[]> {\n const pages = await firestore.collection('hosts').doc(hostId).collection('screens').select('deletedAt', 'kind').get()\n return pages.docs.filter((page) => screenClaimsToBeAPage(page.data() as never)).map((page) => page.id)\n}\n\n/** A write's own failures, as the statuses an API answers. */\nfunction writeRefusal(error: string, tooLarge?: { bytes: number }): PageContentRefusal {\n if (tooLarge) {\n return refusal(413, 'page_too_large', `${AI_EDIT_TOO_LARGE_COPY} It would be ${tooLarge.bytes} bytes; a page holds at most ${NODE_MAP_MAX_BYTES}.`)\n }\n if (error === AI_EDIT_GONE_COPY) return NO_PAGE()\n if (error === AI_EDIT_NO_NODES_COPY) return EMPTY_PAGE()\n if (error === AI_EDIT_STALE_COPY || error === AI_EDIT_VERSION_GONE_COPY) {\n return refusal(409, 'stale', 'The page changed while the edits were being saved, so nothing was saved. Read it again.')\n }\n return refusal(422, 'edit_refused', 'The editor refused part of these edits, so none were saved.')\n}\n\nexport function createAiPageContentEditor(deps: AiPageContentDeps = {}) {\n const writeEdit = deps.writeEdit ?? writeAiEdit\n const readDatasets = deps.readDatasets ?? readAiSiteDatasets\n const clearMirror = deps.clearMirror ?? clearAiEditMirror\n return async function editAiPageContent(input: PageContentEditInput): Promise<PageContentEditResult | PageContentRefusal> {\n const firestore = input.firestore as Firestore\n if (!Array.isArray(input.edits) || !input.edits.length || input.edits.length > ASSIST_EDIT_MAX_OPS) {\n return refusal(422, 'edit_refused', 'The edits could not be saved, so none were.', {\n edits: `send 1 to ${ASSIST_EDIT_MAX_OPS} edits`,\n })\n }\n const page = await readPage(firestore, input)\n if ('ok' in page) return page\n const [screenIds, datasets] = await Promise.all([\n sitePageIds(firestore, input.hostId),\n readDatasets(input.orgId, input.hostId),\n ])\n const scope = aiEditDatasetScope(datasets, { kind: 'screen', id: input.pageId })\n const write = await writeEdit<PageContentRefusal>(firestore, {\n hostId: input.hostId,\n kind: 'screen',\n id: input.pageId,\n sourceVersionId: page.versionId,\n jobVersionId: input.editId,\n // Always the version's draft: never a new version, never the search\n // fields, so nothing a visitor sees and nothing on the page moves.\n versioning: false,\n newVersion: false,\n writeSeo: false,\n versionName: API_EDIT_SUMMARY,\n uid: input.actor.uid ?? AI_PAGE_CONTENT_API_ACTOR,\n updatedByLabel: input.actor.label,\n updatedVia: input.actor.via ?? 'api',\n maxNodeBytes: NODE_MAP_MAX_BYTES,\n aiJobId: input.editId,\n now: (deps.now ?? (() => new Date()))(),\n proposal: (base) => {\n // The version the page points at moved since the read: the draft the\n // edits were asked of is no longer the page's.\n if (base.pointerVersionId !== page.versionId) {\n return { refused: refusal(409, 'stale', 'The page changed since it was read, so nothing was saved. Read it again.') }\n }\n const built = buildAiPageContentEdit({\n base,\n pageId: input.pageId,\n hostId: input.hostId,\n versionId: page.versionId,\n edits: input.edits,\n ...(input.ifRevision !== undefined ? { ifRevision: input.ifRevision } : {}),\n screenIds,\n mediaScopes: input.mediaScopes,\n datasets: scope,\n })\n return 'proposal' in built ? built.proposal : built\n },\n })\n if (write.ok === false) return write.refused ?? writeRefusal(write.error, write.tooLarge)\n if (write.placement === 'draft') {\n await clearMirror({ orgId: input.orgId, hostId: input.hostId, kind: 'screen', id: input.pageId, versionId: write.versionId }).catch(\n (error: unknown) => console.warn('[page content] the co-edit mirror could not be cleared', { pageId: input.pageId, error }),\n )\n }\n // A write asked again finds what it wrote and writes nothing; its\n // revision is the draft's as it stands.\n const revision = write.written\n ? aiPageContentRevision('draft', write.versionId, write.written.stored)\n : await readAiPageContent({ firestore, orgId: input.orgId, hostId: input.hostId, pageId: input.pageId }).then((read) =>\n read.ok ? read.revision : '',\n )\n return {\n ok: true,\n pageId: input.pageId,\n versionId: write.versionId,\n revision,\n applied: input.edits.length,\n created: (write.written?.inserted ?? []).map(({ op, ids }) => ({ index: op, id: ids[0], ids })),\n }\n }\n}\n\n/** The contract's implementation, as the plugin registers it. */\nexport const aiPageContentService: PageContentService = {\n read: readAiPageContent,\n editDraft: createAiPageContentEditor(),\n}\n\n"],"names":["createHash","NODE_MAP_MAX_BYTES","SCREEN_KIND_TEMPLATE","screenClaimsToBeAPage","CANVAS_ROOT_ELEMENT_ID","aiEditBase","aiEditDatasetScope","clearAiEditMirror","draftRef","writeAiEdit","AI_EDIT_GONE_COPY","AI_EDIT_NO_NODES_COPY","AI_EDIT_STALE_COPY","AI_EDIT_TOO_LARGE_COPY","AI_EDIT_VERSION_GONE_COPY","aiDocumentElements","ASSIST_EDIT_ACTION_ID","summarizeAssistEditOps","AI_REPEAT_DATASET_PROP","AI_SX_ALLOWED_KEYS","aiPaletteEntryWithCapabilities","aiPropIsIconPick","AI_COMPONENT_VISIBILITY_PROPS","AI_PALETTE","readAiSiteDatasets","ASSIST_EDIT_MAX_INSERT_NODES","ASSIST_EDIT_MAX_OPS","ASSIST_EDIT_MOTION_SETTINGS","assistEditClosedWorld","assistEditLayerNameRefusal","validatePendingEdit","AI_PAGE_CONTENT_API_ACTOR","API_EDIT_SUMMARY","isRecord","value","Array","isArray","refusal","status","code","message","fields","ok","Object","keys","length","canonicalJson","map","join","sort","key","JSON","stringify","aiPageContentRevision","from","versionId","stored","hash","update","Uint8Array","digest","slice","kindOf","node","aiPageContentKindProps","kind","entry","props","name","schema","entries","propsSchema","properties","role","propRoles","maxLength","textLimits","type","enum","values","undefined","allowed","aiPageContentKind","options","label","root","displayName","acceptsChildren","READ_ONLY_NODE_FIELDS","elementView","element","settable","readOnlyProps","has","style","readOnlyStyle","readOnly","interactions","filter","field","id","pluginId","parentId","children","hidden","aiPageContentElements","nodes","elementId","order","chosen","start","findIndex","inside","Set","add","push","kinds","Map","elements","set","get","total","NO_PAGE","EMPTY_PAGE","RECORD_PAGES_COLLECTION","isRecordTemplate","hostRef","page","binding","collection","doc","datasetId","exists","readPage","firestore","input","hostId","pageRef","pageId","host","Promise","all","orgId","data","versions","version","draft","readAiPageContent","base","content","revision","rootId","UNSETTABLE_PROP","ELEMENT_REFUSALS","unknown","removed","UNSETTABLE_WORDS","wholeContext","index","childCount","componentId","selectedId","whole","localId","steps","parseApiEdits","edits","context","world","parsed","pending","inserts","at","nodeId","found","parent","byId","unsettable","test","op","forEach","edit","sx","named","remove","into","movesInsideItself","move","parentComponentId","paths","refused","visit","raw","path","$id","_","child","position","size","tree","reasonOf","text","replace","trim","escapeRegExp","placeViolation","violation","kindOfElement","subject","names","a","b","repaired","RegExp","exec","startsWith","ids","reduce","out","prop","component","find","buildAiPageContentEdit","ifRevision","current","validated","surface","strict","references","screenIds","mediaScopes","datasets","violations","member","reason","ops","proposal","summary","diff","dropped","target","documentId","sitePageIds","pages","select","docs","writeRefusal","error","tooLarge","bytes","createAiPageContentEditor","deps","writeEdit","readDatasets","clearMirror","editAiPageContent","write","scope","sourceVersionId","jobVersionId","editId","versioning","newVersion","writeSeo","versionName","uid","actor","updatedByLabel","updatedVia","via","maxNodeBytes","aiJobId","now","Date","pointerVersionId","built","placement","catch","console","warn","written","then","read","applied","created","inserted","aiPageContentService","editDraft"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;QACxC,MAAMjG,WAAW0G,MAAMwB,OAAO,GAC1BnO,sBAAsB,SAAS2M,MAAMzM,SAAS,EAAEyM,MAAMwB,OAAO,CAAChO,MAAM,IACpE,MAAM2F,kBAAkB;YAAEb;YAAWQ,OAAOP,MAAMO,KAAK;YAAEN,QAAQD,MAAMC,MAAM;YAAEE,QAAQH,MAAMG,MAAM;QAAC,GAAG+I,IAAI,CAAC,CAACC,OAC3GA,KAAKhP,EAAE,GAAGgP,KAAKpI,QAAQ,GAAG;QAEhC,OAAO;YACL5G,IAAI;YACJgG,QAAQH,MAAMG,MAAM;YACpBnF,WAAWyM,MAAMzM,SAAS;YAC1B+F;YACAqI,SAASpJ,MAAM+B,KAAK,CAACzH,MAAM;YAC3B+O,SAAS,UAAC5B,iBAAAA,MAAMwB,OAAO,qBAAbxB,eAAe6B,QAAQ,mBAAI,EAAE,EAAE9O,GAAG,CAAC,CAAC,EAAEoI,EAAE,EAAEqC,GAAG,EAAE,GAAM,CAAA;oBAAE1D,OAAOqB;oBAAI/E,IAAIoH,GAAG,CAAC,EAAE;oBAAEA;gBAAI,CAAA;QAC9F;IACF;AACF;AAEA,+DAA+D,GAC/D,OAAO,MAAMsE,uBAA2C;IACtDJ,MAAMvI;IACN4I,WAAWrC;AACb,EAAC"}
|
|
@@ -762,6 +762,46 @@ const triplesToSx = (value)=>{
|
|
|
762
762
|
// An ancestor the outline does not describe: the chain cannot be checked.
|
|
763
763
|
return null;
|
|
764
764
|
}
|
|
765
|
+
/**
|
|
766
|
+
* Code-only elements the public API may place (AGL-4261): a Link Container,
|
|
767
|
+
* the card that is itself one link, which an author places in the Besigner
|
|
768
|
+
* on any page. A model's page pass is still not offered one.
|
|
769
|
+
*/ const ASSIST_EDIT_STRICT_CODE_ONLY_KINDS = [
|
|
770
|
+
'muiLinkBox'
|
|
771
|
+
];
|
|
772
|
+
/** The element that is itself a link around whatever it holds. */ const LINK_CONTAINER_KIND = 'muiLinkBox';
|
|
773
|
+
/** Whether an element renders a link: a Link Container, or a link or page setting with a value. */ function rendersLink(componentId, props) {
|
|
774
|
+
var _ref;
|
|
775
|
+
var _AI_PALETTE_componentId;
|
|
776
|
+
if (componentId === LINK_CONTAINER_KIND) return true;
|
|
777
|
+
const roles = (_ref = (_AI_PALETTE_componentId = AI_PALETTE[componentId]) == null ? void 0 : _AI_PALETTE_componentId.propRoles) != null ? _ref : {};
|
|
778
|
+
return Object.entries(props != null ? props : {}).some(([name, value])=>(roles[name] === 'url' || roles[name] === 'screen') && typeof value === 'string' && value.trim() !== '');
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Why a new subtree would put a link inside a Link Container, or `null`
|
|
782
|
+
* (AGL-4261). An `<a>` inside an `<a>` is invalid HTML, and browsers unnest
|
|
783
|
+
* it, which moves half the card out of its link. Each new element that links
|
|
784
|
+
* is walked out through the new elements, then the element it is added into
|
|
785
|
+
* and that element's own chain.
|
|
786
|
+
*/ function nestedLinkRefusal(nodes, rootId, chain) {
|
|
787
|
+
const chainHasContainer = chain.some((node)=>node.componentId === LINK_CONTAINER_KIND);
|
|
788
|
+
for (const node of Object.values(nodes)){
|
|
789
|
+
if (!rendersLink(node.componentId, node.props)) continue;
|
|
790
|
+
let inside = node.$id === rootId ? chainHasContainer : false;
|
|
791
|
+
let at = node.$id === rootId ? undefined : nodes[node.parentId];
|
|
792
|
+
while(at && !inside){
|
|
793
|
+
if (at.componentId === LINK_CONTAINER_KIND) inside = true;
|
|
794
|
+
else if (at.$id === rootId) inside = chainHasContainer;
|
|
795
|
+
at = at.$id === rootId ? undefined : nodes[at.parentId];
|
|
796
|
+
}
|
|
797
|
+
if (inside) {
|
|
798
|
+
var _ref;
|
|
799
|
+
var _AI_PALETTE_node_componentId;
|
|
800
|
+
return `${(_ref = (_AI_PALETTE_node_componentId = AI_PALETTE[node.componentId]) == null ? void 0 : _AI_PALETTE_node_componentId.displayName) != null ? _ref : node.componentId} links, and it would sit inside a Link Container, which is itself a link; a link inside a link is not valid on a page. Leave its link empty, or place it outside the Link Container`;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
return null;
|
|
804
|
+
}
|
|
765
805
|
/** A class name a class step may toggle: one plain CSS identifier. */ const CLASS_NAME = /^-?[A-Za-z_][A-Za-z0-9_-]{0,40}$/;
|
|
766
806
|
/** Where a redirect may go: a path on the site, or an https address. */ const REDIRECT_URL = /^(\/[^\s<>"']{0,200}|https:\/\/[^\s<>"']{1,200})$/;
|
|
767
807
|
const ELEMENT_STEPS = new Set([
|
|
@@ -1200,6 +1240,45 @@ const DELAYED_STEPS = new Set([
|
|
|
1200
1240
|
...fields
|
|
1201
1241
|
];
|
|
1202
1242
|
}
|
|
1243
|
+
/**
|
|
1244
|
+
* Row keys a repeat fills on every record whatever the dataset's own fields
|
|
1245
|
+
* are: `url`, a record's page on this site (the data plugin's
|
|
1246
|
+
* `RECORD_PAGE_URL_KEY`, AGL-3475), which a card links its record with.
|
|
1247
|
+
* Named here rather than imported, because one plugin never imports another.
|
|
1248
|
+
*/ const ITEM_BUILT_IN_FIELDS = [
|
|
1249
|
+
'url'
|
|
1250
|
+
];
|
|
1251
|
+
/** A field id a whole `{{item.<field>}}` token may name, as `ITEM_TOKEN` reads one. */ const ITEM_FIELD_ID = /^[A-Za-z][A-Za-z0-9_]*$/;
|
|
1252
|
+
/**
|
|
1253
|
+
* The tokens a link or a picture setting may hold whole (AGL-4261): each
|
|
1254
|
+
* field of each dataset the edit knows, its picture field, and the built-in
|
|
1255
|
+
* row keys. A card inside a repeat links its record (`{{item.link}}`,
|
|
1256
|
+
* `{{item.url}}`) and shows its photo (`{{item.image}}`) the way the page jobs'
|
|
1257
|
+
* listings do. Admitting a token here only lets it past the address check;
|
|
1258
|
+
* where it sits — inside a repeat over a dataset that has the field, or on
|
|
1259
|
+
* that dataset's record page — is `itemTokenRefusal`'s check, which every
|
|
1260
|
+
* edit that knows the datasets runs. Anything that is not exactly one of
|
|
1261
|
+
* these stays refused like any other value that is not an address.
|
|
1262
|
+
*/ function datasetItemTokens(scope) {
|
|
1263
|
+
var _scope_datasets;
|
|
1264
|
+
const datasets = (_scope_datasets = scope.datasets) != null ? _scope_datasets : [];
|
|
1265
|
+
if (!datasets.length) return [];
|
|
1266
|
+
const fields = new Set(ITEM_BUILT_IN_FIELDS);
|
|
1267
|
+
for (const dataset of datasets){
|
|
1268
|
+
var _dataset_fieldIds;
|
|
1269
|
+
for (const field of [
|
|
1270
|
+
...(_dataset_fieldIds = dataset.fieldIds) != null ? _dataset_fieldIds : [],
|
|
1271
|
+
...dataset.imageField ? [
|
|
1272
|
+
dataset.imageField
|
|
1273
|
+
] : []
|
|
1274
|
+
]){
|
|
1275
|
+
if (ITEM_FIELD_ID.test(field)) fields.add(field);
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
return [
|
|
1279
|
+
...fields
|
|
1280
|
+
].map((field)=>`{{item.${field}}}`);
|
|
1281
|
+
}
|
|
1203
1282
|
const repeatOf = (props)=>{
|
|
1204
1283
|
const key = props == null ? void 0 : props[AI_REPEAT_DATASET_PROP];
|
|
1205
1284
|
return typeof key === 'string' ? key.trim() : '';
|
|
@@ -1223,7 +1302,7 @@ const repeatOf = (props)=>{
|
|
|
1223
1302
|
}
|
|
1224
1303
|
const dataset = (_scope_datasets = scope.datasets) == null ? void 0 : _scope_datasets.find((one)=>one.id === datasetId);
|
|
1225
1304
|
const known = (dataset == null ? void 0 : (_dataset_fieldIds = dataset.fieldIds) == null ? void 0 : _dataset_fieldIds.length) ? dataset.fieldIds : null;
|
|
1226
|
-
const unknown = known ? fields.filter((field)=>!known.includes(field)) : [];
|
|
1305
|
+
const unknown = known ? fields.filter((field)=>!known.includes(field) && !ITEM_BUILT_IN_FIELDS.includes(field)) : [];
|
|
1227
1306
|
if (!dataset || !unknown.length) return null;
|
|
1228
1307
|
return `${unknown.map((field)=>`{{item.${field}}}`).join(', ')} is not a field of the dataset "${dataset.name}" (its fields: ${(known != null ? known : []).join(', ')})`;
|
|
1229
1308
|
}
|
|
@@ -1255,7 +1334,7 @@ const repeatOf = (props)=>{
|
|
|
1255
1334
|
* normalized — is a violation instead, one per repair, and values are held to
|
|
1256
1335
|
* their types as written. The same validators and the same rules otherwise.
|
|
1257
1336
|
*/ export function validatePendingEdit(output) {
|
|
1258
|
-
var _output_datasets, _scope_datasets
|
|
1337
|
+
var _output_datasets, _scope_datasets;
|
|
1259
1338
|
var _output_references, _output_references1, _output_datasets1;
|
|
1260
1339
|
const byId = new Map(output.context.nodes.map((node)=>[
|
|
1261
1340
|
node.id,
|
|
@@ -1273,16 +1352,16 @@ const repeatOf = (props)=>{
|
|
|
1273
1352
|
]);
|
|
1274
1353
|
const treeContext = _extends({
|
|
1275
1354
|
datasetIds,
|
|
1276
|
-
// A record's
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
] : [])
|
|
1355
|
+
// A record's fields bind whole as a link or a picture (AGL-4261); where
|
|
1356
|
+
// each may sit is held below, by `itemTokenRefusal`.
|
|
1357
|
+
bindingTokens: datasetItemTokens(scope)
|
|
1280
1358
|
}, ((_output_references = output.references) == null ? void 0 : _output_references.screenIds) ? {
|
|
1281
1359
|
screenIds: output.references.screenIds
|
|
1282
1360
|
} : {}, ((_output_references1 = output.references) == null ? void 0 : _output_references1.mediaScopes) ? {
|
|
1283
1361
|
mediaScopes: output.references.mediaScopes
|
|
1284
1362
|
} : {}, strict ? {
|
|
1285
|
-
exact: true
|
|
1363
|
+
exact: true,
|
|
1364
|
+
admitCodeOnly: ASSIST_EDIT_STRICT_CODE_ONLY_KINDS
|
|
1286
1365
|
} : {});
|
|
1287
1366
|
// A patch is held to the same references as a new element; the chat door
|
|
1288
1367
|
// names none, and its patches stay as they were.
|
|
@@ -1380,6 +1459,11 @@ const repeatOf = (props)=>{
|
|
|
1380
1459
|
refuse('nothing survived validation');
|
|
1381
1460
|
return;
|
|
1382
1461
|
}
|
|
1462
|
+
const nested = nestedLinkRefusal(nodes, rootId, chain);
|
|
1463
|
+
if (nested) {
|
|
1464
|
+
refuse(nested);
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1383
1467
|
if (judgesTokens) {
|
|
1384
1468
|
// Each new element's repeats, out through the new ones to the
|
|
1385
1469
|
// element it is added into, then the outline's chain from there.
|