@aglyn/plugins-ai 1.32.0 → 1.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +17 -17
- package/src/lib/jobs/ai-job-campaign-step.js +1 -0
- package/src/lib/jobs/ai-job-campaign-step.js.map +1 -1
- package/src/lib/jobs/ai-job-component-step.js +2 -1
- package/src/lib/jobs/ai-job-component-step.js.map +1 -1
- package/src/lib/jobs/ai-job-drafts.d.ts +8 -0
- package/src/lib/jobs/ai-job-drafts.js +18 -12
- package/src/lib/jobs/ai-job-drafts.js.map +1 -1
- package/src/lib/jobs/ai-job-edit-step.d.ts +5 -0
- package/src/lib/jobs/ai-job-edit-step.js +16 -9
- package/src/lib/jobs/ai-job-edit-step.js.map +1 -1
- package/src/lib/jobs/ai-job-email-step.js +1 -0
- package/src/lib/jobs/ai-job-email-step.js.map +1 -1
- package/src/lib/jobs/ai-job-form-step.js +2 -1
- package/src/lib/jobs/ai-job-form-step.js.map +1 -1
- package/src/lib/jobs/ai-job-layout-step.js +4 -1
- package/src/lib/jobs/ai-job-layout-step.js.map +1 -1
- package/src/lib/jobs/ai-job-navigation-step.js +7 -3
- package/src/lib/jobs/ai-job-navigation-step.js.map +1 -1
- package/src/lib/jobs/ai-job-page-step.js +7 -1
- package/src/lib/jobs/ai-job-page-step.js.map +1 -1
- package/src/lib/jobs/ai-job-privacy-step.d.ts +2 -0
- package/src/lib/jobs/ai-job-privacy-step.js +7 -4
- package/src/lib/jobs/ai-job-privacy-step.js.map +1 -1
- package/src/lib/jobs/ai-job-site-store-pages.js +3 -1
- package/src/lib/jobs/ai-job-site-store-pages.js.map +1 -1
- package/src/lib/jobs/ai-job-store-links-layout.js +8 -4
- package/src/lib/jobs/ai-job-store-links-layout.js.map +1 -1
- package/src/lib/jobs/ai-job-template-step.js +2 -1
- package/src/lib/jobs/ai-job-template-step.js.map +1 -1
- package/src/lib/jobs/ai-site-import-forms.js +2 -1
- package/src/lib/jobs/ai-site-import-forms.js.map +1 -1
- package/src/lib/jobs/ai-site-import-publish.d.ts +1 -1
- package/src/lib/jobs/ai-site-import-publish.js.map +1 -1
- package/src/lib/jobs/ai-site-late-photos.js +2 -1
- package/src/lib/jobs/ai-site-late-photos.js.map +1 -1
- package/src/lib/jobs/ai-site-publish.d.ts +2 -2
- package/src/lib/jobs/ai-site-publish.js +23 -15
- package/src/lib/jobs/ai-site-publish.js.map +1 -1
- package/src/lib/layout-language/ai-layout-frame-source.js +1 -0
- package/src/lib/layout-language/ai-layout-frame-source.js.map +1 -1
- package/src/lib/runtime/ai-palette.generated.js +7 -0
- package/src/lib/runtime/ai-palette.generated.js.map +1 -1
- package/src/lib/server/ai-experiment-versions.js +6 -3
- package/src/lib/server/ai-experiment-versions.js.map +1 -1
- package/src/lib/server/ai-page-content.js +2 -1
- package/src/lib/server/ai-page-content.js.map +1 -1
- package/src/lib/server/ai-seo-apply.js +6 -3
- package/src/lib/server/ai-seo-apply.js.map +1 -1
|
@@ -19,6 +19,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
19
19
|
// with the host document in hand.
|
|
20
20
|
import { holdsSiteKey, siteKeyRefusal } from "@aglyn/aglyn/app-utils/host-permissions";
|
|
21
21
|
import { checkEntitlement, encodeStoredNodes } from "@aglyn/aglyn/server";
|
|
22
|
+
import { contentEditStamp, withoutVersionPublishStamp } from "@aglyn/aglyn/app-utils/content-write-stamp";
|
|
22
23
|
import { pageContentRootId } from "@aglyn/aglyn/app-utils/page-markdown";
|
|
23
24
|
import { decodeStoredNodes } from "@aglyn/aglyn/app-utils/stored-nodes";
|
|
24
25
|
import { lockdownRefusal } from "@aglyn/tenant-data-admin/server/lockdown";
|
|
@@ -117,13 +118,15 @@ const str = (value)=>typeof value === 'string' ? value.trim() : '';
|
|
|
117
118
|
}
|
|
118
119
|
// Compressed at rest, as every write of a version's nodes is.
|
|
119
120
|
const packed = encodeStoredNodes(result.nodes);
|
|
120
|
-
await versionRef.set(_extends({}, sourceData, {
|
|
121
|
+
await versionRef.set(_extends({}, withoutVersionPublishStamp(sourceData), {
|
|
121
122
|
nodes: packed ? Buffer.from(packed) : result.nodes,
|
|
122
123
|
displayName: name,
|
|
123
124
|
createdAt: now,
|
|
124
|
-
updatedAt: now,
|
|
125
125
|
createdBy: input.uid
|
|
126
|
-
}
|
|
126
|
+
}, contentEditStamp({
|
|
127
|
+
uid: input.uid,
|
|
128
|
+
via: `ai-job:${input.job.$id}`
|
|
129
|
+
}, now)));
|
|
127
130
|
versions.push({
|
|
128
131
|
index,
|
|
129
132
|
name,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-experiment-versions.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\n// lockdown-423: via libs/plugins/ai/src/lib/server/ai-jobs-gate.ts\n// The gate carries the org verdict; the handler adds the site's own below,\n// with the host document in hand.\n\nimport { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport {\n checkEntitlement,\n encodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { pageContentRootId } from '@aglyn/aglyn/app-utils/page-markdown'\nimport { decodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { lockdownRefusal } from '@aglyn/tenant-data-admin/server/lockdown'\nimport { getAiJob, writeAiJobAudit } from '../jobs/ai-jobs'\nimport type { AiJob } from '../model/ai-jobs.types'\nimport {\n readAiExperimentVariants,\n type AiExperimentVariantsProposalView,\n} from '../model/ai-experiment-proposal'\nimport { applyAiExperimentVariantCopy } from '../runtime/experiment-variant-copy'\nimport { AI_SEO_APPLY_VERSIONING_COPY } from './ai-seo-apply'\nimport { aiJobsGate } from './ai-jobs-gate'\n\n/**\n * A page's or a section's A/B variants as draft versions (AGL-3603):\n * `POST /api/ai/experiments/versions { orgId, hostId, jobId, screenId, nodeId? }`.\n *\n * An `experiment` job proposes the variants' copy. For an email that copy IS\n * the variant, and the editor holds it. For a page or a section the variant is\n * a version of the page, which the editor only pins — so this door makes one\n * per proposed variant past the first: the page's PUBLISHED version is\n * copied, the variant's headline and body are put into the region the test\n * varies (`runtime/experiment-variant-copy.ts`), and the copy is stored as a\n * new unpublished version named for the variant.\n *\n * ## Nothing goes live\n *\n * The published version, the screen's `versionId` and the experiment document\n * are never touched. The A/B testing editor pins each new version to its\n * variant as an unsaved change; the person reviews the versions, saves the\n * test and starts it. The first proposed variant is the copy as it stands, so\n * it is the control and pins the published version, as the editor's default\n * already does.\n *\n * ## The rungs\n *\n * The jobs read gate (membership, the release flag, `aiGenerative`, the org\n * lockdown); then the site — the job's and the org's — a role that writes the\n * site's content, the site's own lockdown verdict, and the `versioning`\n * entitlement, because a page that already has a version gains retained\n * history here, which is what that entitlement sells. Nothing spends a token.\n *\n * Idempotent: each version's id is derived from the job and the variant, so\n * a second press finds the versions the first made.\n */\n\nconst ID_CHARS = /^[A-Za-z0-9_-]{1,100}$/\n\n/** The id a job's variant version is stored under. */\nexport function aiExperimentVersionId(jobId: string, index: number): string {\n return `ab-${jobId}-${index}`\n}\n\n/** What a version made from a variant is named in the versions list. */\nexport function aiExperimentVersionName(name: string, index: number): string {\n const label = name.replace(/\\s+/g, ' ').trim() || `Variant ${index + 1}`\n return `A/B: ${label}`.slice(0, 80)\n}\n\nexport interface AiExperimentVersionsInput {\n hostId: string\n screenId: string\n /** A section test's element; `null` for a page test. */\n nodeId: string | null\n job: Pick<AiJob, '$id'>\n proposal: AiExperimentVariantsProposalView\n uid: string\n now?: Date\n}\n\nexport interface AiExperimentVersionsResult {\n /** One per variant past the control, in order. */\n versions: Array<{ index: number; name: string; versionId: string; changed: string[] }>\n skipped: Array<{ index: number; reason: string }>\n /** Why no version could be made at all, customer-safe; `null` when one could. */\n refusal: string | null\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/** Make the versions. Exported for the spec, which drives it against a Firestore double. */\nexport async function createAiExperimentVersions(\n firestore: FirebaseFirestore.Firestore,\n input: AiExperimentVersionsInput,\n): Promise<AiExperimentVersionsResult> {\n const now = input.now ?? new Date()\n const screenRef = firestore.collection('hosts').doc(input.hostId).collection('screens').doc(input.screenId)\n const screen = await screenRef.get()\n const empty = (refusal: string): AiExperimentVersionsResult => ({ versions: [], skipped: [], refusal })\n if (!screen.exists || screen.get('deletedAt')) return empty('The page under test no longer exists.')\n const publishedId = str(screen.get('versionId'))\n const source = publishedId ? await screenRef.collection('versions').doc(publishedId).get() : null\n const sourceData = source?.exists ? (source.data() as Record<string, unknown>) : null\n const nodes = sourceData ? decodeStoredNodes<Record<string, unknown>>(sourceData['nodes']) : null\n if (!sourceData || !nodes) return empty('The page has no published version to start from.')\n const rootId = typeof sourceData['rootId'] === 'string' ? sourceData['rootId'] : undefined\n const regionRootId = input.nodeId ?? pageContentRootId(nodes as never, rootId)\n\n const versions: AiExperimentVersionsResult['versions'] = []\n const skipped: AiExperimentVersionsResult['skipped'] = []\n for (const [index, variant] of input.proposal.variants.entries()) {\n // The first variant is the copy as it stands: the control, on the published version.\n if (index === 0) continue\n const versionId = aiExperimentVersionId(input.job.$id, index)\n const name = aiExperimentVersionName(variant.name, index)\n const versionRef = screenRef.collection('versions').doc(versionId)\n const earlier = await versionRef.get()\n if (earlier.exists && !earlier.get('deletedAt')) {\n versions.push({ index, name: str(earlier.get('displayName')) || name, versionId, changed: [] })\n continue\n }\n const result = applyAiExperimentVariantCopy(\n nodes,\n { headline: variant.headline, body: variant.body },\n regionRootId,\n )\n if (!result.changed.length) {\n skipped.push({ index, reason: result.reason ?? 'Nothing on the page took the variant’s copy.' })\n continue\n }\n // Compressed at rest, as every write of a version's nodes is.\n const packed = encodeStoredNodes(result.nodes)\n await versionRef.set({\n ...sourceData,\n nodes: packed ? Buffer.from(packed) : result.nodes,\n displayName: name,\n createdAt: now,\n updatedAt: now,\n createdBy: input.uid,\n })\n versions.push({ index, name, versionId, changed: result.changed })\n }\n return { versions, skipped, refusal: null }\n}\n\nexport async function POST(request: Request): Promise<Response> {\n let body: Record<string, unknown>\n try {\n body = ((await request.json()) ?? {}) as Record<string, unknown>\n } catch {\n body = {}\n }\n const gate = await aiJobsGate(request, String(body['orgId'] ?? ''))\n if (gate instanceof Response) return gate\n const hostId = str(body['hostId'])\n const jobId = str(body['jobId'])\n const screenId = str(body['screenId'])\n const nodeId = str(body['nodeId']) || null\n if (!ID_CHARS.test(hostId) || !ID_CHARS.test(jobId) || !ID_CHARS.test(screenId)) {\n return Response.json({ error: 'Name the site, the page under test and the variants to make' }, { status: 400 })\n }\n if (nodeId !== null && !ID_CHARS.test(nodeId)) {\n return Response.json({ error: 'That is not a section of the page' }, { status: 400 })\n }\n const { firestore, orgId, uid, staff, org, decoded } = gate\n\n const hostSnapshot = await firestore.collection('hosts').doc(hostId).get()\n const host = hostSnapshot.exists ? (hostSnapshot.data() as Record<string, unknown>) : null\n if (!host || host['orgId'] !== orgId) {\n return Response.json({ error: 'Unknown site' }, { status: 404 })\n }\n if (!staff && !holdsSiteKey(host, uid, 'site.edit')) {\n return Response.json({ error: siteKeyRefusal('site.edit') }, { status: 403 })\n }\n const locked = await lockdownRefusal({\n request,\n staff,\n uid,\n org: org as Record<string, unknown>,\n host: host as never,\n })\n if (locked) return locked\n if (!checkEntitlement(org, 'versioning')) {\n return Response.json({ error: AI_SEO_APPLY_VERSIONING_COPY }, { status: 403 })\n }\n\n const job = await getAiJob(firestore, orgId, jobId)\n if (!job || job.kind !== 'experiment' || job.hostId !== hostId) {\n return Response.json({ error: 'Unknown variants' }, { status: 404 })\n }\n if (job.status !== 'done') {\n return Response.json({ error: 'The variants are still being written' }, { status: 409 })\n }\n const proposal = readAiExperimentVariants(\n (job.outputs ?? []).find((output) => output.resource === 'experiment')?.proposal,\n )\n if (!proposal || proposal.target === 'email') {\n return Response.json({ error: 'These variants are not a page’s or a section’s' }, { status: 409 })\n }\n if (proposal.target === 'section' && !nodeId) {\n return Response.json({ error: 'Pick the section under test first' }, { status: 400 })\n }\n\n const result = await createAiExperimentVersions(firestore, {\n hostId,\n screenId,\n nodeId: proposal.target === 'section' ? nodeId : null,\n job,\n proposal,\n uid,\n })\n if (result.refusal) return Response.json({ error: result.refusal }, { status: 409 })\n const made = result.versions.filter((entry) => entry.changed.length)\n if (made.length) {\n await writeAiJobAudit(firestore, {\n action: 'ai.job.apply',\n actorUid: uid,\n actorEmail: decoded.email ?? null,\n orgId,\n jobId,\n after: { hostId, screenId, versions: made.map((entry) => entry.versionId) },\n })\n }\n return Response.json(result, { status: 200, headers: { 'Cache-Control': 'no-store' } })\n}\n\nexport const dynamic = 'force-dynamic'\n"],"names":["holdsSiteKey","siteKeyRefusal","checkEntitlement","encodeStoredNodes","pageContentRootId","decodeStoredNodes","lockdownRefusal","getAiJob","writeAiJobAudit","readAiExperimentVariants","applyAiExperimentVariantCopy","AI_SEO_APPLY_VERSIONING_COPY","aiJobsGate","ID_CHARS","aiExperimentVersionId","jobId","index","aiExperimentVersionName","name","label","replace","trim","slice","str","value","createAiExperimentVersions","firestore","input","now","Date","screenRef","collection","doc","hostId","screenId","screen","get","empty","refusal","versions","skipped","exists","publishedId","source","sourceData","data","nodes","rootId","undefined","regionRootId","nodeId","variant","proposal","variants","entries","versionId","job","$id","versionRef","earlier","push","changed","result","headline","body","length","reason","packed","set","Buffer","from","displayName","createdAt","updatedAt","createdBy","uid","POST","request","json","gate","String","Response","test","error","status","orgId","staff","org","decoded","hostSnapshot","host","locked","kind","outputs","find","output","resource","target","made","filter","entry","action","actorUid","actorEmail","email","after","map","headers","dynamic"],"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4B,UAAU,GAAEf,iBAAAA,QAAQgB,KAAK,YAAbhB,iBAAiB;YAC7BH;YACAtE;YACA0F,OAAO;gBAAExE;gBAAQC;gBAAUK,UAAU2D,KAAKQ,GAAG,CAAC,CAACN,QAAUA,MAAM7C,SAAS;YAAE;QAC5E;IACF;IACA,OAAO0B,SAASH,IAAI,CAAChB,QAAQ;QAAEsB,QAAQ;QAAKuB,SAAS;YAAE,iBAAiB;QAAW;IAAE;AACvF;AAEA,OAAO,MAAMC,UAAU,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-experiment-versions.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\n// lockdown-423: via libs/plugins/ai/src/lib/server/ai-jobs-gate.ts\n// The gate carries the org verdict; the handler adds the site's own below,\n// with the host document in hand.\n\nimport { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport {\n checkEntitlement,\n encodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { contentEditStamp, withoutVersionPublishStamp } from '@aglyn/aglyn/app-utils/content-write-stamp'\nimport { pageContentRootId } from '@aglyn/aglyn/app-utils/page-markdown'\nimport { decodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { lockdownRefusal } from '@aglyn/tenant-data-admin/server/lockdown'\nimport { getAiJob, writeAiJobAudit } from '../jobs/ai-jobs'\nimport type { AiJob } from '../model/ai-jobs.types'\nimport {\n readAiExperimentVariants,\n type AiExperimentVariantsProposalView,\n} from '../model/ai-experiment-proposal'\nimport { applyAiExperimentVariantCopy } from '../runtime/experiment-variant-copy'\nimport { AI_SEO_APPLY_VERSIONING_COPY } from './ai-seo-apply'\nimport { aiJobsGate } from './ai-jobs-gate'\n\n/**\n * A page's or a section's A/B variants as draft versions (AGL-3603):\n * `POST /api/ai/experiments/versions { orgId, hostId, jobId, screenId, nodeId? }`.\n *\n * An `experiment` job proposes the variants' copy. For an email that copy IS\n * the variant, and the editor holds it. For a page or a section the variant is\n * a version of the page, which the editor only pins — so this door makes one\n * per proposed variant past the first: the page's PUBLISHED version is\n * copied, the variant's headline and body are put into the region the test\n * varies (`runtime/experiment-variant-copy.ts`), and the copy is stored as a\n * new unpublished version named for the variant.\n *\n * ## Nothing goes live\n *\n * The published version, the screen's `versionId` and the experiment document\n * are never touched. The A/B testing editor pins each new version to its\n * variant as an unsaved change; the person reviews the versions, saves the\n * test and starts it. The first proposed variant is the copy as it stands, so\n * it is the control and pins the published version, as the editor's default\n * already does.\n *\n * ## The rungs\n *\n * The jobs read gate (membership, the release flag, `aiGenerative`, the org\n * lockdown); then the site — the job's and the org's — a role that writes the\n * site's content, the site's own lockdown verdict, and the `versioning`\n * entitlement, because a page that already has a version gains retained\n * history here, which is what that entitlement sells. Nothing spends a token.\n *\n * Idempotent: each version's id is derived from the job and the variant, so\n * a second press finds the versions the first made.\n */\n\nconst ID_CHARS = /^[A-Za-z0-9_-]{1,100}$/\n\n/** The id a job's variant version is stored under. */\nexport function aiExperimentVersionId(jobId: string, index: number): string {\n return `ab-${jobId}-${index}`\n}\n\n/** What a version made from a variant is named in the versions list. */\nexport function aiExperimentVersionName(name: string, index: number): string {\n const label = name.replace(/\\s+/g, ' ').trim() || `Variant ${index + 1}`\n return `A/B: ${label}`.slice(0, 80)\n}\n\nexport interface AiExperimentVersionsInput {\n hostId: string\n screenId: string\n /** A section test's element; `null` for a page test. */\n nodeId: string | null\n job: Pick<AiJob, '$id'>\n proposal: AiExperimentVariantsProposalView\n uid: string\n now?: Date\n}\n\nexport interface AiExperimentVersionsResult {\n /** One per variant past the control, in order. */\n versions: Array<{ index: number; name: string; versionId: string; changed: string[] }>\n skipped: Array<{ index: number; reason: string }>\n /** Why no version could be made at all, customer-safe; `null` when one could. */\n refusal: string | null\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/** Make the versions. Exported for the spec, which drives it against a Firestore double. */\nexport async function createAiExperimentVersions(\n firestore: FirebaseFirestore.Firestore,\n input: AiExperimentVersionsInput,\n): Promise<AiExperimentVersionsResult> {\n const now = input.now ?? new Date()\n const screenRef = firestore.collection('hosts').doc(input.hostId).collection('screens').doc(input.screenId)\n const screen = await screenRef.get()\n const empty = (refusal: string): AiExperimentVersionsResult => ({ versions: [], skipped: [], refusal })\n if (!screen.exists || screen.get('deletedAt')) return empty('The page under test no longer exists.')\n const publishedId = str(screen.get('versionId'))\n const source = publishedId ? await screenRef.collection('versions').doc(publishedId).get() : null\n const sourceData = source?.exists ? (source.data() as Record<string, unknown>) : null\n const nodes = sourceData ? decodeStoredNodes<Record<string, unknown>>(sourceData['nodes']) : null\n if (!sourceData || !nodes) return empty('The page has no published version to start from.')\n const rootId = typeof sourceData['rootId'] === 'string' ? sourceData['rootId'] : undefined\n const regionRootId = input.nodeId ?? pageContentRootId(nodes as never, rootId)\n\n const versions: AiExperimentVersionsResult['versions'] = []\n const skipped: AiExperimentVersionsResult['skipped'] = []\n for (const [index, variant] of input.proposal.variants.entries()) {\n // The first variant is the copy as it stands: the control, on the published version.\n if (index === 0) continue\n const versionId = aiExperimentVersionId(input.job.$id, index)\n const name = aiExperimentVersionName(variant.name, index)\n const versionRef = screenRef.collection('versions').doc(versionId)\n const earlier = await versionRef.get()\n if (earlier.exists && !earlier.get('deletedAt')) {\n versions.push({ index, name: str(earlier.get('displayName')) || name, versionId, changed: [] })\n continue\n }\n const result = applyAiExperimentVariantCopy(\n nodes,\n { headline: variant.headline, body: variant.body },\n regionRootId,\n )\n if (!result.changed.length) {\n skipped.push({ index, reason: result.reason ?? 'Nothing on the page took the variant’s copy.' })\n continue\n }\n // Compressed at rest, as every write of a version's nodes is.\n const packed = encodeStoredNodes(result.nodes)\n await versionRef.set({\n // A new version beside the live one: not published by anyone yet.\n ...withoutVersionPublishStamp(sourceData),\n nodes: packed ? Buffer.from(packed) : result.nodes,\n displayName: name,\n createdAt: now,\n createdBy: input.uid,\n ...contentEditStamp({ uid: input.uid, via: `ai-job:${input.job.$id}` }, now),\n })\n versions.push({ index, name, versionId, changed: result.changed })\n }\n return { versions, skipped, refusal: null }\n}\n\nexport async function POST(request: Request): Promise<Response> {\n let body: Record<string, unknown>\n try {\n body = ((await request.json()) ?? {}) as Record<string, unknown>\n } catch {\n body = {}\n }\n const gate = await aiJobsGate(request, String(body['orgId'] ?? ''))\n if (gate instanceof Response) return gate\n const hostId = str(body['hostId'])\n const jobId = str(body['jobId'])\n const screenId = str(body['screenId'])\n const nodeId = str(body['nodeId']) || null\n if (!ID_CHARS.test(hostId) || !ID_CHARS.test(jobId) || !ID_CHARS.test(screenId)) {\n return Response.json({ error: 'Name the site, the page under test and the variants to make' }, { status: 400 })\n }\n if (nodeId !== null && !ID_CHARS.test(nodeId)) {\n return Response.json({ error: 'That is not a section of the page' }, { status: 400 })\n }\n const { firestore, orgId, uid, staff, org, decoded } = gate\n\n const hostSnapshot = await firestore.collection('hosts').doc(hostId).get()\n const host = hostSnapshot.exists ? (hostSnapshot.data() as Record<string, unknown>) : null\n if (!host || host['orgId'] !== orgId) {\n return Response.json({ error: 'Unknown site' }, { status: 404 })\n }\n if (!staff && !holdsSiteKey(host, uid, 'site.edit')) {\n return Response.json({ error: siteKeyRefusal('site.edit') }, { status: 403 })\n }\n const locked = await lockdownRefusal({\n request,\n staff,\n uid,\n org: org as Record<string, unknown>,\n host: host as never,\n })\n if (locked) return locked\n if (!checkEntitlement(org, 'versioning')) {\n return Response.json({ error: AI_SEO_APPLY_VERSIONING_COPY }, { status: 403 })\n }\n\n const job = await getAiJob(firestore, orgId, jobId)\n if (!job || job.kind !== 'experiment' || job.hostId !== hostId) {\n return Response.json({ error: 'Unknown variants' }, { status: 404 })\n }\n if (job.status !== 'done') {\n return Response.json({ error: 'The variants are still being written' }, { status: 409 })\n }\n const proposal = readAiExperimentVariants(\n (job.outputs ?? []).find((output) => output.resource === 'experiment')?.proposal,\n )\n if (!proposal || proposal.target === 'email') {\n return Response.json({ error: 'These variants are not a page’s or a section’s' }, { status: 409 })\n }\n if (proposal.target === 'section' && !nodeId) {\n return Response.json({ error: 'Pick the section under test first' }, { status: 400 })\n }\n\n const result = await createAiExperimentVersions(firestore, {\n hostId,\n screenId,\n nodeId: proposal.target === 'section' ? nodeId : null,\n job,\n proposal,\n uid,\n })\n if (result.refusal) return Response.json({ error: result.refusal }, { status: 409 })\n const made = result.versions.filter((entry) => entry.changed.length)\n if (made.length) {\n await writeAiJobAudit(firestore, {\n action: 'ai.job.apply',\n actorUid: uid,\n actorEmail: decoded.email ?? null,\n orgId,\n jobId,\n after: { hostId, screenId, versions: made.map((entry) => entry.versionId) },\n })\n }\n return Response.json(result, { status: 200, headers: { 'Cache-Control': 'no-store' } })\n}\n\nexport const dynamic = 'force-dynamic'\n"],"names":["holdsSiteKey","siteKeyRefusal","checkEntitlement","encodeStoredNodes","contentEditStamp","withoutVersionPublishStamp","pageContentRootId","decodeStoredNodes","lockdownRefusal","getAiJob","writeAiJobAudit","readAiExperimentVariants","applyAiExperimentVariantCopy","AI_SEO_APPLY_VERSIONING_COPY","aiJobsGate","ID_CHARS","aiExperimentVersionId","jobId","index","aiExperimentVersionName","name","label","replace","trim","slice","str","value","createAiExperimentVersions","firestore","input","now","Date","screenRef","collection","doc","hostId","screenId","screen","get","empty","refusal","versions","skipped","exists","publishedId","source","sourceData","data","nodes","rootId","undefined","regionRootId","nodeId","variant","proposal","variants","entries","versionId","job","$id","versionRef","earlier","push","changed","result","headline","body","length","reason","packed","set","Buffer","from","displayName","createdAt","createdBy","uid","via","POST","request","json","gate","String","Response","test","error","status","orgId","staff","org","decoded","hostSnapshot","host","locked","kind","outputs","find","output","resource","target","made","filter","entry","action","actorUid","actorEmail","email","after","map","headers","dynamic"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,mEAAmE;AACnE,2EAA2E;AAC3E,kCAAkC;AAElC,SAASA,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AACtF,SACEC,gBAAgB,EAChBC,iBAAiB,QACZ,sBAAqB;AAC5B,SAASC,gBAAgB,EAAEC,0BAA0B,QAAQ,6CAA4C;AACzG,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,QAAQ,EAAEC,eAAe,QAAQ,qBAAiB;AAE3D,SACEC,wBAAwB,QAEnB,qCAAiC;AACxC,SAASC,4BAA4B,QAAQ,wCAAoC;AACjF,SAASC,4BAA4B,QAAQ,oBAAgB;AAC7D,SAASC,UAAU,QAAQ,oBAAgB;AAE3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+BC,GAED,MAAMC,WAAW;AAEjB,oDAAoD,GACpD,OAAO,SAASC,sBAAsBC,KAAa,EAAEC,KAAa;IAChE,OAAO,CAAC,GAAG,EAAED,MAAM,CAAC,EAAEC,OAAO;AAC/B;AAEA,sEAAsE,GACtE,OAAO,SAASC,wBAAwBC,IAAY,EAAEF,KAAa;IACjE,MAAMG,QAAQD,KAAKE,OAAO,CAAC,QAAQ,KAAKC,IAAI,MAAM,CAAC,QAAQ,EAAEL,QAAQ,GAAG;IACxE,OAAO,CAAC,KAAK,EAAEG,OAAO,CAACG,KAAK,CAAC,GAAG;AAClC;AAqBA,MAAMC,MAAM,CAACC,QAA4B,OAAOA,UAAU,WAAWA,MAAMH,IAAI,KAAK;AAEpF,0FAA0F,GAC1F,OAAO,eAAeI,2BACpBC,SAAsC,EACtCC,KAAgC;QAEpBA,YAWSA;IAXrB,MAAMC,OAAMD,aAAAA,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I,CAAC;QAAEK,OAAOrB,OAAOxB,OAAO;IAAC,GAAG;QAAE8C,QAAQ;IAAI;IAClF,MAAMc,OAAOpC,OAAOvB,QAAQ,CAAC4D,MAAM,CAAC,CAACC,QAAUA,MAAMvC,OAAO,CAACI,MAAM;IACnE,IAAIiC,KAAKjC,MAAM,EAAE;YAIDuB;QAHd,MAAMhF,gBAAgBkB,WAAW;YAC/B2E,QAAQ;YACRC,UAAU5B;YACV6B,UAAU,GAAEf,iBAAAA,QAAQgB,KAAK,YAAbhB,iBAAiB;YAC7BH;YACAtE;YACA0F,OAAO;gBAAExE;gBAAQC;gBAAUK,UAAU2D,KAAKQ,GAAG,CAAC,CAACN,QAAUA,MAAM7C,SAAS;YAAE;QAC5E;IACF;IACA,OAAO0B,SAASH,IAAI,CAAChB,QAAQ;QAAEsB,QAAQ;QAAKuB,SAAS;YAAE,iBAAiB;QAAW;IAAE;AACvF;AAEA,OAAO,MAAMC,UAAU,gBAAe"}
|
|
@@ -663,7 +663,7 @@ export function createAiPageContentEditor(deps = {}) {
|
|
|
663
663
|
const readDatasets = (_deps_readDatasets = deps.readDatasets) != null ? _deps_readDatasets : readAiSiteDatasets;
|
|
664
664
|
const clearMirror = (_deps_clearMirror = deps.clearMirror) != null ? _deps_clearMirror : clearAiEditMirror;
|
|
665
665
|
return async function editAiPageContent(input) {
|
|
666
|
-
var _input_actor_uid, _deps_now, _write_refused, _ref;
|
|
666
|
+
var _input_actor_uid, _input_actor_via, _deps_now, _write_refused, _ref;
|
|
667
667
|
var _write_written;
|
|
668
668
|
const firestore = input.firestore;
|
|
669
669
|
if (!Array.isArray(input.edits) || !input.edits.length || input.edits.length > ASSIST_EDIT_MAX_OPS) {
|
|
@@ -695,6 +695,7 @@ export function createAiPageContentEditor(deps = {}) {
|
|
|
695
695
|
versionName: API_EDIT_SUMMARY,
|
|
696
696
|
uid: (_input_actor_uid = input.actor.uid) != null ? _input_actor_uid : AI_PAGE_CONTENT_API_ACTOR,
|
|
697
697
|
updatedByLabel: input.actor.label,
|
|
698
|
+
updatedVia: (_input_actor_via = input.actor.via) != null ? _input_actor_via : 'api',
|
|
698
699
|
maxNodeBytes: NODE_MAP_MAX_BYTES,
|
|
699
700
|
aiJobId: input.editId,
|
|
700
701
|
now: ((_deps_now = deps.now) != null ? _deps_now : ()=>new Date())(),
|
|
@@ -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 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","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,EACzBC,kBAAkB,QAEb,0BAAsB;AAC7B,SACEC,qBAAqB,EACrBC,sBAAsB,QAIjB,0BAAsB;AAC7B,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,8BAA8B,EAC9BC,gBAAgB,QACX,6BAAyB;AAChC,SAASC,UAAU,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AAW0G,MAAMsB,OAAO,GAC1B7N,sBAAsB,SAASuM,MAAMrM,SAAS,EAAEqM,MAAMsB,OAAO,CAAC1N,MAAM,IACpE,MAAMuF,kBAAkB;YAAElB;YAAWa,OAAOZ,MAAMY,KAAK;YAAER,QAAQJ,MAAMI,MAAM;YAAEE,QAAQN,MAAMM,MAAM;QAAC,GAAG+I,IAAI,CAAC,CAACC,OAC3GA,KAAK1O,EAAE,GAAG0O,KAAKlI,QAAQ,GAAG;QAEhC,OAAO;YACLxG,IAAI;YACJ0F,QAAQN,MAAMM,MAAM;YACpB7E,WAAWqM,MAAMrM,SAAS;YAC1B2F;YACAmI,SAASvJ,MAAMoC,KAAK,CAACrH,MAAM;YAC3ByO,SAAS,UAAC1B,iBAAAA,MAAMsB,OAAO,qBAAbtB,eAAe2B,QAAQ,mBAAI,EAAE,EAAExO,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,MAAMoE,uBAA2C;IACtDJ,MAAMrI;IACN0I,WAAWnC;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 { 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,EACzBC,kBAAkB,QAEb,0BAAsB;AAC7B,SACEC,qBAAqB,EACrBC,sBAAsB,QAIjB,0BAAsB;AAC7B,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,8BAA8B,EAC9BC,gBAAgB,QACX,6BAAyB;AAChC,SAASC,UAAU,QAAQ,qCAAiC;AAC5D,SAASC,kBAAkB,QAAQ,+BAA2B;AAC9D,SACEC,4BAA4B,EAC5BC,mBAAmB,EACnBC,2BAA2B,EAC3BC,qBAAqB,EACrBC,0BAA0B,EAC1BC,mBAAmB,QAId,mBAAe;AAwCtB,qFAAqF,GACrF,OAAO,MAAMC,4BAA4B,MAAK;AAE9C,yDAAyD,GACzD,MAAMC,mBAAmB;AAEzB,MAAMC,WAAW,CAACC,QAChB,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACC,MAAMC,OAAO,CAACF;AAEhE,MAAMG,UAAU,CACdC,QACAC,MACAC,SACAC,SACwB;QAAEC,IAAI;QAAOJ;QAAQC;QAAMC;OAAaC,UAAUE,OAAOC,IAAI,CAACH,QAAQI,MAAM,GAAG;QAAEJ;IAAO,IAAI,CAAC;AAEvH,6EAA6E;AAE7E,8DAA8D,GAC9D,SAASK,cAAcZ,KAAc;IACnC,IAAIC,MAAMC,OAAO,CAACF,QAAQ,OAAO,CAAC,CAAC,EAAEA,MAAMa,G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AE,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"}
|
|
@@ -19,6 +19,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
19
19
|
// with the host document in hand.
|
|
20
20
|
import { holdsSiteKey, siteKeyRefusal } from "@aglyn/aglyn/app-utils/host-permissions";
|
|
21
21
|
import { checkEntitlement, createResourceUid, encodeStoredNodes } from "@aglyn/aglyn/server";
|
|
22
|
+
import { contentEditStamp, withoutVersionPublishStamp } from "@aglyn/aglyn/app-utils/content-write-stamp";
|
|
22
23
|
import { pageContentRootId } from "@aglyn/aglyn/app-utils/page-markdown";
|
|
23
24
|
import { decodeStoredNodes } from "@aglyn/aglyn/app-utils/stored-nodes";
|
|
24
25
|
import { lockdownRefusal } from "@aglyn/tenant-data-admin/server/lockdown";
|
|
@@ -134,13 +135,15 @@ const str = (value)=>typeof value === 'string' ? value.trim() : '';
|
|
|
134
135
|
const versionId = createResourceUid();
|
|
135
136
|
// Compressed at rest, as every write of a version's nodes is.
|
|
136
137
|
const packed = encodeStoredNodes(result.nodes);
|
|
137
|
-
await screenRef.collection('versions').doc(versionId).create(_extends({}, sourceData, {
|
|
138
|
+
await screenRef.collection('versions').doc(versionId).create(_extends({}, withoutVersionPublishStamp(sourceData), {
|
|
138
139
|
nodes: packed ? Buffer.from(packed) : result.nodes,
|
|
139
140
|
displayName: 'SEO fixes',
|
|
140
141
|
createdAt: now,
|
|
141
|
-
updatedAt: now,
|
|
142
142
|
createdBy: input.uid
|
|
143
|
-
}
|
|
143
|
+
}, contentEditStamp({
|
|
144
|
+
uid: input.uid,
|
|
145
|
+
via: `ai-job:${input.job.$id}`
|
|
146
|
+
}, now)));
|
|
144
147
|
opened[screenId] = versionId;
|
|
145
148
|
versions.push({
|
|
146
149
|
screenId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-seo-apply.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\n// lockdown-423: via libs/plugins/ai/src/lib/server/ai-jobs-gate.ts\n// The gate carries the org verdict; the handler adds the site's own below,\n// with the host document in hand.\n\nimport { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport {\n checkEntitlement,\n createResourceUid,\n encodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { pageContentRootId } from '@aglyn/aglyn/app-utils/page-markdown'\nimport { decodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { lockdownRefusal } from '@aglyn/tenant-data-admin/server/lockdown'\nimport { logAiSeoApplied } from '../activity/ai-activity'\nimport {\n aiJobSummary,\n getAiJob,\n recordAiJobApplied,\n writeAiJobAudit,\n} from '../jobs/ai-jobs'\nimport type { AiJob, AiJobApplied } from '../model/ai-jobs.types'\nimport { aiSeoAuditView, aiSeoJobTarget, type AiSeoAuditView } from '../model/ai-seo'\nimport { applyAiSeoContentFixes } from '../runtime/seo-content-fixes'\nimport { aiJobsGate } from './ai-jobs-gate'\n\n/**\n * Apply a site audit (AGL-2910): `POST /api/ai/seo/apply { orgId, hostId, jobId }`.\n *\n * \"Apply all\" does two things and neither changes what the published site\n * serves.\n *\n * - **Content fixes open a NEW version per page.** The page's published\n * version is copied, the fixes are applied to the copy — an image\n * description, the page's one main heading — and the copy is stored as a\n * new unpublished version. The published version and the screen's\n * `versionId` are never touched: a person opens the draft, looks, and\n * publishes it through the door that already exists.\n * - **Listing values are STAGED, not written.** A page's search title and\n * description are served straight from the screen document, so writing\n * them would publish them. The apply records which pages have values\n * waiting; the page's SEO card offers them, and its Save SEO is the write.\n *\n * The site-wide proposals — structured data and the agent guidance — are the\n * site SEO form's to save, and the card puts them there as unsaved edits; this\n * door never writes the host document.\n *\n * Idempotent per job: a page this job already opened a version for keeps\n * that version, so a second press opens nothing new.\n *\n * ## The rungs\n *\n * The jobs read gate (membership, the release flag, `aiGenerative`, the org\n * lockdown), then the site: it must be the job's and the org's, the caller\n * must hold a role that writes the site's content — the role creating a\n * version asks for — and the site's own lockdown verdict must admit a write.\n * Nothing here spends a token, so there is no reservation.\n */\n\nconst ID_CHARS = /^[A-Za-z0-9_-]{1,100}$/\n\n/** The version history sentence the versions route gives, for a plan without it. */\nexport const AI_SEO_APPLY_VERSIONING_COPY =\n 'Version history requires a Pro plan — see Billing to upgrade'\n\nexport interface AiSeoApplyInput {\n orgId: string\n hostId: string\n job: AiJob\n view: AiSeoAuditView\n uid: string\n /** Whether the org's plan keeps more than one version of a page. */\n versioning: boolean\n now?: Date\n}\n\nexport interface AiSeoApplyResult {\n job: AiJob\n /** The version each page's content fixes went into; `fixes` is 0 for one opened by an earlier apply. */\n versions: Array<{ screenId: string; versionId: string; name: string; fixes: number }>\n /** Pages whose listing values wait in their SEO card. */\n staged: string[]\n skipped: Array<{ screenId: string; reason: string }>\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/**\n * Open the versions and record the apply. Exported for the spec, which drives\n * it against a Firestore double and proves what it leaves alone.\n */\nexport async function applyAiSeoAudit(\n firestore: FirebaseFirestore.Firestore,\n input: AiSeoApplyInput,\n): Promise<AiSeoApplyResult> {\n const now = input.now ?? new Date()\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n const opened = { ...(input.job.applied?.versions ?? {}) }\n const staged = new Set(input.job.applied?.staged ?? [])\n const names = new Map(input.view.report.pages.map((page) => [page.screenId, page.name]))\n const versions: AiSeoApplyResult['versions'] = []\n const skipped: AiSeoApplyResult['skipped'] = []\n\n for (const fix of Object.values(input.view.fixes)) {\n const screenId = fix.screenId\n const name = names.get(screenId) ?? screenId\n if (Object.keys(fix.values).length) staged.add(screenId)\n if (!fix.content.length) continue\n const screenRef = hostRef.collection('screens').doc(screenId)\n\n const earlier = opened[screenId]\n if (earlier && (await screenRef.collection('versions').doc(earlier).get()).exists) {\n versions.push({ screenId, versionId: earlier, name, fixes: 0 })\n continue\n }\n if (!input.versioning) {\n skipped.push({ screenId, reason: AI_SEO_APPLY_VERSIONING_COPY })\n continue\n }\n const screenSnapshot = await screenRef.get()\n if (!screenSnapshot.exists || screenSnapshot.get('deletedAt')) {\n skipped.push({ screenId, reason: 'The page no longer exists.' })\n continue\n }\n const publishedId = str(screenSnapshot.get('versionId'))\n const source = publishedId ? await screenRef.collection('versions').doc(publishedId).get() : null\n const sourceData = source?.exists ? (source.data() as Record<string, unknown>) : null\n const nodes = sourceData ? decodeStoredNodes<Record<string, unknown>>(sourceData['nodes']) : null\n if (!sourceData || !nodes) {\n skipped.push({ screenId, reason: 'The page has no published version to start from.' })\n continue\n }\n const rootId = typeof sourceData['rootId'] === 'string' ? sourceData['rootId'] : undefined\n const result = applyAiSeoContentFixes(\n nodes,\n fix.content,\n pageContentRootId(nodes as never, rootId),\n )\n if (!result.applied.length) {\n skipped.push({ screenId, reason: result.skipped[0]?.reason ?? 'Nothing on the page needed changing.' })\n continue\n }\n const versionId = createResourceUid()\n // Compressed at rest, as every write of a version's nodes is.\n const packed = encodeStoredNodes(result.nodes)\n await screenRef\n .collection('versions')\n .doc(versionId)\n .create({\n ...sourceData,\n nodes: packed ? Buffer.from(packed) : result.nodes,\n displayName: 'SEO fixes',\n createdAt: now,\n updatedAt: now,\n createdBy: input.uid,\n })\n opened[screenId] = versionId\n versions.push({ screenId, versionId, name, fixes: result.applied.length })\n }\n\n const applied: AiJobApplied = {\n // The Admin SDK stores a `Date` as the timestamp the type describes.\n at: now as unknown as AiJobApplied['at'],\n by: input.uid,\n versions: opened,\n staged: [...staged],\n }\n const job = await recordAiJobApplied(firestore, input.orgId, input.job.$id, applied, now)\n return { job, versions, staged: [...staged], skipped }\n}\n\nexport async function POST(request: Request): Promise<Response> {\n let body: Record<string, unknown>\n try {\n body = ((await request.json()) ?? {}) as Record<string, unknown>\n } catch {\n body = {}\n }\n const gate = await aiJobsGate(request, String(body['orgId'] ?? ''))\n if (gate instanceof Response) return gate\n const hostId = str(body['hostId'])\n const jobId = str(body['jobId'])\n if (!ID_CHARS.test(hostId) || !ID_CHARS.test(jobId)) {\n return Response.json({ error: 'Name the site and the audit to apply' }, { status: 400 })\n }\n const { firestore, orgId, uid, staff, org, decoded } = gate\n\n const hostSnapshot = await firestore.collection('hosts').doc(hostId).get()\n const host = hostSnapshot.exists ? (hostSnapshot.data() as Record<string, unknown>) : null\n if (!host || host['orgId'] !== orgId) {\n return Response.json({ error: 'Unknown site' }, { status: 404 })\n }\n if (!staff && !holdsSiteKey(host, uid, 'site.edit')) {\n return Response.json({ error: siteKeyRefusal('site.edit') }, { status: 403 })\n }\n const locked = await lockdownRefusal({\n request,\n staff,\n uid,\n org: org as Record<string, unknown>,\n host: host as never,\n })\n if (locked) return locked\n\n const job = await getAiJob(firestore, orgId, jobId)\n if (!job || job.kind !== 'seo' || job.hostId !== hostId || aiSeoJobTarget(job.inputs) !== 'site') {\n return Response.json({ error: 'Unknown audit' }, { status: 404 })\n }\n if (job.status !== 'done') {\n return Response.json({ error: 'The audit is still running — apply it once it has finished' }, { status: 409 })\n }\n const view = aiSeoAuditView(job.outputs ?? [])\n if (!view) {\n return Response.json({ error: 'This audit has nothing to apply' }, { status: 409 })\n }\n\n const result = await applyAiSeoAudit(firestore, {\n orgId,\n hostId,\n job,\n view,\n uid,\n versioning: checkEntitlement(org, 'versioning'),\n })\n const opened = result.versions.filter((entry) => entry.fixes > 0)\n await writeAiJobAudit(firestore, {\n action: 'ai.job.apply',\n actorUid: uid,\n actorEmail: decoded.email ?? null,\n orgId,\n jobId,\n after: {\n hostId,\n versions: Object.fromEntries(opened.map((entry) => [entry.screenId, entry.versionId])),\n staged: result.staged,\n },\n })\n if (opened.length || result.staged.length) {\n await logAiSeoApplied(orgId, { uid, email: decoded.email ?? null }, {\n jobId,\n hostId,\n hostName: str(host['displayName']) || null,\n versions: opened.length,\n staged: result.staged.length,\n }).catch((error) => console.error('ai seo apply activity failed', { orgId, jobId, error }))\n }\n return Response.json(\n {\n job: aiJobSummary(result.job),\n versions: result.versions,\n staged: result.staged,\n skipped: result.skipped,\n },\n { status: 200, headers: { 'Cache-Control': 'no-store' } },\n )\n}\n\nexport const dynamic = 'force-dynamic'\n"],"names":["holdsSiteKey","siteKeyRefusal","checkEntitlement","createResourceUid","encodeStoredNodes","pageContentRootId","decodeStoredNodes","lockdownRefusal","logAiSeoApplied","aiJobSummary","getAiJob","recordAiJobApplied","writeAiJobAudit","aiSeoAuditView","aiSeoJobTarget","applyAiSeoContentFixes","aiJobsGate","ID_CHARS","AI_SEO_APPLY_VERSIONING_COPY","str","value","trim","applyAiSeoAudit","firestore","input","now","Date","hostRef","collection","doc","hostId","opened","job","applied","versions","staged","Set","names","Map","view","report","pages","map","page","screenId","name","skipped","fix","Object","values","fixes","get","keys","length","add","content","screenRef","earlier","exists","push","versionId","versioning","reason","screenSnapshot","publishedId","source","sourceData","data","nodes","rootId","undefined","result","packed","create","Buffer","from","displayName","createdAt","updatedAt","createdBy","uid","at","by","orgId","$id","POST","request","body","decoded","json","gate","String","Response","jobId","test","error","status","staff","org","hostSnapshot","host","locked","kind","inputs","outputs","filter","entry","action","actorUid","actorEmail","email","after","fromEntries","hostName","catch","console","headers","dynamic"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,mEAAmE;AACnE,2EAA2E;AAC3E,kCAAkC;AAElC,SAASA,Y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,GAAEtB,kBAAAA,QAAQsB,KAAK,YAAbtB,kBAAiB;QAAK,GAAG;YAClEK;YACA/D;YACAmF,UAAU9F,IAAIiF,IAAI,CAAC,cAAc,KAAK;YACtClE,UAAUH,OAAOsB,MAAM;YACvBlB,QAAQoC,OAAOpC,MAAM,CAACkB,MAAM;QAC9B,GAAG6D,KAAK,CAAC,CAACnB,QAAUoB,QAAQpB,KAAK,CAAC,gCAAgC;gBAAEZ;gBAAOU;gBAAOE;YAAM;IAC1F;IACA,OAAOH,SAASH,IAAI,CAClB;QACEzD,KAAKvB,aAAa8D,OAAOvC,GAAG;QAC5BE,UAAUqC,OAAOrC,QAAQ;QACzBC,QAAQoC,OAAOpC,MAAM;QACrBW,SAASyB,OAAOzB,OAAO;IACzB,GACA;QAAEkD,QAAQ;QAAKoB,SAAS;YAAE,iBAAiB;QAAW;IAAE;AAE5D;AAEA,OAAO,MAAMC,UAAU,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-seo-apply.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\n// lockdown-423: via libs/plugins/ai/src/lib/server/ai-jobs-gate.ts\n// The gate carries the org verdict; the handler adds the site's own below,\n// with the host document in hand.\n\nimport { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport {\n checkEntitlement,\n createResourceUid,\n encodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { contentEditStamp, withoutVersionPublishStamp } from '@aglyn/aglyn/app-utils/content-write-stamp'\nimport { pageContentRootId } from '@aglyn/aglyn/app-utils/page-markdown'\nimport { decodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { lockdownRefusal } from '@aglyn/tenant-data-admin/server/lockdown'\nimport { logAiSeoApplied } from '../activity/ai-activity'\nimport {\n aiJobSummary,\n getAiJob,\n recordAiJobApplied,\n writeAiJobAudit,\n} from '../jobs/ai-jobs'\nimport type { AiJob, AiJobApplied } from '../model/ai-jobs.types'\nimport { aiSeoAuditView, aiSeoJobTarget, type AiSeoAuditView } from '../model/ai-seo'\nimport { applyAiSeoContentFixes } from '../runtime/seo-content-fixes'\nimport { aiJobsGate } from './ai-jobs-gate'\n\n/**\n * Apply a site audit (AGL-2910): `POST /api/ai/seo/apply { orgId, hostId, jobId }`.\n *\n * \"Apply all\" does two things and neither changes what the published site\n * serves.\n *\n * - **Content fixes open a NEW version per page.** The page's published\n * version is copied, the fixes are applied to the copy — an image\n * description, the page's one main heading — and the copy is stored as a\n * new unpublished version. The published version and the screen's\n * `versionId` are never touched: a person opens the draft, looks, and\n * publishes it through the door that already exists.\n * - **Listing values are STAGED, not written.** A page's search title and\n * description are served straight from the screen document, so writing\n * them would publish them. The apply records which pages have values\n * waiting; the page's SEO card offers them, and its Save SEO is the write.\n *\n * The site-wide proposals — structured data and the agent guidance — are the\n * site SEO form's to save, and the card puts them there as unsaved edits; this\n * door never writes the host document.\n *\n * Idempotent per job: a page this job already opened a version for keeps\n * that version, so a second press opens nothing new.\n *\n * ## The rungs\n *\n * The jobs read gate (membership, the release flag, `aiGenerative`, the org\n * lockdown), then the site: it must be the job's and the org's, the caller\n * must hold a role that writes the site's content — the role creating a\n * version asks for — and the site's own lockdown verdict must admit a write.\n * Nothing here spends a token, so there is no reservation.\n */\n\nconst ID_CHARS = /^[A-Za-z0-9_-]{1,100}$/\n\n/** The version history sentence the versions route gives, for a plan without it. */\nexport const AI_SEO_APPLY_VERSIONING_COPY =\n 'Version history requires a Pro plan — see Billing to upgrade'\n\nexport interface AiSeoApplyInput {\n orgId: string\n hostId: string\n job: AiJob\n view: AiSeoAuditView\n uid: string\n /** Whether the org's plan keeps more than one version of a page. */\n versioning: boolean\n now?: Date\n}\n\nexport interface AiSeoApplyResult {\n job: AiJob\n /** The version each page's content fixes went into; `fixes` is 0 for one opened by an earlier apply. */\n versions: Array<{ screenId: string; versionId: string; name: string; fixes: number }>\n /** Pages whose listing values wait in their SEO card. */\n staged: string[]\n skipped: Array<{ screenId: string; reason: string }>\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/**\n * Open the versions and record the apply. Exported for the spec, which drives\n * it against a Firestore double and proves what it leaves alone.\n */\nexport async function applyAiSeoAudit(\n firestore: FirebaseFirestore.Firestore,\n input: AiSeoApplyInput,\n): Promise<AiSeoApplyResult> {\n const now = input.now ?? new Date()\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n const opened = { ...(input.job.applied?.versions ?? {}) }\n const staged = new Set(input.job.applied?.staged ?? [])\n const names = new Map(input.view.report.pages.map((page) => [page.screenId, page.name]))\n const versions: AiSeoApplyResult['versions'] = []\n const skipped: AiSeoApplyResult['skipped'] = []\n\n for (const fix of Object.values(input.view.fixes)) {\n const screenId = fix.screenId\n const name = names.get(screenId) ?? screenId\n if (Object.keys(fix.values).length) staged.add(screenId)\n if (!fix.content.length) continue\n const screenRef = hostRef.collection('screens').doc(screenId)\n\n const earlier = opened[screenId]\n if (earlier && (await screenRef.collection('versions').doc(earlier).get()).exists) {\n versions.push({ screenId, versionId: earlier, name, fixes: 0 })\n continue\n }\n if (!input.versioning) {\n skipped.push({ screenId, reason: AI_SEO_APPLY_VERSIONING_COPY })\n continue\n }\n const screenSnapshot = await screenRef.get()\n if (!screenSnapshot.exists || screenSnapshot.get('deletedAt')) {\n skipped.push({ screenId, reason: 'The page no longer exists.' })\n continue\n }\n const publishedId = str(screenSnapshot.get('versionId'))\n const source = publishedId ? await screenRef.collection('versions').doc(publishedId).get() : null\n const sourceData = source?.exists ? (source.data() as Record<string, unknown>) : null\n const nodes = sourceData ? decodeStoredNodes<Record<string, unknown>>(sourceData['nodes']) : null\n if (!sourceData || !nodes) {\n skipped.push({ screenId, reason: 'The page has no published version to start from.' })\n continue\n }\n const rootId = typeof sourceData['rootId'] === 'string' ? sourceData['rootId'] : undefined\n const result = applyAiSeoContentFixes(\n nodes,\n fix.content,\n pageContentRootId(nodes as never, rootId),\n )\n if (!result.applied.length) {\n skipped.push({ screenId, reason: result.skipped[0]?.reason ?? 'Nothing on the page needed changing.' })\n continue\n }\n const versionId = createResourceUid()\n // Compressed at rest, as every write of a version's nodes is.\n const packed = encodeStoredNodes(result.nodes)\n await screenRef\n .collection('versions')\n .doc(versionId)\n .create({\n // A new version beside the live one: not published by anyone yet.\n ...withoutVersionPublishStamp(sourceData),\n nodes: packed ? Buffer.from(packed) : result.nodes,\n displayName: 'SEO fixes',\n createdAt: now,\n createdBy: input.uid,\n ...contentEditStamp({ uid: input.uid, via: `ai-job:${input.job.$id}` }, now),\n })\n opened[screenId] = versionId\n versions.push({ screenId, versionId, name, fixes: result.applied.length })\n }\n\n const applied: AiJobApplied = {\n // The Admin SDK stores a `Date` as the timestamp the type describes.\n at: now as unknown as AiJobApplied['at'],\n by: input.uid,\n versions: opened,\n staged: [...staged],\n }\n const job = await recordAiJobApplied(firestore, input.orgId, input.job.$id, applied, now)\n return { job, versions, staged: [...staged], skipped }\n}\n\nexport async function POST(request: Request): Promise<Response> {\n let body: Record<string, unknown>\n try {\n body = ((await request.json()) ?? {}) as Record<string, unknown>\n } catch {\n body = {}\n }\n const gate = await aiJobsGate(request, String(body['orgId'] ?? ''))\n if (gate instanceof Response) return gate\n const hostId = str(body['hostId'])\n const jobId = str(body['jobId'])\n if (!ID_CHARS.test(hostId) || !ID_CHARS.test(jobId)) {\n return Response.json({ error: 'Name the site and the audit to apply' }, { status: 400 })\n }\n const { firestore, orgId, uid, staff, org, decoded } = gate\n\n const hostSnapshot = await firestore.collection('hosts').doc(hostId).get()\n const host = hostSnapshot.exists ? (hostSnapshot.data() as Record<string, unknown>) : null\n if (!host || host['orgId'] !== orgId) {\n return Response.json({ error: 'Unknown site' }, { status: 404 })\n }\n if (!staff && !holdsSiteKey(host, uid, 'site.edit')) {\n return Response.json({ error: siteKeyRefusal('site.edit') }, { status: 403 })\n }\n const locked = await lockdownRefusal({\n request,\n staff,\n uid,\n org: org as Record<string, unknown>,\n host: host as never,\n })\n if (locked) return locked\n\n const job = await getAiJob(firestore, orgId, jobId)\n if (!job || job.kind !== 'seo' || job.hostId !== hostId || aiSeoJobTarget(job.inputs) !== 'site') {\n return Response.json({ error: 'Unknown audit' }, { status: 404 })\n }\n if (job.status !== 'done') {\n return Response.json({ error: 'The audit is still running — apply it once it has finished' }, { status: 409 })\n }\n const view = aiSeoAuditView(job.outputs ?? [])\n if (!view) {\n return Response.json({ error: 'This audit has nothing to apply' }, { status: 409 })\n }\n\n const result = await applyAiSeoAudit(firestore, {\n orgId,\n hostId,\n job,\n view,\n uid,\n versioning: checkEntitlement(org, 'versioning'),\n })\n const opened = result.versions.filter((entry) => entry.fixes > 0)\n await writeAiJobAudit(firestore, {\n action: 'ai.job.apply',\n actorUid: uid,\n actorEmail: decoded.email ?? null,\n orgId,\n jobId,\n after: {\n hostId,\n versions: Object.fromEntries(opened.map((entry) => [entry.screenId, entry.versionId])),\n staged: result.staged,\n },\n })\n if (opened.length || result.staged.length) {\n await logAiSeoApplied(orgId, { uid, email: decoded.email ?? null }, {\n jobId,\n hostId,\n hostName: str(host['displayName']) || null,\n versions: opened.length,\n staged: result.staged.length,\n }).catch((error) => console.error('ai seo apply activity failed', { orgId, jobId, error }))\n }\n return Response.json(\n {\n job: aiJobSummary(result.job),\n versions: result.versions,\n staged: result.staged,\n skipped: result.skipped,\n },\n { status: 200, headers: { 'Cache-Control': 'no-store' } },\n )\n}\n\nexport const dynamic = 'force-dynamic'\n"],"names":["holdsSiteKey","siteKeyRefusal","checkEntitlement","createResourceUid","encodeStoredNodes","contentEditStamp","withoutVersionPublishStamp","pageContentRootId","decodeStoredNodes","lockdownRefusal","logAiSeoApplied","aiJobSummary","getAiJob","recordAiJobApplied","writeAiJobAudit","aiSeoAuditView","aiSeoJobTarget","applyAiSeoContentFixes","aiJobsGate","ID_CHARS","AI_SEO_APPLY_VERSIONING_COPY","str","value","trim","applyAiSeoAudit","firestore","input","now","Date","hostRef","collection","doc","hostId","opened","job","applied","versions","staged","Set","names","Map","view","report","pages","map","page","screenId","name","skipped","fix","Object","values","fixes","get","keys","length","add","content","screenRef","earlier","exists","push","versionId","versioning","reason","screenSnapshot","publishedId","source","sourceData","data","nodes","rootId","undefined","result","packed","create","Buffer","from","displayName","createdAt","createdBy","uid","via","$id","at","by","orgId","POST","request","body","decoded","json","gate","String","Response","jobId","test","error","status","staff","org","hostSnapshot","host","locked","kind","inputs","outputs","filter","entry","action","actorUid","actorEmail","email","after","fromEntries","hostName","catch","console","headers","dynamic"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,mEAAmE;AACnE,2EAA2E;AAC3E,kCAAkC;AAElC,SAASA,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AACtF,SACEC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,sBAAqB;AAC5B,SAASC,gBAAgB,EAAEC,0BAA0B,QAAQ,6CAA4C;AACzG,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,eAAe,QAAQ,6BAAyB;AACzD,SACEC,YAAY,EACZC,QAAQ,EACRC,kBAAkB,EAClBC,eAAe,QACV,qBAAiB;AAExB,SAASC,cAAc,EAAEC,cAAc,QAA6B,qBAAiB;AACrF,SAASC,sBAAsB,QAAQ,kCAA8B;AACrE,SAASC,UAAU,QAAQ,oBAAgB;AAE3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+BC,GAED,MAAMC,WAAW;AAEjB,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