@aglyn/plugins-ai 1.26.6 → 1.28.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/components/ai-credits-prompt.component.js +4 -1
- package/src/lib/components/ai-credits-prompt.component.js.map +1 -1
- package/src/lib/components/ai-site-import-job.component.js +5 -2
- package/src/lib/components/ai-site-import-job.component.js.map +1 -1
- package/src/lib/components/ai-site-start-card.component.js +6 -3
- package/src/lib/components/ai-site-start-card.component.js.map +1 -1
- package/src/lib/components/assist-build-card.component.js +4 -1
- package/src/lib/components/assist-build-card.component.js.map +1 -1
- package/src/lib/components/assist-edit-canvas.d.ts +12 -0
- package/src/lib/components/assist-edit-canvas.js +38 -7
- package/src/lib/components/assist-edit-canvas.js.map +1 -1
- package/src/lib/components/assist-jobs-drawer.component.js +4 -1
- package/src/lib/components/assist-jobs-drawer.component.js.map +1 -1
- package/src/lib/components/assist-panel.component.js +5 -2
- package/src/lib/components/assist-panel.component.js.map +1 -1
- package/src/lib/declarations.server.js +17 -0
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/jobs/ai-job-drafts.d.ts +5 -11
- package/src/lib/jobs/ai-job-drafts.js +8 -25
- package/src/lib/jobs/ai-job-drafts.js.map +1 -1
- package/src/lib/jobs/ai-job-edit-step.d.ts +95 -5
- package/src/lib/jobs/ai-job-edit-step.js +88 -17
- package/src/lib/jobs/ai-job-edit-step.js.map +1 -1
- package/src/lib/jobs/ai-job-settings-step.d.ts +1 -1
- package/src/lib/jobs/ai-job-settings-step.js +14 -23
- package/src/lib/jobs/ai-job-settings-step.js.map +1 -1
- package/src/lib/model/ai-edit-job.d.ts +27 -0
- package/src/lib/model/ai-edit-job.js +45 -23
- package/src/lib/model/ai-edit-job.js.map +1 -1
- package/src/lib/model/assist-edit.d.ts +2 -0
- package/src/lib/model/assist-edit.js.map +1 -1
- package/src/lib/runtime/ai-node-tree.d.ts +25 -1
- package/src/lib/runtime/ai-node-tree.js +39 -14
- package/src/lib/runtime/ai-node-tree.js.map +1 -1
- package/src/lib/server/ai-page-content.d.ts +83 -0
- package/src/lib/server/ai-page-content.js +765 -0
- package/src/lib/server/ai-page-content.js.map +1 -0
- package/src/lib/server/ai-usage.js +7 -1
- package/src/lib/server/ai-usage.js.map +1 -1
- package/src/lib/server/assist-edit.d.ts +136 -1
- package/src/lib/server/assist-edit.js +124 -47
- package/src/lib/server/assist-edit.js.map +1 -1
- package/src/lib/usage/ai-usage-wire.d.ts +15 -0
- package/src/lib/usage/ai-usage-wire.js +21 -0
- package/src/lib/usage/ai-usage-wire.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-settings-step.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 { supportedTimeZones } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { holdsSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { orgPermissionLabel } from '@aglyn/aglyn/app-utils/org-permissions'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { inheritedMediaAlt } from '@aglyn/aglyn/app-utils/media-metadata'\nimport { mediaNodeSrc } from '@aglyn/aglyn/app-utils/media-ref'\nimport { visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { SCREEN_ROOT_PATH } from '@aglyn/aglyn/app-utils/screen-route'\nimport { siteLanguageCode } from '@aglyn/aglyn/app-utils/seo-locale'\nimport { isSeoTitleVariable } from '@aglyn/aglyn/app-utils/seo-title-variables'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport type { PluginAiCapabilityArgsSchema } from '@aglyn/aglyn/plugin-manager/plugin-ai-capabilities'\nimport { changesProjectedHostFields, syncHostProjectionForMembers } from '@aglyn/tenant-data-admin/server/host-memberships'\nimport { getLockdownVerdict } from '@aglyn/tenant-data-admin/server/lockdown'\nimport { resolveOrgIdForHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { FieldValue, type Firestore } from 'firebase-admin/firestore'\nimport type { AiJobOutput } from '../model/ai-jobs.types'\nimport { registerAiJobAdmission, type AiJobAdmission, type AiJobAdmissionRefusal } from './ai-job-admission'\nimport { aiJobEditModel } from './ai-job-edit-step'\nimport { aiLimitReview, aiUnspentOutcome } from './ai-job-generation'\nimport type { AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The `settings` step (AGL-3748): a change to what a member can change in the\n * site's settings — its name, its search defaults, its favicon, logo and\n * social image from the media library, its language, its time zone, its\n * contact details and its consent banner's mode — as a first-class build\n * operation, so \"rename my site to Juniper Clay Studio\", \"make the site\n * Spanish\" or \"set the SEO description\" is one item on Assist's plan card.\n *\n * NO MODEL. The planner already wrote the values as the item's arguments;\n * this checks each against the rule the console's own control holds it to\n * and writes it, so it costs no credits.\n *\n * ── Only the console's own fields ────────────────────────────────────────\n *\n * Every field written is one a settings card or form writes, under the same\n * name and to the same limit: `displayName` (Admin → General, 30), `seo.title`\n * (60), `seo.description` (155), `seo.separator` (3), `seo.titlePattern`\n * (120, its own variables only), `seo.entity.name`, `seo.entity.description`\n * (300), `seo.entity.telephone`, `seo.entity.email` with its\n * `business.supportEmail` copy, and the address as `seo.entity.address`'s\n * street with its `business.address` copy (Setup → Business profile's\n * Business details card, AGL-4136), `locales`/`defaultLocale`\n * (the Languages card), `timeZone` (one of the zones the console offers),\n * `consent.mode` (the consent banner card), and `seo.favicon`, `logoUrl` and\n * `seo.image` (with its size and alt) written as the media pickers write\n * them, through `mediaNodeSrc`.\n *\n * NEVER: the address (subdomain, domains), plugins, members and roles,\n * billing, lockdown, deletion, search engine indexing, analytics and\n * advertising ids, verification tokens, or turning the consent banner off.\n * Those are not arguments, so the planner cannot ask for them.\n *\n * ── Live on confirm ──────────────────────────────────────────────────────\n *\n * A setting has no draft: the console saves it straight to the host\n * document, and the tenant renders it from there. So does this, once the\n * person confirms the plan (Zach, 2026-10-12: live on confirm). The write\n * drops the site's cached pages as the console's door does\n * (`host-document-writes.ts`), with a site-wide publish outbox entry in the\n * same transaction for the drain to fire if the drop does not land.\n *\n * ── Who may ──────────────────────────────────────────────────────────────\n *\n * The Firestore rules' own for these keys (`canWriteHostContent` and\n * `hostWritesFrozen`): a member with a write role on the site (admin, editor\n * or author), while no lockdown freezes the site, its org or the platform.\n * Asked at the door, again before the write, and the role once more inside\n * the transaction that writes.\n *\n * ── Idempotent ───────────────────────────────────────────────────────────\n *\n * The transaction compares each value with what is stored and writes only\n * what differs, so a pass asked again writes nothing and announces nothing.\n */\n\nexport const AI_SETTINGS_KIND = 'settings' as const\n\n/**\n * ASSUMED: the least time the step needs — the site, the org, up to three\n * media lookups in two libraries, and the one transaction that writes. No\n * model, so it fits an inline door.\n */\nexport const AI_JOB_SETTINGS_STEP_MINIMUM_MS = 5_000\n\nexport const AI_SETTINGS_NO_SITE_COPY = 'Open the site whose settings should change.'\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const AI_SETTINGS_ROLE_COPY = `Changing the site’s settings needs the \"${orgPermissionLabel('site.edit')}\" permission on this site — ask an organization admin.`\nexport const AI_SETTINGS_LOCKED_COPY = 'This site is not accepting changes right now.'\nexport const AI_SETTINGS_NOTHING_COPY = 'The request named no site setting this could change.'\n\n/** Where a person finds what the op changed, as the build's notes name it. */\nexport const AI_SETTINGS_WHERE = 'the site’s Settings'\n\n/** The output's fixed id: one site's settings, whatever changed. */\nexport const AI_SETTINGS_OUTPUT_ID = 'site'\n\n/** The console's own limits, each from the control that edits the field. */\nexport const AI_SETTINGS_LIMITS = {\n /** Admin → General, Display name. */\n name: 30,\n /** Setup → SEO, Title. */\n seoTitle: 60,\n /** Setup → SEO, Description. */\n seoDescription: 155,\n /** Setup → SEO, Separator. */\n separator: 3,\n /** Setup → SEO, Title pattern. */\n titlePattern: 120,\n /** Setup → SEO, the publisher's description. */\n businessDescription: 300,\n businessName: 100,\n telephone: 40,\n supportEmail: 254,\n address: 200,\n} as const\n\n/** The consent banner card's two modes; turning the banner off is not offered. */\nexport const AI_SETTINGS_CONSENT_MODES = ['geo', 'strict'] as const\n\n/** The media a setting may name, and the field each is written to. */\nexport const AI_SETTINGS_MEDIA_ARGS = ['favicon', 'logo', 'socialImage'] as const\nexport type AiSettingsMediaArg = (typeof AI_SETTINGS_MEDIA_ARGS)[number]\n\nconst MEDIA_ARG_NOUNS: Readonly<Record<AiSettingsMediaArg, string>> = {\n favicon: 'favicon',\n logo: 'logo',\n socialImage: 'social image',\n}\n\n/** The item's arguments, as the planner fills them in. Every one optional. */\nexport const AI_SETTINGS_ARGS_SCHEMA: PluginAiCapabilityArgsSchema = {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'The site’s name as the console lists it. Visitors see the search title, not this.',\n maxLength: AI_SETTINGS_LIMITS.name,\n },\n seoTitle: {\n type: 'string',\n description: 'The search title pages fall back to, usually the business’s name.',\n maxLength: AI_SETTINGS_LIMITS.seoTitle,\n },\n seoDescription: {\n type: 'string',\n description: 'The search description pages fall back to: one or two plain sentences.',\n maxLength: AI_SETTINGS_LIMITS.seoDescription,\n },\n separator: {\n type: 'string',\n description: 'The character between a page’s name and the site title, such as | or ·.',\n maxLength: AI_SETTINGS_LIMITS.separator,\n },\n titlePattern: {\n type: 'string',\n description: 'How an untitled page is titled, using only {{page.name}}, {{site.separator}} and {{site.name}}.',\n maxLength: AI_SETTINGS_LIMITS.titlePattern,\n },\n businessName: {\n type: 'string',\n description: 'The business’s name as search engines and AI assistants are told it.',\n maxLength: AI_SETTINGS_LIMITS.businessName,\n },\n businessDescription: {\n type: 'string',\n description: 'What the business is, in one sentence (its tagline), as search engines and AI assistants are told it.',\n maxLength: AI_SETTINGS_LIMITS.businessDescription,\n },\n telephone: {\n type: 'string',\n description: 'The business’s phone number, exactly as the person gave it.',\n maxLength: AI_SETTINGS_LIMITS.telephone,\n },\n supportEmail: {\n type: 'string',\n description: 'The contact email pages and emails show, exactly as the person gave it.',\n maxLength: AI_SETTINGS_LIMITS.supportEmail,\n },\n address: {\n type: 'string',\n description: 'The business’s address on one line, exactly as the person gave it.',\n maxLength: AI_SETTINGS_LIMITS.address,\n },\n language: {\n type: 'string',\n description: 'The language the site is in, as a code such as en, es, fr or pt-BR. It does not translate the pages.',\n maxLength: 10,\n },\n timeZone: {\n type: 'string',\n description: 'The site’s time zone as an IANA name, such as America/Chicago.',\n maxLength: 64,\n },\n consentMode: {\n type: 'string',\n description: 'The cookie banner’s mode: geo (asks only where the law requires) or strict (asks every visitor).',\n enum: AI_SETTINGS_CONSENT_MODES,\n },\n favicon: {\n type: 'string',\n description: 'An image already in the media library, by its id or exact file name, for the browser tab icon.',\n maxLength: 200,\n },\n logo: {\n type: 'string',\n description: 'An image already in the media library, by its id or exact file name, for the site’s logo.',\n maxLength: 200,\n },\n socialImage: {\n type: 'string',\n description: 'An image already in the media library, by its id or exact file name, for the card shown when a page is shared.',\n maxLength: 200,\n },\n },\n additionalProperties: false,\n}\n\n/** What an item asks, each value read and held to the console's rule. */\nexport interface AiSettingsRequest {\n name?: string\n seoTitle?: string\n seoDescription?: string\n separator?: string\n titlePattern?: string\n businessName?: string\n businessDescription?: string\n telephone?: string\n supportEmail?: string\n address?: string\n /** A language code the Languages card would accept. */\n language?: string\n timeZone?: string\n consentMode?: (typeof AI_SETTINGS_CONSENT_MODES)[number]\n favicon?: string\n logo?: string\n socialImage?: string\n}\n\nexport interface AiSettingsRead {\n request: AiSettingsRequest\n /** A sentence per value that could not be used, so the rest still are. */\n problems: string[]\n}\n\nconst text = (value: unknown): string => (typeof value === 'string' ? value.replace(/\\s+/g, ' ').trim() : '')\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\nconst TELEPHONE = /^[+()0-9][0-9 ()+.\\-/]{4,38}[0-9)]$/\nconst PATTERN_VARIABLE = /\\{\\{\\s*([^}]*?)\\s*\\}\\}/g\n\n/** Whether a title pattern names only the variables the renderer knows. */\nexport function aiSettingsTitlePatternOk(pattern: string): boolean {\n if (/[{}]/.test(pattern.replace(PATTERN_VARIABLE, ''))) return false\n return [...pattern.matchAll(PATTERN_VARIABLE)].every((match) => isSeoTitleVariable(match[1]))\n}\n\n/** The item's arguments read: what may be written, and a sentence for each that may not. */\nexport function aiSettingsRequestOf(inputs: Readonly<Record<string, unknown>> | null | undefined): AiSettingsRead {\n const request: AiSettingsRequest = {}\n const problems: string[] = []\n const bounded = (key: keyof typeof AI_SETTINGS_LIMITS, noun: string) => {\n const value = text(inputs?.[key])\n if (!value) return\n if (value.length > AI_SETTINGS_LIMITS[key]) {\n problems.push(`The ${noun} is longer than ${AI_SETTINGS_LIMITS[key]} characters.`)\n return\n }\n request[key] = value\n }\n bounded('name', 'site name')\n bounded('seoTitle', 'search title')\n bounded('seoDescription', 'search description')\n bounded('separator', 'title separator')\n bounded('businessName', 'business name')\n bounded('businessDescription', 'business description')\n bounded('address', 'address')\n bounded('titlePattern', 'title pattern')\n if (request.titlePattern && !aiSettingsTitlePatternOk(request.titlePattern)) {\n problems.push('The title pattern may use only {{page.name}}, {{site.separator}} and {{site.name}}.')\n delete request.titlePattern\n }\n bounded('telephone', 'phone number')\n if (request.telephone && !TELEPHONE.test(request.telephone)) {\n problems.push(`“${request.telephone}” is not a phone number.`)\n delete request.telephone\n }\n bounded('supportEmail', 'contact email')\n if (request.supportEmail && !EMAIL.test(request.supportEmail)) {\n problems.push(`“${request.supportEmail}” is not an email address.`)\n delete request.supportEmail\n }\n const language = text(inputs?.['language'])\n if (language) {\n const locale = siteLanguageCode(language)\n if (locale) request.language = locale\n else problems.push(`“${language}” is not a language code such as es or pt-BR.`)\n }\n const timeZone = text(inputs?.['timeZone'])\n if (timeZone) {\n if (supportedTimeZones().includes(timeZone)) request.timeZone = timeZone\n else problems.push(`“${timeZone}” is not a time zone the site settings offer.`)\n }\n const consentMode = text(inputs?.['consentMode'])\n if (consentMode) {\n if ((AI_SETTINGS_CONSENT_MODES as readonly string[]).includes(consentMode)) {\n request.consentMode = consentMode as AiSettingsRequest['consentMode']\n } else problems.push('The cookie banner’s mode is geo or strict.')\n }\n for (const key of AI_SETTINGS_MEDIA_ARGS) {\n const value = text(inputs?.[key])\n if (value) request[key] = value.slice(0, 200)\n }\n return { request, problems }\n}\n\n/** Whether a read request asks for anything at all. */\nexport function aiSettingsRequestEmpty(request: AiSettingsRequest): boolean {\n return Object.keys(request).length === 0\n}\n\n// ── Media ─────────────────────────────────────────────────────────────────\n\n/** A media library row, as a setting may name it. */\nexport interface AiSettingsMediaRow {\n id: string\n fileName: string\n contentType: string\n url: string | null\n cdnPath: string | null\n contentHash: string | null\n private: boolean\n deleted: boolean\n /** The org library's sites; `undefined` on the site's own library. */\n visibleTo?: readonly string[] | null\n width: number | null\n height: number | null\n alt: string\n}\n\n/** The image a setting names, as written to the host. */\nexport interface AiSettingsMedia {\n src: string\n width: number | null\n height: number | null\n alt: string\n fileName: string\n}\n\nfunction mediaRowOf(doc: FirebaseFirestore.QueryDocumentSnapshot | FirebaseFirestore.DocumentSnapshot, org: boolean): AiSettingsMediaRow {\n const data = (doc.data() ?? {}) as Record<string, unknown>\n const number = (value: unknown) => (typeof value === 'number' && value > 0 ? value : null)\n return {\n id: doc.id,\n fileName: String(data['fileName'] ?? ''),\n contentType: String(data['contentType'] ?? ''),\n url: typeof data['url'] === 'string' ? data['url'] : null,\n cdnPath: typeof data['cdnPath'] === 'string' ? data['cdnPath'] : null,\n contentHash: typeof data['contentHash'] === 'string' ? data['contentHash'] : null,\n private: data['private'] === true,\n deleted: data['deletedAt'] != null,\n ...(org ? { visibleTo: Array.isArray(data['visibleTo']) ? (data['visibleTo'] as string[]) : null } : {}),\n width: number(data['width']),\n height: number(data['height']),\n alt: typeof data['alt'] === 'string' ? data['alt'] : '',\n }\n}\n\n/**\n * The rows a media name could be, from the site's own library and then its\n * org's: the one whose id it is, else those whose file name it is.\n */\nexport async function readAiSettingsMediaRows(\n firestore: Firestore,\n input: { hostId: string; orgId: string; source: string },\n): Promise<AiSettingsMediaRow[]> {\n const libraries = [\n { ref: firestore.collection('hosts').doc(input.hostId).collection('media'), org: false },\n { ref: firestore.collection('orgs').doc(input.orgId).collection('media'), org: true },\n ]\n const rows: AiSettingsMediaRow[] = []\n for (const library of libraries) {\n if (/^[A-Za-z0-9_-]{1,128}$/.test(input.source)) {\n const byId = await library.ref.doc(input.source).get()\n if (byId.exists) rows.push(mediaRowOf(byId, library.org))\n }\n const byName = await library.ref.where('fileName', '==', input.source).limit(5).get()\n for (const doc of byName.docs) if (!rows.some((row) => row.id === doc.id)) rows.push(mediaRowOf(doc, library.org))\n }\n return rows\n}\n\n/**\n * The image a setting names, chosen from the rows read: a public image of\n * this site's library, or of its org's that this site may use, never deleted.\n * Its id wins over a file name; two images of one name are refused in words.\n */\nexport function aiSettingsMediaOf(\n arg: AiSettingsMediaArg,\n source: string,\n rows: readonly AiSettingsMediaRow[],\n hostId: string,\n): AiSettingsMedia | { error: string } {\n const noun = MEDIA_ARG_NOUNS[arg]\n const usable = rows.filter(\n (row) =>\n !row.deleted &&\n !row.private &&\n row.contentType.startsWith('image/') &&\n (row.visibleTo === undefined || visibleToHost(row.visibleTo, hostId)),\n )\n const byId = usable.find((row) => row.id === source)\n const named = usable.filter((row) => row.fileName === source)\n if (!byId && named.length > 1) return { error: `The media library has more than one image called “${source}”; name the one for the ${noun}.` }\n const row = byId ?? named[0]\n if (!row) return { error: `The media library has no image “${source}” this site can use for the ${noun}.` }\n const src = mediaNodeSrc({ url: row.url, cdnPath: row.cdnPath, contentHash: row.contentHash, private: row.private })\n if (!src) return { error: `The image “${source}” has no address the site can show.` }\n return { src, width: row.width, height: row.height, alt: row.alt, fileName: row.fileName || row.id }\n}\n\n// ── The write ─────────────────────────────────────────────────────────────\n\n/** One change to the host document, with the sentence that says it was made. */\ninterface AiSettingsChange {\n path: string\n value: unknown\n said: string\n /** The field is deleted rather than set; `value` is then ignored. */\n remove?: true\n}\n\n/**\n * The structured address parts a one-line address leaves empty (AGL-4136):\n * the line is the street, and a city or postal code still stored from an\n * older address would contradict it.\n */\nconst ADDRESS_PARTS_A_LINE_REPLACES = [\n 'addressLocality',\n 'addressRegion',\n 'postalCode',\n 'addressCountry',\n] as const\n\n/** Whether a stored value is there to delete. */\nconst isStored = (value: unknown): boolean =>\n value !== undefined && value !== null && !(typeof value === 'string' && value.trim() === '')\n\nconst getPath = (data: Record<string, unknown>, path: string): unknown =>\n path.split('.').reduce<unknown>((at, key) => (at && typeof at === 'object' ? (at as Record<string, unknown>)[key] : undefined), data)\n\nconst sameValue = (a: unknown, b: unknown): boolean => JSON.stringify(a ?? null) === JSON.stringify(b ?? null)\n\n/**\n * The language change, as the Languages card would save it: a site with no\n * languages, or one, now publishes in this one; a multilingual site that\n * lists it makes it the default. A multilingual site that does not list it\n * is refused, because adding a language is the Languages card's decision.\n */\nexport function aiSettingsLanguageChanges(\n host: { locales?: unknown; defaultLocale?: unknown },\n language: string,\n): AiSettingsChange[] | { error: string } {\n const locales = Array.isArray(host.locales) ? host.locales.filter((one): one is string => typeof one === 'string') : []\n const said = `The site’s language is now ${language}.`\n if (locales.length > 1) {\n if (!locales.includes(language)) {\n return { error: `This site publishes in ${locales.join(', ')}; add ${language} in Settings → Details → Languages first.` }\n }\n return [{ path: 'defaultLocale', value: language, said }]\n }\n return [\n { path: 'locales', value: [language], said },\n { path: 'defaultLocale', value: language, said },\n ]\n}\n\n/** Every change the request asks of this host, before comparing with what is stored. */\nexport function aiSettingsChanges(\n host: Record<string, unknown>,\n request: AiSettingsRequest,\n media: Partial<Record<AiSettingsMediaArg, AiSettingsMedia>>,\n): { changes: AiSettingsChange[]; problems: string[] } {\n const changes: AiSettingsChange[] = []\n const problems: string[] = []\n const set = (path: string, value: unknown, said: string) => changes.push({ path, value, said })\n if (request.name) set('displayName', request.name, `The site is now called “${request.name}”.`)\n if (request.seoTitle) set('seo.title', request.seoTitle, `The search title is now “${request.seoTitle}”.`)\n if (request.seoDescription) set('seo.description', request.seoDescription, 'The search description is set.')\n if (request.separator) set('seo.separator', request.separator, `The title separator is now “${request.separator}”.`)\n if (request.titlePattern) set('seo.titlePattern', request.titlePattern, `Untitled pages are now titled “${request.titlePattern}”.`)\n if (request.businessName) set('seo.entity.name', request.businessName, `The business name is now “${request.businessName}”.`)\n if (request.businessDescription) set('seo.entity.description', request.businessDescription, 'The business description is set.')\n if (request.telephone) set('seo.entity.telephone', request.telephone, `The phone number is now ${request.telephone}.`)\n if (request.supportEmail) {\n // The site's one email (AGL-4136): the canonical `seo.entity.email`, and\n // the `business.supportEmail` copy Setup → Business profile keeps in step for the\n // native apps, so every reader shows the new address at once.\n const said = `The contact email is now ${request.supportEmail}.`\n set('seo.entity.email', request.supportEmail, said)\n set('business.supportEmail', request.supportEmail, said)\n }\n if (request.address) {\n // The address arrives as ONE line, which cannot be split into the parts\n // Setup → Business profile stores (AGL-4136). So the whole line is the\n // street, the other parts are deleted where the site has them, so an\n // older city or postal code cannot contradict it, and the one-block\n // `business.address` copy says the same. Every reader then shows the\n // new address, whichever path it reads.\n const said = 'The address is set.'\n set('seo.entity.address.streetAddress', request.address, said)\n for (const part of ADDRESS_PARTS_A_LINE_REPLACES) {\n const path = `seo.entity.address.${part}`\n if (isStored(getPath(host, path))) changes.push({ path, value: null, said, remove: true })\n }\n set('business.address', request.address, said)\n }\n if (request.timeZone) set('timeZone', request.timeZone, `The site’s time zone is now ${request.timeZone}.`)\n if (request.consentMode) {\n set('consent.mode', request.consentMode, request.consentMode === 'strict' ? 'The cookie banner now asks every visitor.' : 'The cookie banner now asks where the law requires.')\n }\n if (request.language) {\n const language = aiSettingsLanguageChanges(host, request.language)\n if ('error' in language) problems.push(language.error)\n else changes.push(...language)\n }\n if (media.favicon) set('seo.favicon', media.favicon.src, `The favicon is now “${media.favicon.fileName}”.`)\n if (media.logo) set('logoUrl', media.logo.src, `The logo is now “${media.logo.fileName}”.`)\n if (media.socialImage) {\n const image = media.socialImage\n const said = `The social image is now “${image.fileName}”.`\n set('seo.image', image.src, said)\n // Its size and alt, as the Social image card copies them at pick time.\n set('seo.imageWidth', image.width ?? 0, said)\n set('seo.imageHeight', image.height ?? 0, said)\n const savedAlt = getPath(host, 'seo.imageAlt')\n set('seo.imageAlt', inheritedMediaAlt({ placementAlt: savedAlt, assetAlt: image.alt }) ?? (typeof savedAlt === 'string' ? savedAlt : ''), said)\n }\n return { changes, problems }\n}\n\nexport type AiSettingsWrite =\n | { ok: true; done: string[]; notDone: string[]; changed: string[]; outboxId: string | null }\n | { ok: false; error: string }\n\n/**\n * The settings written, in one transaction that reads the host as it is\n * stored NOW: the member still holds a write role, and only the values that\n * differ from what is stored are written, with a site-wide publish outbox\n * entry beside them so the live site's cached pages are dropped.\n */\nexport async function writeAiSiteSettings(\n firestore: Firestore,\n input: {\n hostId: string\n uid: string\n request: AiSettingsRequest\n media: Partial<Record<AiSettingsMediaArg, AiSettingsMedia>>\n now: Date\n },\n): Promise<AiSettingsWrite> {\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n return firestore.runTransaction(async (tx): Promise<AiSettingsWrite> => {\n const host = await tx.get(hostRef)\n if (!host.exists) return { ok: false, error: 'Unknown site' }\n if (!holdsSiteKey(host, input.uid, 'site.edit')) return { ok: false, error: AI_SETTINGS_ROLE_COPY }\n const data = (host.data() ?? {}) as Record<string, unknown>\n const { changes, problems } = aiSettingsChanges(data, input.request, input.media)\n const changed = changes.filter((change) =>\n change.remove ? isStored(getPath(data, change.path)) : !sameValue(getPath(data, change.path), change.value),\n )\n const done = [...new Set(changes.map((change) => change.said))]\n if (!changed.length) return { ok: true, done, notDone: problems, changed: [], outboxId: null }\n const updates: Record<string, unknown> = { updatedAt: input.now }\n for (const change of changed) updates[change.path] = change.remove ? FieldValue.delete() : change.value\n tx.update(hostRef, updates)\n // The announce, written down in the save's own transaction: a setting\n // has no address, so it asks for the whole site, as the console's does.\n const outboxRef = firestore.collection('publishOutbox').doc(createResourceUid())\n tx.set(outboxRef, {\n hostId: input.hostId,\n paths: [SCREEN_ROOT_PATH],\n entireHost: true,\n createdAt: FieldValue.serverTimestamp(),\n attempts: 0,\n })\n return { ok: true, done, notDone: problems, changed: changed.map((change) => change.path), outboxId: outboxRef.id }\n })\n}\n\n// ── The step ──────────────────────────────────────────────────────────────\n\n/** Why this member may not change this site's settings now, or `null`. */\nexport async function aiSettingsAccessRefusal(\n input: { host: FirebaseFirestore.DocumentSnapshot; uid: string; org: object | null },\n deps: { lockdown?: typeof getLockdownVerdict } = {},\n): Promise<string | null> {\n if (!input.host.exists) return 'Unknown site'\n if (!holdsSiteKey(input.host, input.uid, 'site.edit')) return AI_SETTINGS_ROLE_COPY\n const locked = await (deps.lockdown ?? getLockdownVerdict)({\n staff: false,\n uid: input.uid,\n org: input.org as never,\n host: input.host.data() as never,\n intent: 'write',\n })\n return locked ? AI_SETTINGS_LOCKED_COPY : null\n}\n\n/** The output's note: what changed, that it is live, and what was not done. */\nexport function aiSettingsOutputNote(done: readonly string[], notDone: readonly string[], language: boolean): string {\n // The build's own wording for an item with no draft state (AGL-3745).\n const did = done.length ? `${done.join(' ')} Live now, in ${AI_SETTINGS_WHERE}.` : 'Nothing needed changing.'\n const translate = language ? ' The pages keep the words they have: changing the language does not translate them.' : ''\n const not = notDone.length ? ` Not done: ${notDone.join(' ')}` : ''\n return `${did}${translate}${not}`.slice(0, 1_000)\n}\n\nexport interface AiJobSettingsStepDeps {\n readMedia?: typeof readAiSettingsMediaRows\n write?: typeof writeAiSiteSettings\n lockdown?: typeof getLockdownVerdict\n dropCache?: typeof dropPluginSiteCache\n syncMemberships?: typeof syncHostProjectionForMembers\n}\n\n/** Each media argument resolved to its image, or a sentence for each that cannot be. */\nasync function mediaOf(\n firestore: Firestore,\n input: { hostId: string; orgId: string; request: AiSettingsRequest },\n readMedia: typeof readAiSettingsMediaRows,\n): Promise<{ media: Partial<Record<AiSettingsMediaArg, AiSettingsMedia>>; problems: string[] }> {\n const media: Partial<Record<AiSettingsMediaArg, AiSettingsMedia>> = {}\n const problems: string[] = []\n for (const arg of AI_SETTINGS_MEDIA_ARGS) {\n const source = input.request[arg]\n if (!source) continue\n const rows = await readMedia(firestore, { hostId: input.hostId, orgId: input.orgId, source })\n const found = aiSettingsMediaOf(arg, source, rows, input.hostId)\n if ('error' in found) problems.push(found.error)\n else media[arg] = found\n }\n return { media, problems }\n}\n\nexport function createAiJobSettingsStep(deps: AiJobSettingsStepDeps = {}): AiJobStepRunner {\n const readMedia = deps.readMedia ?? readAiSettingsMediaRows\n const write = deps.write ?? writeAiSiteSettings\n const dropCache = deps.dropCache ?? dropPluginSiteCache\n const syncMemberships = deps.syncMemberships ?? syncHostProjectionForMembers\n return async ({ job, now, firestore, org, modelFor }): Promise<AiJobStepOutcome> => {\n // No model is asked: the outcome records the edit step's at no cost.\n const model = modelFor?.('job.edit') ?? aiJobEditModel()\n const unspent = (failure: string): AiJobStepOutcome => ({ ...aiUnspentOutcome(model), failure })\n const hostId = job.hostId\n if (!hostId) return unspent(AI_SETTINGS_NO_SITE_COPY)\n const read = aiSettingsRequestOf(job.inputs)\n if (aiSettingsRequestEmpty(read.request)) return unspent([AI_SETTINGS_NOTHING_COPY, ...read.problems].join(' '))\n const orgData = (org ?? ((await firestore.collection('orgs').doc(job.orgId).get()).data() ?? null)) as Record<string, unknown> | null\n const host = await firestore.collection('hosts').doc(hostId).get()\n const refused = await aiSettingsAccessRefusal({ host, uid: job.createdBy, org: orgData }, { lockdown: deps.lockdown })\n if (refused) return aiUnspentOutcome(model, { review: aiLimitReview(refused) })\n const found = await mediaOf(firestore, { hostId, orgId: job.orgId, request: read.request }, readMedia)\n const written = await write(firestore, { hostId, uid: job.createdBy, request: read.request, media: found.media, now })\n if (written.ok === false) return unspent(written.error)\n const notDone = [...read.problems, ...found.problems, ...written.notDone]\n if (!written.done.length) return unspent([AI_SETTINGS_NOTHING_COPY, ...notDone].join(' '))\n if (written.outboxId) {\n // The live site's cached pages go now; the outbox entry stays for the\n // drain unless the drop certainly happened.\n const dropped = await dropCache({ hostIds: [hostId], reason: 'AI build changed site settings' }).catch(() => ({ complete: false }))\n if (dropped.complete) await firestore.collection('publishOutbox').doc(written.outboxId).delete().catch(() => undefined)\n }\n if (changesProjectedHostFields(written.changed)) {\n // Every site list reads the name and favicon members' rows carry, so a\n // new favicon owes the re-fan as much as a new name does (AGL-3972).\n await syncMemberships(job.orgId, hostId).catch((error: unknown) => {\n console.error('ai settings: membership projection not synced', { hostId, jobId: job.$id, error })\n })\n }\n const output: AiJobOutput = {\n resource: 'settings',\n id: AI_SETTINGS_OUTPUT_ID,\n hostId,\n hostSubdomain: (typeof host.get('subdomain') === 'string' && host.get('subdomain')) || null,\n label: 'Site settings',\n note: aiSettingsOutputNote(written.done, notDone, Boolean(read.request.language)),\n }\n return aiUnspentOutcome(model, { outputs: [output] })\n }\n}\n\nexport const runAiJobSettingsStep = createAiJobSettingsStep()\n\n// ── Admission ─────────────────────────────────────────────────────────────\n\nexport interface AiSettingsJobAdmissionDeps {\n ownerOf?: typeof resolveOrgIdForHost\n lockdown?: typeof getLockdownVerdict\n}\n\n/**\n * A settings change is admitted on a site of the job's own org, for a member\n * who may write its settings now, where the request names at least one\n * setting this can change. Refused in those words before anything is written.\n */\nexport function createAiSettingsJobAdmission(deps: AiSettingsJobAdmissionDeps = {}): AiJobAdmission {\n const ownerOf = deps.ownerOf ?? resolveOrgIdForHost\n return async (context): Promise<AiJobAdmissionRefusal | null> => {\n if (!context.hostId) return { status: 400, error: AI_SETTINGS_NO_SITE_COPY }\n const owner = await ownerOf(context.hostId)\n if (!owner || owner !== context.orgId) return { status: 404, error: 'Unknown site' }\n const host = await context.firestore.collection('hosts').doc(context.hostId).get()\n const refused = await aiSettingsAccessRefusal({ host, uid: context.uid ?? '', org: context.org }, { lockdown: deps.lockdown })\n if (refused) return { status: 403, error: refused }\n const read = aiSettingsRequestOf(context.inputs as Record<string, unknown>)\n return aiSettingsRequestEmpty(read.request) ? { status: 400, error: [AI_SETTINGS_NOTHING_COPY, ...read.problems].join(' ') } : null\n }\n}\n\nexport const aiSettingsJobAdmission = createAiSettingsJobAdmission()\n\n/** Registers the settings step and its door (AGL-3748). */\nexport function registerAiSettingsJob(): void {\n registerAiJobStep(AI_SETTINGS_KIND, runAiJobSettingsStep, { minimumMs: AI_JOB_SETTINGS_STEP_MINIMUM_MS })\n registerAiJobAdmission(AI_SETTINGS_KIND, aiSettingsJobAdmission)\n}\n\n"],"names":["supportedTimeZones","holdsSiteKey","orgPermissionLabel","createResourceUid","inheritedMediaAlt","mediaNodeSrc","visibleToHost","SCREEN_ROOT_PATH","siteLanguageCode","isSeoTitleVariable","dropPluginSiteCache","changesProjectedHostFields","syncHostProjectionForMembers","getLockdownVerdict","resolveOrgIdForHost","FieldValue","registerAiJobAdmission","aiJobEditModel","aiLimitReview","aiUnspentOutcome","registerAiJobStep","AI_SETTINGS_KIND","AI_JOB_SETTINGS_STEP_MINIMUM_MS","AI_SETTINGS_NO_SITE_COPY","AI_SETTINGS_ROLE_COPY","AI_SETTINGS_LOCKED_COPY","AI_SETTINGS_NOTHING_COPY","AI_SETTINGS_WHERE","AI_SETTINGS_OUTPUT_ID","AI_SETTINGS_LIMITS","name","seoTitle","seoDescription","separator","titlePattern","businessDescription","businessName","telephone","supportEmail","address","AI_SETTINGS_CONSENT_MODES","AI_SETTINGS_MEDIA_ARGS","MEDIA_ARG_NOUNS","favicon","logo","socialImage","AI_SETTINGS_ARGS_SCHEMA","type","properties","description","maxLength","language","timeZone","consentMode","enum","additionalProperties","text","value","replace","trim","EMAIL","TELEPHONE","PATTERN_VARIABLE","aiSettingsTitlePatternOk","pattern","test","matchAll","every","match","aiSettingsRequestOf","inputs","request","problems","bounded","key","noun","length","push","locale","includes","slice","aiSettingsRequestEmpty","Object","keys","mediaRowOf","doc","org","data","number","id","fileName","String","contentType","url","cdnPath","contentHash","private","deleted","visibleTo","Array","isArray","width","height","alt","readAiSettingsMediaRows","firestore","input","libraries","ref","collection","hostId","orgId","rows","library","source","byId","get","exists","byName","where","limit","docs","some","row","aiSettingsMediaOf","arg","usable","filter","startsWith","undefined","find","named","error","src","ADDRESS_PARTS_A_LINE_REPLACES","isStored","getPath","path","split","reduce","at","sameValue","a","b","JSON","stringify","aiSettingsLanguageChanges","host","locales","one","said","join","aiSettingsChanges","media","changes","set","part","remove","image","savedAlt","placementAlt","assetAlt","writeAiSiteSettings","hostRef","runTransaction","tx","ok","uid","changed","change","done","Set","map","notDone","outboxId","updates","updatedAt","now","delete","update","outboxRef","paths","entireHost","createdAt","serverTimestamp","attempts","aiSettingsAccessRefusal","deps","locked","lockdown","staff","intent","aiSettingsOutputNote","did","translate","not","mediaOf","readMedia","found","createAiJobSettingsStep","write","dropCache","syncMemberships","job","modelFor","model","unspent","failure","read","orgData","refused","createdBy","review","written","dropped","hostIds","reason","catch","complete","console","jobId","$id","output","resource","hostSubdomain","label","note","Boolean","outputs","runAiJobSettingsStep","createAiSettingsJobAdmission","ownerOf","context","status","owner","aiSettingsJobAdmission","registerAiSettingsJob","minimumMs"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,+CAA8C;AACjF,SAASC,YAAY,QAAQ,0CAAyC;AACtE,SAASC,kBAAkB,QAAQ,yCAAwC;AAC3E,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,iBAAiB,QAAQ,wCAAuC;AACzE,SAASC,YAAY,QAAQ,mCAAkC;AAC/D,SAASC,aAAa,QAAQ,sCAAqC;AACnE,SAASC,gBAA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AEpE,yDAAyD,GACzD,OAAO,SAASM;IACdxN,kBAAkBC,kBAAkBgN,sBAAsB;QAAEQ,WAAWvN;IAAgC;IACvGN,uBAAuBK,kBAAkBsN;AAC3C"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-settings-step.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 { supportedTimeZones } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { holdsSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { orgPermissionLabel } from '@aglyn/aglyn/app-utils/org-permissions'\nimport { inheritedMediaAlt } from '@aglyn/aglyn/app-utils/media-metadata'\nimport { mediaNodeSrc } from '@aglyn/aglyn/app-utils/media-ref'\nimport { visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { siteLanguageCode } from '@aglyn/aglyn/app-utils/seo-locale'\nimport { SEO_DESCRIPTION_MAX_LENGTH, SEO_TITLE_MAX_LENGTH } from '@aglyn/aglyn/app-utils/screen-seo-fields'\nimport { SITE_SEO_SEPARATOR_MAX_LENGTH, SITE_SEO_TITLE_PATTERN_MAX_LENGTH } from '@aglyn/aglyn/app-utils/seo-listing-fields'\nimport { isSeoTitleVariable } from '@aglyn/aglyn/app-utils/seo-title-variables'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport type { PluginAiCapabilityArgsSchema } from '@aglyn/aglyn/plugin-manager/plugin-ai-capabilities'\nimport { changesProjectedHostFields, syncHostProjectionForMembers } from '@aglyn/tenant-data-admin/server/host-memberships'\nimport { getLockdownVerdict } from '@aglyn/tenant-data-admin/server/lockdown'\nimport { resolveOrgIdForHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { stageSiteSettingsWrite } from '@aglyn/tenant-data-admin/server/site-settings-write'\nimport type { Firestore } from 'firebase-admin/firestore'\nimport type { AiJobOutput } from '../model/ai-jobs.types'\nimport { registerAiJobAdmission, type AiJobAdmission, type AiJobAdmissionRefusal } from './ai-job-admission'\nimport { aiJobEditModel } from './ai-job-edit-step'\nimport { aiLimitReview, aiUnspentOutcome } from './ai-job-generation'\nimport type { AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The `settings` step (AGL-3748): a change to what a member can change in the\n * site's settings — its name, its search defaults, its favicon, logo and\n * social image from the media library, its language, its time zone, its\n * contact details and its consent banner's mode — as a first-class build\n * operation, so \"rename my site to Juniper Clay Studio\", \"make the site\n * Spanish\" or \"set the SEO description\" is one item on Assist's plan card.\n *\n * NO MODEL. The planner already wrote the values as the item's arguments;\n * this checks each against the rule the console's own control holds it to\n * and writes it, so it costs no credits.\n *\n * ── Only the console's own fields ────────────────────────────────────────\n *\n * Every field written is one a settings card or form writes, under the same\n * name and to the same limit: `displayName` (Admin → General, 30), `seo.title`\n * (60), `seo.description` (155), `seo.separator` (3), `seo.titlePattern`\n * (120, its own variables only), `seo.entity.name`, `seo.entity.description`\n * (300), `seo.entity.telephone`, `seo.entity.email` with its\n * `business.supportEmail` copy, and the address as `seo.entity.address`'s\n * street with its `business.address` copy (Setup → Business profile's\n * Business details card, AGL-4136), `locales`/`defaultLocale`\n * (the Languages card), `timeZone` (one of the zones the console offers),\n * `consent.mode` (the consent banner card), and `seo.favicon`, `logoUrl` and\n * `seo.image` (with its size and alt) written as the media pickers write\n * them, through `mediaNodeSrc`.\n *\n * NEVER: the address (subdomain, domains), plugins, members and roles,\n * billing, lockdown, deletion, search engine indexing, analytics and\n * advertising ids, verification tokens, or turning the consent banner off.\n * Those are not arguments, so the planner cannot ask for them.\n *\n * ── Live on confirm ──────────────────────────────────────────────────────\n *\n * A setting has no draft: the console saves it straight to the host\n * document, and the tenant renders it from there. So does this, once the\n * person confirms the plan (Zach, 2026-10-12: live on confirm). The write\n * drops the site's cached pages as the console's door does\n * (`host-document-writes.ts`), with a site-wide publish outbox entry in the\n * same transaction for the drain to fire if the drop does not land.\n *\n * ── Who may ──────────────────────────────────────────────────────────────\n *\n * The Firestore rules' own for these keys (`canWriteHostContent` and\n * `hostWritesFrozen`): a member with a write role on the site (admin, editor\n * or author), while no lockdown freezes the site, its org or the platform.\n * Asked at the door, again before the write, and the role once more inside\n * the transaction that writes.\n *\n * ── Idempotent ───────────────────────────────────────────────────────────\n *\n * The transaction compares each value with what is stored and writes only\n * what differs, so a pass asked again writes nothing and announces nothing.\n */\n\nexport const AI_SETTINGS_KIND = 'settings' as const\n\n/**\n * ASSUMED: the least time the step needs — the site, the org, up to three\n * media lookups in two libraries, and the one transaction that writes. No\n * model, so it fits an inline door.\n */\nexport const AI_JOB_SETTINGS_STEP_MINIMUM_MS = 5_000\n\nexport const AI_SETTINGS_NO_SITE_COPY = 'Open the site whose settings should change.'\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const AI_SETTINGS_ROLE_COPY = `Changing the site’s settings needs the \"${orgPermissionLabel('site.edit')}\" permission on this site — ask an organization admin.`\nexport const AI_SETTINGS_LOCKED_COPY = 'This site is not accepting changes right now.'\nexport const AI_SETTINGS_NOTHING_COPY = 'The request named no site setting this could change.'\n\n/** Where a person finds what the op changed, as the build's notes name it. */\nexport const AI_SETTINGS_WHERE = 'the site’s Settings'\n\n/** The output's fixed id: one site's settings, whatever changed. */\nexport const AI_SETTINGS_OUTPUT_ID = 'site'\n\n/** The console's own limits, each from the control that edits the field. */\nexport const AI_SETTINGS_LIMITS = {\n /** Admin → General, Display name. */\n name: 30,\n /** Setup → SEO, Title. */\n seoTitle: SEO_TITLE_MAX_LENGTH,\n /** Setup → SEO, Description. */\n seoDescription: SEO_DESCRIPTION_MAX_LENGTH,\n /** Setup → SEO, Separator. */\n separator: SITE_SEO_SEPARATOR_MAX_LENGTH,\n /** Setup → SEO, Title pattern. */\n titlePattern: SITE_SEO_TITLE_PATTERN_MAX_LENGTH,\n /** Setup → SEO, the publisher's description. */\n businessDescription: 300,\n businessName: 100,\n telephone: 40,\n supportEmail: 254,\n address: 200,\n} as const\n\n/** The consent banner card's two modes; turning the banner off is not offered. */\nexport const AI_SETTINGS_CONSENT_MODES = ['geo', 'strict'] as const\n\n/** The media a setting may name, and the field each is written to. */\nexport const AI_SETTINGS_MEDIA_ARGS = ['favicon', 'logo', 'socialImage'] as const\nexport type AiSettingsMediaArg = (typeof AI_SETTINGS_MEDIA_ARGS)[number]\n\nconst MEDIA_ARG_NOUNS: Readonly<Record<AiSettingsMediaArg, string>> = {\n favicon: 'favicon',\n logo: 'logo',\n socialImage: 'social image',\n}\n\n/** The item's arguments, as the planner fills them in. Every one optional. */\nexport const AI_SETTINGS_ARGS_SCHEMA: PluginAiCapabilityArgsSchema = {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'The site’s name as the console lists it. Visitors see the search title, not this.',\n maxLength: AI_SETTINGS_LIMITS.name,\n },\n seoTitle: {\n type: 'string',\n description: 'The search title pages fall back to, usually the business’s name.',\n maxLength: AI_SETTINGS_LIMITS.seoTitle,\n },\n seoDescription: {\n type: 'string',\n description: 'The search description pages fall back to: one or two plain sentences.',\n maxLength: AI_SETTINGS_LIMITS.seoDescription,\n },\n separator: {\n type: 'string',\n description: 'The character between a page’s name and the site title, such as | or ·.',\n maxLength: AI_SETTINGS_LIMITS.separator,\n },\n titlePattern: {\n type: 'string',\n description: 'How an untitled page is titled, using only {{page.name}}, {{site.separator}} and {{site.name}}.',\n maxLength: AI_SETTINGS_LIMITS.titlePattern,\n },\n businessName: {\n type: 'string',\n description: 'The business’s name as search engines and AI assistants are told it.',\n maxLength: AI_SETTINGS_LIMITS.businessName,\n },\n businessDescription: {\n type: 'string',\n description: 'What the business is, in one sentence (its tagline), as search engines and AI assistants are told it.',\n maxLength: AI_SETTINGS_LIMITS.businessDescription,\n },\n telephone: {\n type: 'string',\n description: 'The business’s phone number, exactly as the person gave it.',\n maxLength: AI_SETTINGS_LIMITS.telephone,\n },\n supportEmail: {\n type: 'string',\n description: 'The contact email pages and emails show, exactly as the person gave it.',\n maxLength: AI_SETTINGS_LIMITS.supportEmail,\n },\n address: {\n type: 'string',\n description: 'The business’s address on one line, exactly as the person gave it.',\n maxLength: AI_SETTINGS_LIMITS.address,\n },\n language: {\n type: 'string',\n description: 'The language the site is in, as a code such as en, es, fr or pt-BR. It does not translate the pages.',\n maxLength: 10,\n },\n timeZone: {\n type: 'string',\n description: 'The site’s time zone as an IANA name, such as America/Chicago.',\n maxLength: 64,\n },\n consentMode: {\n type: 'string',\n description: 'The cookie banner’s mode: geo (asks only where the law requires) or strict (asks every visitor).',\n enum: AI_SETTINGS_CONSENT_MODES,\n },\n favicon: {\n type: 'string',\n description: 'An image already in the media library, by its id or exact file name, for the browser tab icon.',\n maxLength: 200,\n },\n logo: {\n type: 'string',\n description: 'An image already in the media library, by its id or exact file name, for the site’s logo.',\n maxLength: 200,\n },\n socialImage: {\n type: 'string',\n description: 'An image already in the media library, by its id or exact file name, for the card shown when a page is shared.',\n maxLength: 200,\n },\n },\n additionalProperties: false,\n}\n\n/** What an item asks, each value read and held to the console's rule. */\nexport interface AiSettingsRequest {\n name?: string\n seoTitle?: string\n seoDescription?: string\n separator?: string\n titlePattern?: string\n businessName?: string\n businessDescription?: string\n telephone?: string\n supportEmail?: string\n address?: string\n /** A language code the Languages card would accept. */\n language?: string\n timeZone?: string\n consentMode?: (typeof AI_SETTINGS_CONSENT_MODES)[number]\n favicon?: string\n logo?: string\n socialImage?: string\n}\n\nexport interface AiSettingsRead {\n request: AiSettingsRequest\n /** A sentence per value that could not be used, so the rest still are. */\n problems: string[]\n}\n\nconst text = (value: unknown): string => (typeof value === 'string' ? value.replace(/\\s+/g, ' ').trim() : '')\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\nconst TELEPHONE = /^[+()0-9][0-9 ()+.\\-/]{4,38}[0-9)]$/\nconst PATTERN_VARIABLE = /\\{\\{\\s*([^}]*?)\\s*\\}\\}/g\n\n/** Whether a title pattern names only the variables the renderer knows. */\nexport function aiSettingsTitlePatternOk(pattern: string): boolean {\n if (/[{}]/.test(pattern.replace(PATTERN_VARIABLE, ''))) return false\n return [...pattern.matchAll(PATTERN_VARIABLE)].every((match) => isSeoTitleVariable(match[1]))\n}\n\n/** The item's arguments read: what may be written, and a sentence for each that may not. */\nexport function aiSettingsRequestOf(inputs: Readonly<Record<string, unknown>> | null | undefined): AiSettingsRead {\n const request: AiSettingsRequest = {}\n const problems: string[] = []\n const bounded = (key: keyof typeof AI_SETTINGS_LIMITS, noun: string) => {\n const value = text(inputs?.[key])\n if (!value) return\n if (value.length > AI_SETTINGS_LIMITS[key]) {\n problems.push(`The ${noun} is longer than ${AI_SETTINGS_LIMITS[key]} characters.`)\n return\n }\n request[key] = value\n }\n bounded('name', 'site name')\n bounded('seoTitle', 'search title')\n bounded('seoDescription', 'search description')\n bounded('separator', 'title separator')\n bounded('businessName', 'business name')\n bounded('businessDescription', 'business description')\n bounded('address', 'address')\n bounded('titlePattern', 'title pattern')\n if (request.titlePattern && !aiSettingsTitlePatternOk(request.titlePattern)) {\n problems.push('The title pattern may use only {{page.name}}, {{site.separator}} and {{site.name}}.')\n delete request.titlePattern\n }\n bounded('telephone', 'phone number')\n if (request.telephone && !TELEPHONE.test(request.telephone)) {\n problems.push(`“${request.telephone}” is not a phone number.`)\n delete request.telephone\n }\n bounded('supportEmail', 'contact email')\n if (request.supportEmail && !EMAIL.test(request.supportEmail)) {\n problems.push(`“${request.supportEmail}” is not an email address.`)\n delete request.supportEmail\n }\n const language = text(inputs?.['language'])\n if (language) {\n const locale = siteLanguageCode(language)\n if (locale) request.language = locale\n else problems.push(`“${language}” is not a language code such as es or pt-BR.`)\n }\n const timeZone = text(inputs?.['timeZone'])\n if (timeZone) {\n if (supportedTimeZones().includes(timeZone)) request.timeZone = timeZone\n else problems.push(`“${timeZone}” is not a time zone the site settings offer.`)\n }\n const consentMode = text(inputs?.['consentMode'])\n if (consentMode) {\n if ((AI_SETTINGS_CONSENT_MODES as readonly string[]).includes(consentMode)) {\n request.consentMode = consentMode as AiSettingsRequest['consentMode']\n } else problems.push('The cookie banner’s mode is geo or strict.')\n }\n for (const key of AI_SETTINGS_MEDIA_ARGS) {\n const value = text(inputs?.[key])\n if (value) request[key] = value.slice(0, 200)\n }\n return { request, problems }\n}\n\n/** Whether a read request asks for anything at all. */\nexport function aiSettingsRequestEmpty(request: AiSettingsRequest): boolean {\n return Object.keys(request).length === 0\n}\n\n// ── Media ─────────────────────────────────────────────────────────────────\n\n/** A media library row, as a setting may name it. */\nexport interface AiSettingsMediaRow {\n id: string\n fileName: string\n contentType: string\n url: string | null\n cdnPath: string | null\n contentHash: string | null\n private: boolean\n deleted: boolean\n /** The org library's sites; `undefined` on the site's own library. */\n visibleTo?: readonly string[] | null\n width: number | null\n height: number | null\n alt: string\n}\n\n/** The image a setting names, as written to the host. */\nexport interface AiSettingsMedia {\n src: string\n width: number | null\n height: number | null\n alt: string\n fileName: string\n}\n\nfunction mediaRowOf(doc: FirebaseFirestore.QueryDocumentSnapshot | FirebaseFirestore.DocumentSnapshot, org: boolean): AiSettingsMediaRow {\n const data = (doc.data() ?? {}) as Record<string, unknown>\n const number = (value: unknown) => (typeof value === 'number' && value > 0 ? value : null)\n return {\n id: doc.id,\n fileName: String(data['fileName'] ?? ''),\n contentType: String(data['contentType'] ?? ''),\n url: typeof data['url'] === 'string' ? data['url'] : null,\n cdnPath: typeof data['cdnPath'] === 'string' ? data['cdnPath'] : null,\n contentHash: typeof data['contentHash'] === 'string' ? data['contentHash'] : null,\n private: data['private'] === true,\n deleted: data['deletedAt'] != null,\n ...(org ? { visibleTo: Array.isArray(data['visibleTo']) ? (data['visibleTo'] as string[]) : null } : {}),\n width: number(data['width']),\n height: number(data['height']),\n alt: typeof data['alt'] === 'string' ? data['alt'] : '',\n }\n}\n\n/**\n * The rows a media name could be, from the site's own library and then its\n * org's: the one whose id it is, else those whose file name it is.\n */\nexport async function readAiSettingsMediaRows(\n firestore: Firestore,\n input: { hostId: string; orgId: string; source: string },\n): Promise<AiSettingsMediaRow[]> {\n const libraries = [\n { ref: firestore.collection('hosts').doc(input.hostId).collection('media'), org: false },\n { ref: firestore.collection('orgs').doc(input.orgId).collection('media'), org: true },\n ]\n const rows: AiSettingsMediaRow[] = []\n for (const library of libraries) {\n if (/^[A-Za-z0-9_-]{1,128}$/.test(input.source)) {\n const byId = await library.ref.doc(input.source).get()\n if (byId.exists) rows.push(mediaRowOf(byId, library.org))\n }\n const byName = await library.ref.where('fileName', '==', input.source).limit(5).get()\n for (const doc of byName.docs) if (!rows.some((row) => row.id === doc.id)) rows.push(mediaRowOf(doc, library.org))\n }\n return rows\n}\n\n/**\n * The image a setting names, chosen from the rows read: a public image of\n * this site's library, or of its org's that this site may use, never deleted.\n * Its id wins over a file name; two images of one name are refused in words.\n */\nexport function aiSettingsMediaOf(\n arg: AiSettingsMediaArg,\n source: string,\n rows: readonly AiSettingsMediaRow[],\n hostId: string,\n): AiSettingsMedia | { error: string } {\n const noun = MEDIA_ARG_NOUNS[arg]\n const usable = rows.filter(\n (row) =>\n !row.deleted &&\n !row.private &&\n row.contentType.startsWith('image/') &&\n (row.visibleTo === undefined || visibleToHost(row.visibleTo, hostId)),\n )\n const byId = usable.find((row) => row.id === source)\n const named = usable.filter((row) => row.fileName === source)\n if (!byId && named.length > 1) return { error: `The media library has more than one image called “${source}”; name the one for the ${noun}.` }\n const row = byId ?? named[0]\n if (!row) return { error: `The media library has no image “${source}” this site can use for the ${noun}.` }\n const src = mediaNodeSrc({ url: row.url, cdnPath: row.cdnPath, contentHash: row.contentHash, private: row.private })\n if (!src) return { error: `The image “${source}” has no address the site can show.` }\n return { src, width: row.width, height: row.height, alt: row.alt, fileName: row.fileName || row.id }\n}\n\n// ── The write ─────────────────────────────────────────────────────────────\n\n/** One change to the host document, with the sentence that says it was made. */\ninterface AiSettingsChange {\n path: string\n value: unknown\n said: string\n /** The field is deleted rather than set; `value` is then ignored. */\n remove?: true\n}\n\n/**\n * The structured address parts a one-line address leaves empty (AGL-4136):\n * the line is the street, and a city or postal code still stored from an\n * older address would contradict it.\n */\nconst ADDRESS_PARTS_A_LINE_REPLACES = [\n 'addressLocality',\n 'addressRegion',\n 'postalCode',\n 'addressCountry',\n] as const\n\n/** Whether a stored value is there to delete. */\nconst isStored = (value: unknown): boolean =>\n value !== undefined && value !== null && !(typeof value === 'string' && value.trim() === '')\n\nconst getPath = (data: Record<string, unknown>, path: string): unknown =>\n path.split('.').reduce<unknown>((at, key) => (at && typeof at === 'object' ? (at as Record<string, unknown>)[key] : undefined), data)\n\nconst sameValue = (a: unknown, b: unknown): boolean => JSON.stringify(a ?? null) === JSON.stringify(b ?? null)\n\n/**\n * The language change, as the Languages card would save it: a site with no\n * languages, or one, now publishes in this one; a multilingual site that\n * lists it makes it the default. A multilingual site that does not list it\n * is refused, because adding a language is the Languages card's decision.\n */\nexport function aiSettingsLanguageChanges(\n host: { locales?: unknown; defaultLocale?: unknown },\n language: string,\n): AiSettingsChange[] | { error: string } {\n const locales = Array.isArray(host.locales) ? host.locales.filter((one): one is string => typeof one === 'string') : []\n const said = `The site’s language is now ${language}.`\n if (locales.length > 1) {\n if (!locales.includes(language)) {\n return { error: `This site publishes in ${locales.join(', ')}; add ${language} in Settings → Details → Languages first.` }\n }\n return [{ path: 'defaultLocale', value: language, said }]\n }\n return [\n { path: 'locales', value: [language], said },\n { path: 'defaultLocale', value: language, said },\n ]\n}\n\n/** Every change the request asks of this host, before comparing with what is stored. */\nexport function aiSettingsChanges(\n host: Record<string, unknown>,\n request: AiSettingsRequest,\n media: Partial<Record<AiSettingsMediaArg, AiSettingsMedia>>,\n): { changes: AiSettingsChange[]; problems: string[] } {\n const changes: AiSettingsChange[] = []\n const problems: string[] = []\n const set = (path: string, value: unknown, said: string) => changes.push({ path, value, said })\n if (request.name) set('displayName', request.name, `The site is now called “${request.name}”.`)\n if (request.seoTitle) set('seo.title', request.seoTitle, `The search title is now “${request.seoTitle}”.`)\n if (request.seoDescription) set('seo.description', request.seoDescription, 'The search description is set.')\n if (request.separator) set('seo.separator', request.separator, `The title separator is now “${request.separator}”.`)\n if (request.titlePattern) set('seo.titlePattern', request.titlePattern, `Untitled pages are now titled “${request.titlePattern}”.`)\n if (request.businessName) set('seo.entity.name', request.businessName, `The business name is now “${request.businessName}”.`)\n if (request.businessDescription) set('seo.entity.description', request.businessDescription, 'The business description is set.')\n if (request.telephone) set('seo.entity.telephone', request.telephone, `The phone number is now ${request.telephone}.`)\n if (request.supportEmail) {\n // The site's one email (AGL-4136): the canonical `seo.entity.email`, and\n // the `business.supportEmail` copy Setup → Business profile keeps in step for the\n // native apps, so every reader shows the new address at once.\n const said = `The contact email is now ${request.supportEmail}.`\n set('seo.entity.email', request.supportEmail, said)\n set('business.supportEmail', request.supportEmail, said)\n }\n if (request.address) {\n // The address arrives as ONE line, which cannot be split into the parts\n // Setup → Business profile stores (AGL-4136). So the whole line is the\n // street, the other parts are deleted where the site has them, so an\n // older city or postal code cannot contradict it, and the one-block\n // `business.address` copy says the same. Every reader then shows the\n // new address, whichever path it reads.\n const said = 'The address is set.'\n set('seo.entity.address.streetAddress', request.address, said)\n for (const part of ADDRESS_PARTS_A_LINE_REPLACES) {\n const path = `seo.entity.address.${part}`\n if (isStored(getPath(host, path))) changes.push({ path, value: null, said, remove: true })\n }\n set('business.address', request.address, said)\n }\n if (request.timeZone) set('timeZone', request.timeZone, `The site’s time zone is now ${request.timeZone}.`)\n if (request.consentMode) {\n set('consent.mode', request.consentMode, request.consentMode === 'strict' ? 'The cookie banner now asks every visitor.' : 'The cookie banner now asks where the law requires.')\n }\n if (request.language) {\n const language = aiSettingsLanguageChanges(host, request.language)\n if ('error' in language) problems.push(language.error)\n else changes.push(...language)\n }\n if (media.favicon) set('seo.favicon', media.favicon.src, `The favicon is now “${media.favicon.fileName}”.`)\n if (media.logo) set('logoUrl', media.logo.src, `The logo is now “${media.logo.fileName}”.`)\n if (media.socialImage) {\n const image = media.socialImage\n const said = `The social image is now “${image.fileName}”.`\n set('seo.image', image.src, said)\n // Its size and alt, as the Social image card copies them at pick time.\n set('seo.imageWidth', image.width ?? 0, said)\n set('seo.imageHeight', image.height ?? 0, said)\n const savedAlt = getPath(host, 'seo.imageAlt')\n set('seo.imageAlt', inheritedMediaAlt({ placementAlt: savedAlt, assetAlt: image.alt }) ?? (typeof savedAlt === 'string' ? savedAlt : ''), said)\n }\n return { changes, problems }\n}\n\nexport type AiSettingsWrite =\n | { ok: true; done: string[]; notDone: string[]; changed: string[]; outboxId: string | null }\n | { ok: false; error: string }\n\n/**\n * The settings written, in one transaction that reads the host as it is\n * stored NOW: the member still holds a write role, and only the values that\n * differ from what is stored are written, with a site-wide publish outbox\n * entry beside them so the live site's cached pages are dropped.\n */\nexport async function writeAiSiteSettings(\n firestore: Firestore,\n input: {\n hostId: string\n uid: string\n request: AiSettingsRequest\n media: Partial<Record<AiSettingsMediaArg, AiSettingsMedia>>\n now: Date\n },\n): Promise<AiSettingsWrite> {\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n return firestore.runTransaction(async (tx): Promise<AiSettingsWrite> => {\n const host = await tx.get(hostRef)\n if (!host.exists) return { ok: false, error: 'Unknown site' }\n if (!holdsSiteKey(host, input.uid, 'site.edit')) return { ok: false, error: AI_SETTINGS_ROLE_COPY }\n const data = (host.data() ?? {}) as Record<string, unknown>\n const { changes, problems } = aiSettingsChanges(data, input.request, input.media)\n const changed = changes.filter((change) =>\n change.remove ? isStored(getPath(data, change.path)) : !sameValue(getPath(data, change.path), change.value),\n )\n const done = [...new Set(changes.map((change) => change.said))]\n if (!changed.length) return { ok: true, done, notDone: problems, changed: [], outboxId: null }\n // The changes and the site-wide outbox entry beside them, through the one\n // server writer every site-settings save shares (AGL-4235).\n const outboxId = stageSiteSettingsWrite(tx, firestore, { hostRef, hostId: input.hostId, changes: changed, now: input.now })\n return { ok: true, done, notDone: problems, changed: changed.map((change) => change.path), outboxId }\n })\n}\n\n// ── The step ──────────────────────────────────────────────────────────────\n\n/** Why this member may not change this site's settings now, or `null`. */\nexport async function aiSettingsAccessRefusal(\n input: { host: FirebaseFirestore.DocumentSnapshot; uid: string; org: object | null },\n deps: { lockdown?: typeof getLockdownVerdict } = {},\n): Promise<string | null> {\n if (!input.host.exists) return 'Unknown site'\n if (!holdsSiteKey(input.host, input.uid, 'site.edit')) return AI_SETTINGS_ROLE_COPY\n const locked = await (deps.lockdown ?? getLockdownVerdict)({\n staff: false,\n uid: input.uid,\n org: input.org as never,\n host: input.host.data() as never,\n intent: 'write',\n })\n return locked ? AI_SETTINGS_LOCKED_COPY : null\n}\n\n/** The output's note: what changed, that it is live, and what was not done. */\nexport function aiSettingsOutputNote(done: readonly string[], notDone: readonly string[], language: boolean): string {\n // The build's own wording for an item with no draft state (AGL-3745).\n const did = done.length ? `${done.join(' ')} Live now, in ${AI_SETTINGS_WHERE}.` : 'Nothing needed changing.'\n const translate = language ? ' The pages keep the words they have: changing the language does not translate them.' : ''\n const not = notDone.length ? ` Not done: ${notDone.join(' ')}` : ''\n return `${did}${translate}${not}`.slice(0, 1_000)\n}\n\nexport interface AiJobSettingsStepDeps {\n readMedia?: typeof readAiSettingsMediaRows\n write?: typeof writeAiSiteSettings\n lockdown?: typeof getLockdownVerdict\n dropCache?: typeof dropPluginSiteCache\n syncMemberships?: typeof syncHostProjectionForMembers\n}\n\n/** Each media argument resolved to its image, or a sentence for each that cannot be. */\nasync function mediaOf(\n firestore: Firestore,\n input: { hostId: string; orgId: string; request: AiSettingsRequest },\n readMedia: typeof readAiSettingsMediaRows,\n): Promise<{ media: Partial<Record<AiSettingsMediaArg, AiSettingsMedia>>; problems: string[] }> {\n const media: Partial<Record<AiSettingsMediaArg, AiSettingsMedia>> = {}\n const problems: string[] = []\n for (const arg of AI_SETTINGS_MEDIA_ARGS) {\n const source = input.request[arg]\n if (!source) continue\n const rows = await readMedia(firestore, { hostId: input.hostId, orgId: input.orgId, source })\n const found = aiSettingsMediaOf(arg, source, rows, input.hostId)\n if ('error' in found) problems.push(found.error)\n else media[arg] = found\n }\n return { media, problems }\n}\n\nexport function createAiJobSettingsStep(deps: AiJobSettingsStepDeps = {}): AiJobStepRunner {\n const readMedia = deps.readMedia ?? readAiSettingsMediaRows\n const write = deps.write ?? writeAiSiteSettings\n const dropCache = deps.dropCache ?? dropPluginSiteCache\n const syncMemberships = deps.syncMemberships ?? syncHostProjectionForMembers\n return async ({ job, now, firestore, org, modelFor }): Promise<AiJobStepOutcome> => {\n // No model is asked: the outcome records the edit step's at no cost.\n const model = modelFor?.('job.edit') ?? aiJobEditModel()\n const unspent = (failure: string): AiJobStepOutcome => ({ ...aiUnspentOutcome(model), failure })\n const hostId = job.hostId\n if (!hostId) return unspent(AI_SETTINGS_NO_SITE_COPY)\n const read = aiSettingsRequestOf(job.inputs)\n if (aiSettingsRequestEmpty(read.request)) return unspent([AI_SETTINGS_NOTHING_COPY, ...read.problems].join(' '))\n const orgData = (org ?? ((await firestore.collection('orgs').doc(job.orgId).get()).data() ?? null)) as Record<string, unknown> | null\n const host = await firestore.collection('hosts').doc(hostId).get()\n const refused = await aiSettingsAccessRefusal({ host, uid: job.createdBy, org: orgData }, { lockdown: deps.lockdown })\n if (refused) return aiUnspentOutcome(model, { review: aiLimitReview(refused) })\n const found = await mediaOf(firestore, { hostId, orgId: job.orgId, request: read.request }, readMedia)\n const written = await write(firestore, { hostId, uid: job.createdBy, request: read.request, media: found.media, now })\n if (written.ok === false) return unspent(written.error)\n const notDone = [...read.problems, ...found.problems, ...written.notDone]\n if (!written.done.length) return unspent([AI_SETTINGS_NOTHING_COPY, ...notDone].join(' '))\n if (written.outboxId) {\n // The live site's cached pages go now; the outbox entry stays for the\n // drain unless the drop certainly happened.\n const dropped = await dropCache({ hostIds: [hostId], reason: 'AI build changed site settings' }).catch(() => ({ complete: false }))\n if (dropped.complete) await firestore.collection('publishOutbox').doc(written.outboxId).delete().catch(() => undefined)\n }\n if (changesProjectedHostFields(written.changed)) {\n // Every site list reads the name and favicon members' rows carry, so a\n // new favicon owes the re-fan as much as a new name does (AGL-3972).\n await syncMemberships(job.orgId, hostId).catch((error: unknown) => {\n console.error('ai settings: membership projection not synced', { hostId, jobId: job.$id, error })\n })\n }\n const output: AiJobOutput = {\n resource: 'settings',\n id: AI_SETTINGS_OUTPUT_ID,\n hostId,\n hostSubdomain: (typeof host.get('subdomain') === 'string' && host.get('subdomain')) || null,\n label: 'Site settings',\n note: aiSettingsOutputNote(written.done, notDone, Boolean(read.request.language)),\n }\n return aiUnspentOutcome(model, { outputs: [output] })\n }\n}\n\nexport const runAiJobSettingsStep = createAiJobSettingsStep()\n\n// ── Admission ─────────────────────────────────────────────────────────────\n\nexport interface AiSettingsJobAdmissionDeps {\n ownerOf?: typeof resolveOrgIdForHost\n lockdown?: typeof getLockdownVerdict\n}\n\n/**\n * A settings change is admitted on a site of the job's own org, for a member\n * who may write its settings now, where the request names at least one\n * setting this can change. Refused in those words before anything is written.\n */\nexport function createAiSettingsJobAdmission(deps: AiSettingsJobAdmissionDeps = {}): AiJobAdmission {\n const ownerOf = deps.ownerOf ?? resolveOrgIdForHost\n return async (context): Promise<AiJobAdmissionRefusal | null> => {\n if (!context.hostId) return { status: 400, error: AI_SETTINGS_NO_SITE_COPY }\n const owner = await ownerOf(context.hostId)\n if (!owner || owner !== context.orgId) return { status: 404, error: 'Unknown site' }\n const host = await context.firestore.collection('hosts').doc(context.hostId).get()\n const refused = await aiSettingsAccessRefusal({ host, uid: context.uid ?? '', org: context.org }, { lockdown: deps.lockdown })\n if (refused) return { status: 403, error: refused }\n const read = aiSettingsRequestOf(context.inputs as Record<string, unknown>)\n return aiSettingsRequestEmpty(read.request) ? { status: 400, error: [AI_SETTINGS_NOTHING_COPY, ...read.problems].join(' ') } : null\n }\n}\n\nexport const aiSettingsJobAdmission = createAiSettingsJobAdmission()\n\n/** Registers the settings step and its door (AGL-3748). */\nexport function registerAiSettingsJob(): void {\n registerAiJobStep(AI_SETTINGS_KIND, runAiJobSettingsStep, { minimumMs: AI_JOB_SETTINGS_STEP_MINIMUM_MS })\n registerAiJobAdmission(AI_SETTINGS_KIND, aiSettingsJobAdmission)\n}\n\n"],"names":["supportedTimeZones","holdsSiteKey","orgPermissionLabel","inheritedMediaAlt","mediaNodeSrc","visibleToHost","siteLanguageCode","SEO_DESCRIPTION_MAX_LENGTH","SEO_TITLE_MAX_LENGTH","SITE_SEO_SEPARATOR_MAX_LENGTH","SITE_SEO_TITLE_PATTERN_MAX_LENGTH","isSeoTitleVariable","dropPluginSiteCache","changesProjectedHostFields","syncHostProjectionForMembers","getLockdownVerdict","resolveOrgIdForHost","stageSiteSettingsWrite","registerAiJobAdmission","aiJobEditModel","aiLimitReview","aiUnspentOutcome","registerAiJobStep","AI_SETTINGS_KIND","AI_JOB_SETTINGS_STEP_MINIMUM_MS","AI_SETTINGS_NO_SITE_COPY","AI_SETTINGS_ROLE_COPY","AI_SETTINGS_LOCKED_COPY","AI_SETTINGS_NOTHING_COPY","AI_SETTINGS_WHERE","AI_SETTINGS_OUTPUT_ID","AI_SETTINGS_LIMITS","name","seoTitle","seoDescription","separator","titlePattern","businessDescription","businessName","telephone","supportEmail","address","AI_SETTINGS_CONSENT_MODES","AI_SETTINGS_MEDIA_ARGS","MEDIA_ARG_NOUNS","favicon","logo","socialImage","AI_SETTINGS_ARGS_SCHEMA","type","properties","description","maxLength","language","timeZone","consentMode","enum","additionalProperties","text","value","replace","trim","EMAIL","TELEPHONE","PATTERN_VARIABLE","aiSettingsTitlePatternOk","pattern","test","matchAll","every","match","aiSettingsRequestOf","inputs","request","problems","bounded","key","noun","length","push","locale","includes","slice","aiSettingsRequestEmpty","Object","keys","mediaRowOf","doc","org","data","number","id","fileName","String","contentType","url","cdnPath","contentHash","private","deleted","visibleTo","Array","isArray","width","height","alt","readAiSettingsMediaRows","firestore","input","libraries","ref","collection","hostId","orgId","rows","library","source","byId","get","exists","byName","where","limit","docs","some","row","aiSettingsMediaOf","arg","usable","filter","startsWith","undefined","find","named","error","src","ADDRESS_PARTS_A_LINE_REPLACES","isStored","getPath","path","split","reduce","at","sameValue","a","b","JSON","stringify","aiSettingsLanguageChanges","host","locales","one","said","join","aiSettingsChanges","media","changes","set","part","remove","image","savedAlt","placementAlt","assetAlt","writeAiSiteSettings","hostRef","runTransaction","tx","ok","uid","changed","change","done","Set","map","notDone","outboxId","now","aiSettingsAccessRefusal","deps","locked","lockdown","staff","intent","aiSettingsOutputNote","did","translate","not","mediaOf","readMedia","found","createAiJobSettingsStep","write","dropCache","syncMemberships","job","modelFor","model","unspent","failure","read","orgData","refused","createdBy","review","written","dropped","hostIds","reason","catch","complete","delete","console","jobId","$id","output","resource","hostSubdomain","label","note","Boolean","outputs","runAiJobSettingsStep","createAiSettingsJobAdmission","ownerOf","context","status","owner","aiSettingsJobAdmission","registerAiSettingsJob","minimumMs"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,+CAA8C;AACjF,SAASC,YAAY,QAAQ,0CAAyC;AACtE,SAASC,kBAAkB,QAAQ,yCAAwC;AAC3E,SAASC,iBAAiB,QAAQ,wCAAuC;AACzE,SAASC,YAAY,QAAQ,mCAAkC;AAC/D,SAASC,aAAa,QAAQ,sCAAqC;AACnE,SAASC,gBAAgB,QAAQ,oCAAmC;AACpE,SAASC,0BAA0B,EAAEC,oBAAoB,QAAQ,2CAA0C;AAC3G,SAASC,6BAA6B,EAAEC,iCAAiC,QAAQ,4CAA2C;AAC5H,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SAASC,mBAAmB,QAAQ,gDAA+C;AAEnF,SAASC,0BAA0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QAC3E,MAAM0M,QAAQ,MAAMH,QAAQC,QAAQjH,MAAM;QAC1C,IAAI,CAACmH,SAASA,UAAUF,QAAQhH,KAAK,EAAE,OAAO;YAAEiH,QAAQ;YAAK5F,OAAO;QAAe;QACnF,MAAMe,OAAO,MAAM4E,QAAQtH,SAAS,CAACI,UAAU,CAAC,SAASxB,GAAG,CAAC0I,QAAQjH,MAAM,EAAEM,GAAG;QAChF,MAAMoF,UAAU,MAAMxB,wBAAwB;YAAE7B;YAAMoB,GAAG,GAAEwD,eAAAA,QAAQxD,GAAG,YAAXwD,eAAe;YAAIzI,KAAKyI,QAAQzI,GAAG;QAAC,GAAG;YAAE6F,UAAUF,KAAKE,QAAQ;QAAC;QAC5H,IAAIqB,SAAS,OAAO;YAAEwB,QAAQ;YAAK5F,OAAOoE;QAAQ;QAClD,MAAMF,OAAOjI,oBAAoB0J,QAAQzJ,MAAM;QAC/C,OAAOW,uBAAuBqH,KAAK/H,OAAO,IAAI;YAAEyJ,QAAQ;YAAK5F,OAAO;gBAAC1G;mBAA6B4K,KAAK9H,QAAQ;aAAC,CAAC+E,IAAI,CAAC;QAAK,IAAI;IACjI;AACF;AAEA,OAAO,MAAM2E,yBAAyBL,+BAA8B;AAEpE,yDAAyD,GACzD,OAAO,SAASM;IACd/M,kBAAkBC,kBAAkBuM,sBAAsB;QAAEQ,WAAW9M;IAAgC;IACvGN,uBAAuBK,kBAAkB6M;AAC3C"}
|
|
@@ -73,6 +73,8 @@ export declare const AI_EDIT_NOTHING_COPY = "No change could be made from that r
|
|
|
73
73
|
export declare const AI_EDIT_STALE_COPY = "The page changed while this edit was being written, so nothing was saved. Ask again.";
|
|
74
74
|
/** The canvas's own guards refused part of the change. */
|
|
75
75
|
export declare const AI_EDIT_REFUSED_COPY = "The editor refused part of this change, so none of it was saved.";
|
|
76
|
+
/** The change would make the document larger than a save can store (AGL-4235). */
|
|
77
|
+
export declare const AI_EDIT_TOO_LARGE_COPY = "With this change the page would be too large to save, so none of it was saved.";
|
|
76
78
|
/** What a version an edit job makes is called, from the change's one-line summary. */
|
|
77
79
|
export declare const AI_EDIT_VERSION_PREFIX = "AI edit";
|
|
78
80
|
/** The longest label a version takes, as the versions route cuts one. */
|
|
@@ -105,6 +107,29 @@ export declare function aiEditOutputNote(input: {
|
|
|
105
107
|
export declare const AI_EDIT_SEO_LEFT_OUT = "the search title and description, which a published page uses as soon as they are saved \u2014 change them in Page properties";
|
|
106
108
|
/** What the output says of a part a job cannot save on its own. */
|
|
107
109
|
export declare const AI_EDIT_COMPONENT_LEFT_OUT = "saving part of the page as a reusable component, which is done in the editor";
|
|
110
|
+
/** One element of a stored document, in the order the document reads. */
|
|
111
|
+
export interface AiDocumentElement {
|
|
112
|
+
id: string;
|
|
113
|
+
/** The element it sits in, or null for the document root. */
|
|
114
|
+
parentId: string | null;
|
|
115
|
+
/** Its position among its parent's children. */
|
|
116
|
+
index: number;
|
|
117
|
+
/** The elements placed inside it by this walk, in their stored order. */
|
|
118
|
+
children: string[];
|
|
119
|
+
/** How many children the element lists that are on the document, whatever the walk placed. */
|
|
120
|
+
childCount: number;
|
|
121
|
+
/** The stored node, as it is. */
|
|
122
|
+
node: Record<string, unknown>;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Every element of a stored document (AGL-4235), complete: the document root,
|
|
126
|
+
* then each element after its parent, depth first, children in their stored
|
|
127
|
+
* order — the page as it reads. An element listed under two parents is placed
|
|
128
|
+
* once, under the first the walk reaches; a child id with no node is skipped.
|
|
129
|
+
* Nothing is capped or shortened: this is the one walker, and a reader with a
|
|
130
|
+
* budget caps what it returns. `null` without a root.
|
|
131
|
+
*/
|
|
132
|
+
export declare function aiDocumentElements(nodes: Readonly<Record<string, unknown>>): AiDocumentElement[] | null;
|
|
108
133
|
/**
|
|
109
134
|
* The stored document as the outline the edit rung's protocol reads
|
|
110
135
|
* (`parseAssistEditContext` with `whole` holds it to its limits): the
|
|
@@ -118,6 +143,8 @@ export declare const AI_EDIT_COMPONENT_LEFT_OUT = "saving part of the page as a
|
|
|
118
143
|
* see, and a restyle starts from the styles the element has. Each element
|
|
119
144
|
* keeps its real child count and the document its real size, so the prompt
|
|
120
145
|
* can say what a document past the cap leaves out. `null` without a root.
|
|
146
|
+
*
|
|
147
|
+
* The walk is {@link aiDocumentElements}'s; this applies the outline's cap.
|
|
121
148
|
*/
|
|
122
149
|
export declare function aiEditJobOutline(nodes: Readonly<Record<string, unknown>>): {
|
|
123
150
|
selectedId: null;
|
|
@@ -79,6 +79,7 @@ export const AI_EDIT_NO_NODES_COPY = 'That version has nothing on it to change.'
|
|
|
79
79
|
/** The model answered and no change survived its checks, even after its re-ask. */ export const AI_EDIT_NOTHING_COPY = 'No change could be made from that request. Say which part of the page to change, the way it reads on the page, and ask again.';
|
|
80
80
|
/** The stored document moved under the change between the read and the write. */ export const AI_EDIT_STALE_COPY = 'The page changed while this edit was being written, so nothing was saved. Ask again.';
|
|
81
81
|
/** The canvas's own guards refused part of the change. */ export const AI_EDIT_REFUSED_COPY = 'The editor refused part of this change, so none of it was saved.';
|
|
82
|
+
/** The change would make the document larger than a save can store (AGL-4235). */ export const AI_EDIT_TOO_LARGE_COPY = 'With this change the page would be too large to save, so none of it was saved.';
|
|
82
83
|
/** What a version an edit job makes is called, from the change's one-line summary. */ export const AI_EDIT_VERSION_PREFIX = 'AI edit';
|
|
83
84
|
/** The longest label a version takes, as the versions route cuts one. */ export const AI_EDIT_VERSION_NAME_MAX_CHARS = 200;
|
|
84
85
|
export function aiEditVersionName(summary) {
|
|
@@ -105,23 +106,18 @@ const NOUNS = {
|
|
|
105
106
|
// ── The outline the model is shown ────────────────────────────────────────
|
|
106
107
|
const isRecord = (value)=>typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
107
108
|
/**
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
*
|
|
112
|
-
*
|
|
113
|
-
*
|
|
114
|
-
|
|
115
|
-
* A job has no selection and nobody to ask, so it is the WHOLE document: a
|
|
116
|
-
* request about a picture five levels down is about an element the model can
|
|
117
|
-
* see, and a restyle starts from the styles the element has. Each element
|
|
118
|
-
* keeps its real child count and the document its real size, so the prompt
|
|
119
|
-
* can say what a document past the cap leaves out. `null` without a root.
|
|
120
|
-
*/ export function aiEditJobOutline(nodes) {
|
|
109
|
+
* Every element of a stored document (AGL-4235), complete: the document root,
|
|
110
|
+
* then each element after its parent, depth first, children in their stored
|
|
111
|
+
* order — the page as it reads. An element listed under two parents is placed
|
|
112
|
+
* once, under the first the walk reaches; a child id with no node is skipped.
|
|
113
|
+
* Nothing is capped or shortened: this is the one walker, and a reader with a
|
|
114
|
+
* budget caps what it returns. `null` without a root.
|
|
115
|
+
*/ export function aiDocumentElements(nodes) {
|
|
121
116
|
const root = nodes[CANVAS_ROOT_ELEMENT_ID];
|
|
122
117
|
if (!isRecord(root)) return null;
|
|
123
118
|
const childrenOf = (node)=>Array.isArray(node['nodes']) ? node['nodes'].filter((id)=>typeof id === 'string' && isRecord(nodes[id])) : [];
|
|
124
119
|
const order = [];
|
|
120
|
+
const byId = new Map();
|
|
125
121
|
const seen = new Set([
|
|
126
122
|
CANVAS_ROOT_ELEMENT_ID
|
|
127
123
|
]);
|
|
@@ -134,11 +130,20 @@ const isRecord = (value)=>typeof value === 'object' && value !== null && !Array.
|
|
|
134
130
|
}
|
|
135
131
|
];
|
|
136
132
|
while(stack.length){
|
|
133
|
+
var _byId_get;
|
|
137
134
|
const at = stack.pop();
|
|
138
|
-
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
|
|
135
|
+
const node = nodes[at.id];
|
|
136
|
+
const listed = childrenOf(node);
|
|
137
|
+
const element = _extends({}, at, {
|
|
138
|
+
children: [],
|
|
139
|
+
childCount: listed.length,
|
|
140
|
+
node
|
|
141
|
+
});
|
|
142
|
+
order.push(element);
|
|
143
|
+
byId.set(at.id, element);
|
|
144
|
+
if (at.parentId !== null) (_byId_get = byId.get(at.parentId)) == null ? void 0 : _byId_get.children.push(at.id);
|
|
145
|
+
for(let index = listed.length - 1; index >= 0; index -= 1){
|
|
146
|
+
const child = listed[index];
|
|
142
147
|
if (seen.has(child)) continue;
|
|
143
148
|
seen.add(child);
|
|
144
149
|
stack.push({
|
|
@@ -148,25 +153,42 @@ const isRecord = (value)=>typeof value === 'object' && value !== null && !Array.
|
|
|
148
153
|
});
|
|
149
154
|
}
|
|
150
155
|
}
|
|
156
|
+
return order;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* The stored document as the outline the edit rung's protocol reads
|
|
160
|
+
* (`parseAssistEditContext` with `whole` holds it to its limits): the
|
|
161
|
+
* document root, then every element in the order it reads on the page — each
|
|
162
|
+
* after its parent, so every ancestor chain the check walks is whole — with
|
|
163
|
+
* its settings and its styles, up to the whole-document cap.
|
|
164
|
+
*
|
|
165
|
+
* In the editor, an outline is the neighborhood of what the author selected.
|
|
166
|
+
* A job has no selection and nobody to ask, so it is the WHOLE document: a
|
|
167
|
+
* request about a picture five levels down is about an element the model can
|
|
168
|
+
* see, and a restyle starts from the styles the element has. Each element
|
|
169
|
+
* keeps its real child count and the document its real size, so the prompt
|
|
170
|
+
* can say what a document past the cap leaves out. `null` without a root.
|
|
171
|
+
*
|
|
172
|
+
* The walk is {@link aiDocumentElements}'s; this applies the outline's cap.
|
|
173
|
+
*/ export function aiEditJobOutline(nodes) {
|
|
174
|
+
const order = aiDocumentElements(nodes);
|
|
175
|
+
if (!order) return null;
|
|
151
176
|
return {
|
|
152
177
|
selectedId: null,
|
|
153
178
|
total: order.length,
|
|
154
|
-
nodes: order.slice(0, ASSIST_EDIT_WHOLE_MAX_NODES).map(({ id, parentId, index })=>{
|
|
155
|
-
const node = nodes[id];
|
|
156
|
-
return _extends({
|
|
179
|
+
nodes: order.slice(0, ASSIST_EDIT_WHOLE_MAX_NODES).map(({ id, parentId, index, childCount, node })=>_extends({
|
|
157
180
|
id,
|
|
158
181
|
componentId: node['componentId'],
|
|
159
182
|
parentId,
|
|
160
183
|
index,
|
|
161
|
-
childCount
|
|
184
|
+
childCount
|
|
162
185
|
}, typeof node['name'] === 'string' && node['name'] ? {
|
|
163
186
|
name: node['name']
|
|
164
187
|
} : {}, isRecord(node['props']) ? {
|
|
165
188
|
props: node['props']
|
|
166
189
|
} : {}, isRecord(node['sx']) ? {
|
|
167
190
|
sx: node['sx']
|
|
168
|
-
} : {})
|
|
169
|
-
})
|
|
191
|
+
} : {}))
|
|
170
192
|
};
|
|
171
193
|
}
|
|
172
194
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-edit-job.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 { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport { ASSIST_EDIT_WHOLE_MAX_NODES } from './assist-edit'\n\n/**\n * An `edit` job (AGL-3616): a change to a page or a layout the site already\n * has, asked for in words, made without the Besigner open.\n *\n * It speaks the Assist edit rung's own protocol — the same tool, the same\n * closed world of element ids, the same validators, the same canvas mutators\n * — against the stored document instead of an open canvas, and the change is\n * saved where no visitor sees it:\n *\n * - by default, on every plan, into the WORKING DRAFT of the version it\n * started from (AGL-4116) — the draft the Besigner saves to as an author\n * works and offers with Open draft, so the author reviews the change and\n * publishes it there exactly as they would their own. A draft the author\n * already has is built on, never replaced;\n * - when the request asks for a new version and the plan keeps version\n * history, as a NEW version beside the one it started from, which becomes\n * the page's current version only when the page is not published; a\n * published page's and a layout's current version never move. Asked for\n * on a plan without version history, the change goes into the draft and\n * the output says why.\n *\n * Pure: the inputs, the sentences a person reads, and the outline the model\n * is shown. The runner is `jobs/ai-job-edit-step.ts`.\n */\n\n/** The documents an edit job changes: those that keep versions and render on a site. */\nexport const AI_EDIT_TARGET_KINDS = ['screen', 'layout'] as const\nexport type AiEditTargetKind = (typeof AI_EDIT_TARGET_KINDS)[number]\n\nexport interface AiEditJobInputs {\n /** The page's or layout's document id, on the job's site. */\n target: string\n /** Which collection the id is in; both are looked in, a page's first, when absent. */\n targetKind: AiEditTargetKind | null\n /** The version to start from; the document's current version when absent. */\n versionId: string | null\n /** The request asked for a new version; otherwise the change goes into the draft. */\n newVersion: boolean\n}\n\nconst DOCUMENT_ID = /^[A-Za-z0-9_-]{1,64}$/\n\nexport const AI_EDIT_TARGET_REQUIRED_COPY = 'Name the page or layout to change.'\nexport const AI_EDIT_TARGET_KIND_COPY = 'inputs.targetKind must be screen or layout'\nexport const AI_EDIT_VERSION_ID_COPY = 'inputs.versionId must name a version of the page or layout'\n\n/** A job's inputs read, or the sentence that says what is wrong with them. */\nexport function parseAiEditJobInputs(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n): AiEditJobInputs | string {\n const target = inputs?.['target']\n if (typeof target !== 'string' || !DOCUMENT_ID.test(target)) return AI_EDIT_TARGET_REQUIRED_COPY\n const kind = inputs?.['targetKind']\n if (kind != null && kind !== '' && !(AI_EDIT_TARGET_KINDS as readonly unknown[]).includes(kind)) {\n return AI_EDIT_TARGET_KIND_COPY\n }\n const versionId = inputs?.['versionId']\n if (versionId != null && versionId !== '' && (typeof versionId !== 'string' || !DOCUMENT_ID.test(versionId))) {\n return AI_EDIT_VERSION_ID_COPY\n }\n return {\n target,\n targetKind: kind ? (kind as AiEditTargetKind) : null,\n versionId: typeof versionId === 'string' && versionId ? versionId : null,\n newVersion: inputs?.['newVersion'] === true,\n }\n}\n\n// ── What a person reads ───────────────────────────────────────────────────\n\nexport const AI_EDIT_NO_SITE_COPY = 'Open the site the change is for before starting the job'\nexport const AI_EDIT_GONE_COPY = 'The page or layout to change is not on the site.'\nexport const AI_EDIT_VERSION_GONE_COPY = 'The version to start from is no longer on the page or layout.'\nexport const AI_EDIT_EMAIL_COPY = 'That is an email design, not a page — change it from Emails → Templates.'\nexport const AI_EDIT_NO_NODES_COPY = 'That version has nothing on it to change.'\n\n/**\n * A change that would land on a version visitors see, on a plan without\n * version history: the versions route's own sentence, after what it means\n * here.\n */\nexport const AI_EDIT_NEEDS_VERSIONING_COPY =\n 'Visitors see that version, so the change has to go into a new version beside it. Version history requires a Pro plan — see Billing to upgrade.'\n\n/** The model answered and no change survived its checks, even after its re-ask. */\nexport const AI_EDIT_NOTHING_COPY =\n 'No change could be made from that request. Say which part of the page to change, the way it reads on the page, and ask again.'\n\n/** The stored document moved under the change between the read and the write. */\nexport const AI_EDIT_STALE_COPY =\n 'The page changed while this edit was being written, so nothing was saved. Ask again.'\n\n/** The canvas's own guards refused part of the change. */\nexport const AI_EDIT_REFUSED_COPY = 'The editor refused part of this change, so none of it was saved.'\n\n/** What a version an edit job makes is called, from the change's one-line summary. */\nexport const AI_EDIT_VERSION_PREFIX = 'AI edit'\n\n/** The longest label a version takes, as the versions route cuts one. */\nexport const AI_EDIT_VERSION_NAME_MAX_CHARS = 200\n\nexport function aiEditVersionName(summary: string): string {\n const said = String(summary ?? '').replace(/\\s+/g, ' ').trim()\n return (said ? `${AI_EDIT_VERSION_PREFIX}: ${said}` : AI_EDIT_VERSION_PREFIX).slice(0, AI_EDIT_VERSION_NAME_MAX_CHARS)\n}\n\n/** Where the change landed, which decides what the output's note says. */\nexport type AiEditPlacement =\n /** A new version, now the unpublished page's current one. */\n | 'new-current'\n /** A new version beside the one it started from, which is unchanged. */\n | 'new-beside'\n /** The version it started from, changed in place: one no visitor reaches. Written before AGL-4116. */\n | 'in-place'\n /** The working draft of the version it started from, which the Besigner offers with Open draft. */\n | 'draft'\n\nconst NOUNS: Readonly<Record<AiEditTargetKind, string>> = { screen: 'page', layout: 'layout' }\n\n/**\n * Why a change asked for as a new version went into the draft: the plan\n * keeps no version history. The versions route's own words for the plan.\n */\nexport const AI_EDIT_NO_VERSIONS_DRAFT_COPY =\n 'A new version needs version history, which requires a Pro plan, so the change went into the draft instead.'\n\n/** The output's note: where the change is, that nothing visitors see moved, and what was left out. */\nexport function aiEditOutputNote(input: {\n kind: AiEditTargetKind\n placement: AiEditPlacement\n leftOut: readonly string[]\n /** A new version was asked for on a plan without version history. */\n versionsUnavailable?: boolean\n}): string {\n const noun = NOUNS[input.kind]\n const where =\n input.placement === 'draft'\n ? `Saved as this ${noun}’s draft. Nothing visitors see has changed: open it in the Besigner to review it, then publish it when it is ready.`\n : input.placement === 'new-current'\n ? `Saved as a new version, now this ${noun}’s current one. The ${noun} is not published, so no visitor sees it until you publish it.`\n : input.placement === 'new-beside'\n ? `Saved as a new version beside the one it started from. Nothing visitors see has changed: open it to review it, and publish it when it is ready.`\n : `Saved on the version it started from, which no visitor sees: open it to review it.`\n const versions = input.versionsUnavailable ? ` ${AI_EDIT_NO_VERSIONS_DRAFT_COPY}` : ''\n const leftOut = input.leftOut.length ? ` Left out: ${input.leftOut.join('; ')}.` : ''\n return `${where}${versions}${leftOut}`.slice(0, 1_000)\n}\n\n/** What the output says of search fields a published page keeps on the page itself. */\nexport const AI_EDIT_SEO_LEFT_OUT =\n 'the search title and description, which a published page uses as soon as they are saved — change them in Page properties'\n\n/** What the output says of a part a job cannot save on its own. */\nexport const AI_EDIT_COMPONENT_LEFT_OUT = 'saving part of the page as a reusable component, which is done in the editor'\n\n// ── The outline the model is shown ────────────────────────────────────────\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * The stored document as the outline the edit rung's protocol reads\n * (`parseAssistEditContext` with `whole` holds it to its limits): the\n * document root, then every element in the order it reads on the page — each\n * after its parent, so every ancestor chain the check walks is whole — with\n * its settings and its styles, up to the whole-document cap.\n *\n * In the editor, an outline is the neighborhood of what the author selected.\n * A job has no selection and nobody to ask, so it is the WHOLE document: a\n * request about a picture five levels down is about an element the model can\n * see, and a restyle starts from the styles the element has. Each element\n * keeps its real child count and the document its real size, so the prompt\n * can say what a document past the cap leaves out. `null` without a root.\n */\nexport function aiEditJobOutline(nodes: Readonly<Record<string, unknown>>): {\n selectedId: null\n total: number\n nodes: Array<Record<string, unknown>>\n} | null {\n const root = nodes[CANVAS_ROOT_ELEMENT_ID]\n if (!isRecord(root)) return null\n const childrenOf = (node: Record<string, unknown>): string[] =>\n Array.isArray(node['nodes']) ? node['nodes'].filter((id): id is string => typeof id === 'string' && isRecord(nodes[id])) : []\n const order: Array<{ id: string; parentId: string | null; index: number }> = []\n const seen = new Set<string>([CANVAS_ROOT_ELEMENT_ID])\n // Depth first, children in their stored order: the page as it reads.\n const stack: Array<{ id: string; parentId: string | null; index: number }> = [\n { id: CANVAS_ROOT_ELEMENT_ID, parentId: null, index: 0 },\n ]\n while (stack.length) {\n const at = stack.pop() as (typeof stack)[number]\n order.push(at)\n const children = childrenOf(nodes[at.id] as Record<string, unknown>)\n for (let index = children.length - 1; index >= 0; index -= 1) {\n const child = children[index]\n if (seen.has(child)) continue\n seen.add(child)\n stack.push({ id: child, parentId: at.id, index })\n }\n }\n return {\n selectedId: null,\n total: order.length,\n nodes: order.slice(0, ASSIST_EDIT_WHOLE_MAX_NODES).map(({ id, parentId, index }) => {\n const node = nodes[id] as Record<string, unknown>\n return {\n id,\n componentId: node['componentId'],\n parentId,\n index,\n childCount: childrenOf(node).length,\n ...(typeof node['name'] === 'string' && node['name'] ? { name: node['name'] } : {}),\n ...(isRecord(node['props']) ? { props: node['props'] } : {}),\n ...(isRecord(node['sx']) ? { sx: node['sx'] } : {}),\n }\n }),\n }\n}\n"],"names":["CANVAS_ROOT_ELEMENT_ID","ASSIST_EDIT_WHOLE_MAX_NODES","AI_EDIT_TARGET_KINDS","DOCUMENT_ID","AI_EDIT_TARGET_REQUIRED_COPY","AI_EDIT_TARGET_KIND_COPY","AI_EDIT_VERSION_ID_COPY","parseAiEditJobInputs","inputs","target","test","kind","includes","versionId","targetKind","newVersion","AI_EDIT_NO_SITE_COPY","AI_EDIT_GONE_COPY","AI_EDIT_VERSION_GONE_COPY","AI_EDIT_EMAIL_COPY","AI_EDIT_NO_NODES_COPY","AI_EDIT_NEEDS_VERSIONING_COPY","AI_EDIT_NOTHING_COPY","AI_EDIT_STALE_COPY","AI_EDIT_REFUSED_COPY","AI_EDIT_VERSION_PREFIX","AI_EDIT_VERSION_NAME_MAX_CHARS","aiEditVersionName","summary","said","String","replace","trim","slice","NOUNS","screen","layout","AI_EDIT_NO_VERSIONS_DRAFT_COPY","aiEditOutputNote","input","noun","where","placement","versions","versionsUnavailable","leftOut","length","join","AI_EDIT_SEO_LEFT_OUT","AI_EDIT_COMPONENT_LEFT_OUT","isRecord","value","Array","isArray","aiEditJobOutline","nodes","root","childrenOf","node","filter","id","order","seen","Set","stack","parentId","index","at","pop","push","children","child","has","add","selectedId","total","map","componentId","childCount","name","props","sx"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,2CAA0C;AACjF,SAASC,2BAA2B,QAAQ,mBAAe;AAE3D;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED,sFAAsF,GACtF,OAAO,MAAMC,uBAAuB;IAAC;IAAU;CAAS,CAAS;AAcjE,MAAMC,cAAc;AAEpB,OAAO,MAAMC,+BAA+B,qCAAoC;AAChF,OAAO,MAAMC,2BAA2B,6CAA4C;AACpF,OAAO,MAAMC,0BAA0B,6DAA4D;AAEnG,4EAA4E,GAC5E,OAAO,SAASC,qBACdC,MAA4D;IAE5D,MAAMC,SAASD,0BAAAA,MAAQ,CAAC,SAAS;IACjC,IAAI,OAAOC,WAAW,YAAY,CAACN,YAAYO,IAAI,CAACD,SAAS,OAAOL;IACpE,MAAMO,OAAOH,0BAAAA,MAAQ,CAAC,aAAa;IACnC,IAAIG,QAAQ,QAAQA,SAAS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["../../../../../../../libs/plugins/ai/src/lib/model/ai-edit-job.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 { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport { ASSIST_EDIT_WHOLE_MAX_NODES } from './assist-edit'\n\n/**\n * An `edit` job (AGL-3616): a change to a page or a layout the site already\n * has, asked for in words, made without the Besigner open.\n *\n * It speaks the Assist edit rung's own protocol — the same tool, the same\n * closed world of element ids, the same validators, the same canvas mutators\n * — against the stored document instead of an open canvas, and the change is\n * saved where no visitor sees it:\n *\n * - by default, on every plan, into the WORKING DRAFT of the version it\n * started from (AGL-4116) — the draft the Besigner saves to as an author\n * works and offers with Open draft, so the author reviews the change and\n * publishes it there exactly as they would their own. A draft the author\n * already has is built on, never replaced;\n * - when the request asks for a new version and the plan keeps version\n * history, as a NEW version beside the one it started from, which becomes\n * the page's current version only when the page is not published; a\n * published page's and a layout's current version never move. Asked for\n * on a plan without version history, the change goes into the draft and\n * the output says why.\n *\n * Pure: the inputs, the sentences a person reads, and the outline the model\n * is shown. The runner is `jobs/ai-job-edit-step.ts`.\n */\n\n/** The documents an edit job changes: those that keep versions and render on a site. */\nexport const AI_EDIT_TARGET_KINDS = ['screen', 'layout'] as const\nexport type AiEditTargetKind = (typeof AI_EDIT_TARGET_KINDS)[number]\n\nexport interface AiEditJobInputs {\n /** The page's or layout's document id, on the job's site. */\n target: string\n /** Which collection the id is in; both are looked in, a page's first, when absent. */\n targetKind: AiEditTargetKind | null\n /** The version to start from; the document's current version when absent. */\n versionId: string | null\n /** The request asked for a new version; otherwise the change goes into the draft. */\n newVersion: boolean\n}\n\nconst DOCUMENT_ID = /^[A-Za-z0-9_-]{1,64}$/\n\nexport const AI_EDIT_TARGET_REQUIRED_COPY = 'Name the page or layout to change.'\nexport const AI_EDIT_TARGET_KIND_COPY = 'inputs.targetKind must be screen or layout'\nexport const AI_EDIT_VERSION_ID_COPY = 'inputs.versionId must name a version of the page or layout'\n\n/** A job's inputs read, or the sentence that says what is wrong with them. */\nexport function parseAiEditJobInputs(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n): AiEditJobInputs | string {\n const target = inputs?.['target']\n if (typeof target !== 'string' || !DOCUMENT_ID.test(target)) return AI_EDIT_TARGET_REQUIRED_COPY\n const kind = inputs?.['targetKind']\n if (kind != null && kind !== '' && !(AI_EDIT_TARGET_KINDS as readonly unknown[]).includes(kind)) {\n return AI_EDIT_TARGET_KIND_COPY\n }\n const versionId = inputs?.['versionId']\n if (versionId != null && versionId !== '' && (typeof versionId !== 'string' || !DOCUMENT_ID.test(versionId))) {\n return AI_EDIT_VERSION_ID_COPY\n }\n return {\n target,\n targetKind: kind ? (kind as AiEditTargetKind) : null,\n versionId: typeof versionId === 'string' && versionId ? versionId : null,\n newVersion: inputs?.['newVersion'] === true,\n }\n}\n\n// ── What a person reads ───────────────────────────────────────────────────\n\nexport const AI_EDIT_NO_SITE_COPY = 'Open the site the change is for before starting the job'\nexport const AI_EDIT_GONE_COPY = 'The page or layout to change is not on the site.'\nexport const AI_EDIT_VERSION_GONE_COPY = 'The version to start from is no longer on the page or layout.'\nexport const AI_EDIT_EMAIL_COPY = 'That is an email design, not a page — change it from Emails → Templates.'\nexport const AI_EDIT_NO_NODES_COPY = 'That version has nothing on it to change.'\n\n/**\n * A change that would land on a version visitors see, on a plan without\n * version history: the versions route's own sentence, after what it means\n * here.\n */\nexport const AI_EDIT_NEEDS_VERSIONING_COPY =\n 'Visitors see that version, so the change has to go into a new version beside it. Version history requires a Pro plan — see Billing to upgrade.'\n\n/** The model answered and no change survived its checks, even after its re-ask. */\nexport const AI_EDIT_NOTHING_COPY =\n 'No change could be made from that request. Say which part of the page to change, the way it reads on the page, and ask again.'\n\n/** The stored document moved under the change between the read and the write. */\nexport const AI_EDIT_STALE_COPY =\n 'The page changed while this edit was being written, so nothing was saved. Ask again.'\n\n/** The canvas's own guards refused part of the change. */\nexport const AI_EDIT_REFUSED_COPY = 'The editor refused part of this change, so none of it was saved.'\n\n/** The change would make the document larger than a save can store (AGL-4235). */\nexport const AI_EDIT_TOO_LARGE_COPY = 'With this change the page would be too large to save, so none of it was saved.'\n\n/** What a version an edit job makes is called, from the change's one-line summary. */\nexport const AI_EDIT_VERSION_PREFIX = 'AI edit'\n\n/** The longest label a version takes, as the versions route cuts one. */\nexport const AI_EDIT_VERSION_NAME_MAX_CHARS = 200\n\nexport function aiEditVersionName(summary: string): string {\n const said = String(summary ?? '').replace(/\\s+/g, ' ').trim()\n return (said ? `${AI_EDIT_VERSION_PREFIX}: ${said}` : AI_EDIT_VERSION_PREFIX).slice(0, AI_EDIT_VERSION_NAME_MAX_CHARS)\n}\n\n/** Where the change landed, which decides what the output's note says. */\nexport type AiEditPlacement =\n /** A new version, now the unpublished page's current one. */\n | 'new-current'\n /** A new version beside the one it started from, which is unchanged. */\n | 'new-beside'\n /** The version it started from, changed in place: one no visitor reaches. Written before AGL-4116. */\n | 'in-place'\n /** The working draft of the version it started from, which the Besigner offers with Open draft. */\n | 'draft'\n\nconst NOUNS: Readonly<Record<AiEditTargetKind, string>> = { screen: 'page', layout: 'layout' }\n\n/**\n * Why a change asked for as a new version went into the draft: the plan\n * keeps no version history. The versions route's own words for the plan.\n */\nexport const AI_EDIT_NO_VERSIONS_DRAFT_COPY =\n 'A new version needs version history, which requires a Pro plan, so the change went into the draft instead.'\n\n/** The output's note: where the change is, that nothing visitors see moved, and what was left out. */\nexport function aiEditOutputNote(input: {\n kind: AiEditTargetKind\n placement: AiEditPlacement\n leftOut: readonly string[]\n /** A new version was asked for on a plan without version history. */\n versionsUnavailable?: boolean\n}): string {\n const noun = NOUNS[input.kind]\n const where =\n input.placement === 'draft'\n ? `Saved as this ${noun}’s draft. Nothing visitors see has changed: open it in the Besigner to review it, then publish it when it is ready.`\n : input.placement === 'new-current'\n ? `Saved as a new version, now this ${noun}’s current one. The ${noun} is not published, so no visitor sees it until you publish it.`\n : input.placement === 'new-beside'\n ? `Saved as a new version beside the one it started from. Nothing visitors see has changed: open it to review it, and publish it when it is ready.`\n : `Saved on the version it started from, which no visitor sees: open it to review it.`\n const versions = input.versionsUnavailable ? ` ${AI_EDIT_NO_VERSIONS_DRAFT_COPY}` : ''\n const leftOut = input.leftOut.length ? ` Left out: ${input.leftOut.join('; ')}.` : ''\n return `${where}${versions}${leftOut}`.slice(0, 1_000)\n}\n\n/** What the output says of search fields a published page keeps on the page itself. */\nexport const AI_EDIT_SEO_LEFT_OUT =\n 'the search title and description, which a published page uses as soon as they are saved — change them in Page properties'\n\n/** What the output says of a part a job cannot save on its own. */\nexport const AI_EDIT_COMPONENT_LEFT_OUT = 'saving part of the page as a reusable component, which is done in the editor'\n\n// ── The outline the model is shown ────────────────────────────────────────\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** One element of a stored document, in the order the document reads. */\nexport interface AiDocumentElement {\n id: string\n /** The element it sits in, or null for the document root. */\n parentId: string | null\n /** Its position among its parent's children. */\n index: number\n /** The elements placed inside it by this walk, in their stored order. */\n children: string[]\n /** How many children the element lists that are on the document, whatever the walk placed. */\n childCount: number\n /** The stored node, as it is. */\n node: Record<string, unknown>\n}\n\n/**\n * Every element of a stored document (AGL-4235), complete: the document root,\n * then each element after its parent, depth first, children in their stored\n * order — the page as it reads. An element listed under two parents is placed\n * once, under the first the walk reaches; a child id with no node is skipped.\n * Nothing is capped or shortened: this is the one walker, and a reader with a\n * budget caps what it returns. `null` without a root.\n */\nexport function aiDocumentElements(nodes: Readonly<Record<string, unknown>>): AiDocumentElement[] | null {\n const root = nodes[CANVAS_ROOT_ELEMENT_ID]\n if (!isRecord(root)) return null\n const childrenOf = (node: Record<string, unknown>): string[] =>\n Array.isArray(node['nodes']) ? node['nodes'].filter((id): id is string => typeof id === 'string' && isRecord(nodes[id])) : []\n const order: AiDocumentElement[] = []\n const byId = new Map<string, AiDocumentElement>()\n const seen = new Set<string>([CANVAS_ROOT_ELEMENT_ID])\n // Depth first, children in their stored order: the page as it reads.\n const stack: Array<{ id: string; parentId: string | null; index: number }> = [\n { id: CANVAS_ROOT_ELEMENT_ID, parentId: null, index: 0 },\n ]\n while (stack.length) {\n const at = stack.pop() as (typeof stack)[number]\n const node = nodes[at.id] as Record<string, unknown>\n const listed = childrenOf(node)\n const element: AiDocumentElement = { ...at, children: [], childCount: listed.length, node }\n order.push(element)\n byId.set(at.id, element)\n if (at.parentId !== null) byId.get(at.parentId)?.children.push(at.id)\n for (let index = listed.length - 1; index >= 0; index -= 1) {\n const child = listed[index]\n if (seen.has(child)) continue\n seen.add(child)\n stack.push({ id: child, parentId: at.id, index })\n }\n }\n return order\n}\n\n/**\n * The stored document as the outline the edit rung's protocol reads\n * (`parseAssistEditContext` with `whole` holds it to its limits): the\n * document root, then every element in the order it reads on the page — each\n * after its parent, so every ancestor chain the check walks is whole — with\n * its settings and its styles, up to the whole-document cap.\n *\n * In the editor, an outline is the neighborhood of what the author selected.\n * A job has no selection and nobody to ask, so it is the WHOLE document: a\n * request about a picture five levels down is about an element the model can\n * see, and a restyle starts from the styles the element has. Each element\n * keeps its real child count and the document its real size, so the prompt\n * can say what a document past the cap leaves out. `null` without a root.\n *\n * The walk is {@link aiDocumentElements}'s; this applies the outline's cap.\n */\nexport function aiEditJobOutline(nodes: Readonly<Record<string, unknown>>): {\n selectedId: null\n total: number\n nodes: Array<Record<string, unknown>>\n} | null {\n const order = aiDocumentElements(nodes)\n if (!order) return null\n return {\n selectedId: null,\n total: order.length,\n nodes: order.slice(0, ASSIST_EDIT_WHOLE_MAX_NODES).map(({ id, parentId, index, childCount, node }) => ({\n id,\n componentId: node['componentId'],\n parentId,\n index,\n childCount,\n ...(typeof node['name'] === 'string' && node['name'] ? { name: node['name'] } : {}),\n ...(isRecord(node['props']) ? { props: node['props'] } : {}),\n ...(isRecord(node['sx']) ? { sx: node['sx'] } : {}),\n })),\n }\n}\n"],"names":["CANVAS_ROOT_ELEMENT_ID","ASSIST_EDIT_WHOLE_MAX_NODES","AI_EDIT_TARGET_KINDS","DOCUMENT_ID","AI_EDIT_TARGET_REQUIRED_COPY","AI_EDIT_TARGET_KIND_COPY","AI_EDIT_VERSION_ID_COPY","parseAiEditJobInputs","inputs","target","test","kind","includes","versionId","targetKind","newVersion","AI_EDIT_NO_SITE_COPY","AI_EDIT_GONE_COPY","AI_EDIT_VERSION_GONE_COPY","AI_EDIT_EMAIL_COPY","AI_EDIT_NO_NODES_COPY","AI_EDIT_NEEDS_VERSIONING_COPY","AI_EDIT_NOTHING_COPY","AI_EDIT_STALE_COPY","AI_EDIT_REFUSED_COPY","AI_EDIT_TOO_LARGE_COPY","AI_EDIT_VERSION_PREFIX","AI_EDIT_VERSION_NAME_MAX_CHARS","aiEditVersionName","summary","said","String","replace","trim","slice","NOUNS","screen","layout","AI_EDIT_NO_VERSIONS_DRAFT_COPY","aiEditOutputNote","input","noun","where","placement","versions","versionsUnavailable","leftOut","length","join","AI_EDIT_SEO_LEFT_OUT","AI_EDIT_COMPONENT_LEFT_OUT","isRecord","value","Array","isArray","aiDocumentElements","nodes","root","childrenOf","node","filter","id","order","byId","Map","seen","Set","stack","parentId","index","at","pop","listed","element","children","childCount","push","set","get","child","has","add","aiEditJobOutline","selectedId","total","map","componentId","name","props","sx"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,2CAA0C;AACjF,SAASC,2BAA2B,QAAQ,mBAAe;AAE3D;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED,sFAAsF,GACtF,OAA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AAKgB,GAAG,CAACF;YACTZ,MAAMS,IAAI,CAAC;gBAAEf,IAAIkB;gBAAOX,UAAUE,GAAGT,EAAE;gBAAEQ;YAAM;QACjD;IACF;IACA,OAAOP;AACT;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASoB,iBAAiB1B,KAAwC;IAKvE,MAAMM,QAAQP,mBAAmBC;IACjC,IAAI,CAACM,OAAO,OAAO;IACnB,OAAO;QACLqB,YAAY;QACZC,OAAOtB,MAAMf,MAAM;QACnBS,OAAOM,MAAM5B,KAAK,CAAC,GAAGjC,6BAA6BoF,GAAG,CAAC,CAAC,EAAExB,EAAE,EAAEO,QAAQ,EAAEC,KAAK,EAAEM,UAAU,EAAEhB,IAAI,EAAE,GAAM;gBACrGE;gBACAyB,aAAa3B,IAAI,CAAC,cAAc;gBAChCS;gBACAC;gBACAM;eACI,OAAOhB,IAAI,CAAC,OAAO,KAAK,YAAYA,IAAI,CAAC,OAAO,GAAG;gBAAE4B,MAAM5B,IAAI,CAAC,OAAO;YAAC,IAAI,CAAC,GAC7ER,SAASQ,IAAI,CAAC,QAAQ,IAAI;gBAAE6B,OAAO7B,IAAI,CAAC,QAAQ;YAAC,IAAI,CAAC,GACtDR,SAASQ,IAAI,CAAC,KAAK,IAAI;gBAAE8B,IAAI9B,IAAI,CAAC,KAAK;YAAC,IAAI,CAAC;IAErD;AACF"}
|
|
@@ -160,6 +160,8 @@ export interface AssistEditNode {
|
|
|
160
160
|
props: Record<string, unknown>;
|
|
161
161
|
sx?: Record<string, unknown>;
|
|
162
162
|
hidden?: boolean;
|
|
163
|
+
/** The layer name, when the request gave the new element one (AGL-4235). */
|
|
164
|
+
name?: string;
|
|
163
165
|
}
|
|
164
166
|
/**
|
|
165
167
|
* Every op that acts on an element names the component the server validated
|