@aglyn/plugins-workflows 1.18.0 → 1.19.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 +12 -12
- package/src/lib/components/org-automation-editor.component.d.ts +29 -6
- package/src/lib/components/org-automation-editor.component.js +105 -87
- package/src/lib/components/org-automation-editor.component.js.map +1 -1
- package/src/lib/components/org-automations-card.component.js +24 -4
- package/src/lib/components/org-automations-card.component.js.map +1 -1
- package/src/lib/components/use-org-automation-step-pickers.d.ts +6 -3
- package/src/lib/components/use-org-automation-step-pickers.js +7 -6
- package/src/lib/components/use-org-automation-step-pickers.js.map +1 -1
- package/src/lib/model/org-automations.d.ts +36 -5
- package/src/lib/model/org-automations.js +94 -7
- package/src/lib/model/org-automations.js.map +1 -1
- package/src/lib/server/org-automations-routes.d.ts +0 -6
- package/src/lib/server/org-automations-routes.js +116 -10
- package/src/lib/server/org-automations-routes.js.map +1 -1
- package/src/lib/transfer/org-automations-package.js +41 -8
- package/src/lib/transfer/org-automations-package.js.map +1 -1
- package/src/lib/transfer/org-automations-package.server.js +17 -3
- package/src/lib/transfer/org-automations-package.server.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/model/org-automations.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 {\n normalizeVisibleTo,\n type ScopeToken,\n visibleToHost,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\nimport type { HostEventType } from '@aglyn/aglyn/app-utils/host-events'\nimport {\n ACTION_MAX_CONDITIONS,\n ACTION_MAX_STEPS,\n TRIGGER_COMBINATORS,\n TRIGGER_CONDITION_OPS,\n type TriggerCombinator,\n} from '@aglyn/aglyn/app-utils/site-interactions'\nimport {\n HOST_ACTION_STEP_LABELS,\n type HostActionStep,\n type HostActionStepType,\n type HostActionTriggerCondition,\n validateHostAction,\n} from './host-actions'\n\n/**\n * ORG AUTOMATIONS (AGL-3302): one automation the organization writes once and\n * places on the sites it chooses.\n *\n * A site's own actions stay where they are, at `hosts/{hostId}/actions`. They\n * are not moved here, and the reasons are the four things a site action can\n * do that an org automation must not:\n *\n * - call the site's functions and variables through a workflow step — the\n * working set a computed variable binds to, which is one site's;\n * - run the steps only a visitor's page can run (overlays, drawers, class\n * toggles, a redirect to a screen), which the `actions` collection also\n * holds for element interactions;\n * - be fired by `/api/events/dispatch`, which is unauthenticated and ties an\n * action id to a site only by its path;\n * - wait, with the resume beat reading a missing document as the kill\n * switch, so a migration would stop every person already inside a flow.\n *\n * An org automation is therefore its own document with a narrower\n * vocabulary: triggers only the server raises, and steps that mean the same\n * thing on whichever site they run. Each run executes AS the site the event\n * happened on — that site's sender, suppressions, consent group, meters and\n * run allowance — so placing one automation on five sites is five sites each\n * running it for themselves, never one site acting for the others.\n *\n * Pure and client-safe: the console's editor, the server routes and the\n * engine read the same definitions from here.\n */\n\n/** `orgs/{orgId}/automations/{automationId}`. */\nexport const ORG_AUTOMATIONS_COLLECTION = 'automations'\n\n/**\n * The two server doors onto the collection, under the plugin's `automations`\n * API prefix: the organization's (`manage`) and a site's own pause\n * (`pause`). Named here so the console's caller and the server's registration\n * read one spelling.\n */\nexport const ORG_AUTOMATION_API_ROUTES = {\n manage: 'automations/manage',\n pause: 'automations/pause',\n} as const\n\n/**\n * How many live org automations one organization may hold.\n *\n * A flat platform cap in the shape `ACTIONS_MAX_PER_HOST` takes, and smaller,\n * because the two are different things: a site action is authored per site\n * and per element, where an org automation is a shared building block placed\n * on many sites at once. A hundred is far past what an organization writes by\n * hand and keeps the org hub's list — which reads every live one — a single\n * bounded window. Soft-deleted documents do not count.\n */\nexport const ORG_AUTOMATIONS_MAX = 100\n\n/**\n * How many org automations one event may run on one site: every one the\n * organization may hold (AGL-3458). The query asks for switched-on ones only\n * — a deletion switches an automation off — so nothing that cannot run takes\n * a place, and a site's own actions are read by a query of their own, so the\n * two cannot crowd each other out.\n */\nexport const MAX_TRIGGERED_ORG_AUTOMATIONS = ORG_AUTOMATIONS_MAX\n\n/**\n * The run history's target type for a run of an org automation, on the\n * activity feed of the site it ran on.\n */\nexport const ORG_AUTOMATION_RUN_TARGET = 'orgAutomation'\n\n/**\n * The org activity target an org automation's own lifecycle rows are filed\n * under: the plugin's namespaced resource (`pluginId:noun`), which the org's\n * feed reads as \"Automation\" — core's target list names only core's resources.\n */\nexport const ORG_AUTOMATION_ACTIVITY_TARGET = 'workflows:automation'\n\n/**\n * The events an org automation may start on: every host event the SERVER\n * raises and a person can be the subject of.\n *\n * Listed rather than derived from `HOST_EVENT_TYPES`, deliberately. The engine\n * queries the organization's automations on every event in this list, so a\n * new host event must not become an org trigger — and a new read on every\n * occurrence of it — by being added to the platform's list. Two are left out\n * on purpose: `pageView` fires on every request to every published page, and\n * an org query on it would be a read per visitor; `memberSignOut` is raised\n * by no door today.\n */\nexport const ORG_AUTOMATION_TRIGGER_EVENTS = [\n 'formSubmission',\n 'lead',\n 'contactCreated',\n 'contactStageChanged',\n 'booking',\n 'memberSignUp',\n 'memberSignIn',\n 'dealStageChanged',\n 'dealWon',\n 'dealLost',\n 'taskCompleted',\n] as const satisfies readonly HostEventType[]\n\nexport type OrgAutomationTriggerEvent =\n (typeof ORG_AUTOMATION_TRIGGER_EVENTS)[number]\n\nconst ORG_TRIGGER_SET: ReadonlySet<string> = new Set(\n ORG_AUTOMATION_TRIGGER_EVENTS,\n)\n\n/** Whether an org automation may start on this event. */\nexport function isOrgAutomationTriggerEvent(\n event: unknown,\n): event is OrgAutomationTriggerEvent {\n return typeof event === 'string' && ORG_TRIGGER_SET.has(event)\n}\n\n/**\n * The steps an org automation may hold: the server steps that read the same\n * on every site.\n *\n * What is left out, and why:\n * - every step the visitor's page runs — overlays, drawers, menus, class\n * toggles, custom HTML and JavaScript, analytics, redirects, the site\n * alert — because an org trigger is a server event with no page to act on;\n * - `runWorkflow`, because a workflow is one site's and calls that site's\n * functions and variables;\n * - `webhookPost`, because a webhook's address and secret are one site's.\n *\n * `customEvent` stays: it fires a custom event ON the site the run is on,\n * which that site's own actions may listen for — the documented way for an\n * org automation to hand over to something site-specific.\n */\nexport const ORG_AUTOMATION_STEP_TYPES = [\n 'sendEmail',\n 'notifyAdmins',\n 'enrollList',\n 'assignCampaign',\n 'datasetAppend',\n 'updateDataset',\n 'setContactStage',\n 'addContactTag',\n 'assignContactOwner',\n 'createCrmTask',\n 'logCrmActivity',\n 'customEvent',\n 'wait',\n 'waitForEvent',\n 'exitFlow',\n] as const satisfies readonly HostActionStepType[]\n\nexport type OrgAutomationStepType = (typeof ORG_AUTOMATION_STEP_TYPES)[number]\n\nconst ORG_STEP_SET: ReadonlySet<string> = new Set(ORG_AUTOMATION_STEP_TYPES)\n\n/** Whether an org automation may run a step of this type. */\nexport function isOrgAutomationStepType(\n type: unknown,\n): type is OrgAutomationStepType {\n return typeof type === 'string' && ORG_STEP_SET.has(type)\n}\n\n/** The org editor's \"Do\" picker: each allowed step with its label, in order. */\nexport const ORG_AUTOMATION_STEP_KINDS: ReadonlyArray<{\n value: OrgAutomationStepType\n label: string\n}> = ORG_AUTOMATION_STEP_TYPES.map((value) => ({\n value,\n label: HOST_ACTION_STEP_LABELS[value],\n}))\n\n/**\n * Why an org automation cannot hold this step, or null when it can.\n *\n * Shared by the save route, which refuses it, and by the engine, which\n * refuses to run one a writer stored anyway.\n */\nexport function orgAutomationStepRefusal(step: {\n type?: unknown\n}): string | null {\n if (isOrgAutomationStepType(step?.type)) return null\n const label = HOST_ACTION_STEP_LABELS[step?.type as HostActionStepType]\n if (!label) return `“${String(step?.type ?? '')}” is not a step`\n return (\n `“${label}” belongs to one site, so an org automation cannot run it — ` +\n 'build it as an action on that site'\n )\n}\n\n/** The trigger an org automation starts on, as it is stored. */\nexport interface OrgAutomationTrigger {\n event: OrgAutomationTriggerEvent\n /** Optional expression over the payload; runs only when truthy. */\n filter?: string\n conditions: HostActionTriggerCondition[] | null\n combinator: TriggerCombinator | null\n}\n\n/**\n * The fields an org automation is written with — by the save route, and by\n * nothing else: the collection is closed to client writes.\n */\nexport interface OrgAutomationFields {\n name: string\n trigger: OrgAutomationTrigger\n steps: HostActionStep[]\n enabled: boolean\n /**\n * The sites it runs on, as scope tokens: `['org']` is every site of the\n * organization, now and later; `['host:{id}', …]` names up to thirty.\n */\n visibleTo: ScopeToken[]\n}\n\n/** `orgs/{orgId}/automations/{id}`, as it is stored. */\nexport interface OrgAutomation extends OrgAutomationFields {\n /**\n * The sites that have paused it for themselves — each a site id, never a\n * scope token. The \"host level control\": a site's admin or editor adds or\n * removes their own site here, and only their own.\n */\n pausedHostIds: string[]\n createdBy?: string\n updatedBy?: string\n /**\n * Set when it was deleted. Always written — `null` while live — so the\n * org hub's list can ask for the live ones by equality.\n */\n deletedAt: unknown\n}\n\n/** A stored org automation with its id, as the console lists it. */\nexport type OrgAutomationRow = OrgAutomation & { $id: string }\n\n/** Longest name an org automation may carry: the actions editor's cap. */\nexport const ORG_AUTOMATION_NAME_MAX = 60\n\n/** Longest trigger filter expression. */\nconst FILTER_MAX = 500\n\n/** Longest a condition's field or value may be. */\nconst CONDITION_FIELD_MAX = 64\nconst CONDITION_VALUE_MAX = 200\n\n/**\n * Every field a step of each type may carry beyond `type` and `when`, with\n * the longest a string in it may be. What the save route stores is exactly\n * this: a key a step's type does not list is dropped, so the document holds\n * the vocabulary and nothing a caller made up.\n *\n * The caps follow what the engine reads — it cuts a subject at 200 and a body\n * at 5,000 before sending — so nothing is stored that could not be run.\n */\nconst STEP_FIELDS: Record<\n OrgAutomationStepType,\n Readonly<Record<string, 'string' | 'number' | 'boolean' | number>>\n> = {\n sendEmail: { subject: 200, body: 5000, toField: 64, topicId: 128, transactional: 'boolean' },\n notifyAdmins: { title: 200, body: 500 },\n enrollList: { listId: 128, listName: 200 },\n assignCampaign: { campaignId: 128, campaignName: 200 },\n datasetAppend: { datasetId: 128, datasetName: 200 },\n updateDataset: { datasetId: 128, datasetName: 200 },\n setContactStage: { lifecycleStage: 64 },\n addContactTag: { tag: 200 },\n assignContactOwner: {\n ownerUid: 128,\n ownerEmail: 320,\n roundRobin: 'boolean',\n },\n createCrmTask: {\n title: 200,\n kind: 64,\n priority: 16,\n dueInDays: 'number',\n assigneeUid: 128,\n assigneeEmail: 320,\n },\n logCrmActivity: { kind: 64, body: 2000, direction: 16 },\n customEvent: { eventName: 64 },\n wait: { delayMinutes: 'number' },\n waitForEvent: { eventName: 64, timeoutMinutes: 'number' },\n exitFlow: {},\n}\n\nconst asObject = (value: unknown): Record<string, unknown> | null =>\n value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n\n/** A condition as it is stored, or null for a row that is not one. */\nfunction readCondition(raw: unknown): HostActionTriggerCondition | null {\n const row = asObject(raw)\n if (!row) return null\n const op = row['op']\n if (!(TRIGGER_CONDITION_OPS as readonly unknown[]).includes(op)) {\n // Kept as written so the validator names the missing operator rather\n // than the row silently vanishing.\n return {\n field: String(row['field'] ?? '').trim().slice(0, CONDITION_FIELD_MAX),\n op: op as never,\n }\n }\n return {\n field: String(row['field'] ?? '').trim().slice(0, CONDITION_FIELD_MAX),\n op: op as HostActionTriggerCondition['op'],\n ...(op !== 'notEmpty'\n ? { value: String(row['value'] ?? '').trim().slice(0, CONDITION_VALUE_MAX) }\n : {}),\n }\n}\n\nfunction readConditions(raw: unknown): HostActionTriggerCondition[] {\n return (Array.isArray(raw) ? raw : [])\n .slice(0, ACTION_MAX_CONDITIONS + 1)\n .map(readCondition)\n .filter((row): row is HostActionTriggerCondition => row !== null)\n}\n\nfunction readCombinator(raw: unknown): TriggerCombinator | null {\n return (TRIGGER_COMBINATORS as readonly unknown[]).includes(raw)\n ? (raw as TriggerCombinator)\n : null\n}\n\n/** One step as it would be stored: its own fields only, strings capped. */\nfunction readStep(raw: unknown): HostActionStep | { type: unknown } {\n const source = asObject(raw) ?? {}\n const type = source['type']\n if (!isOrgAutomationStepType(type)) return { type }\n const step: Record<string, unknown> = { type }\n for (const [key, kind] of Object.entries(STEP_FIELDS[type])) {\n const value = source[key]\n if (value === undefined || value === null) continue\n if (kind === 'boolean') {\n if (typeof value === 'boolean') step[key] = value\n } else if (kind === 'number') {\n if (typeof value === 'number' && Number.isFinite(value)) step[key] = value\n } else if (typeof value === 'string') {\n step[key] = value.slice(0, Number(kind))\n }\n }\n const when = asObject(source['when'])\n if (when) {\n const conditions = readConditions(when['conditions'])\n if (conditions.length) {\n step['when'] = {\n conditions,\n combinator: readCombinator(when['combinator']) ?? 'and',\n }\n }\n }\n return step as HostActionStep\n}\n\n/** What a caller sends to create or replace an org automation. */\nexport type OrgAutomationInput = Record<string, unknown>\n\n/**\n * Reads an org automation out of an untrusted request body: the fields it may\n * hold, in the shape they are stored, or the first reason it cannot be saved.\n *\n * The rules are the actions builder's own — `validateHostAction` checks the\n * name, the trigger's conditions and every step's fields — and on top of them\n * the two this vocabulary adds: the trigger must be an org trigger and every\n * step an org step. The placement must be a scope a save can store:\n * `normalizeVisibleTo` refuses an empty one and one over thirty sites rather\n * than guessing between sharing wider and taking access away.\n *\n * Whether each named site belongs to the organization is the route's to ask,\n * because it takes a read.\n */\nexport function readOrgAutomation(\n input: unknown,\n): { ok: true; value: OrgAutomationFields } | { ok: false; problem: string } {\n const body = asObject(input) ?? {}\n const name = String(body['name'] ?? '')\n .trim()\n .slice(0, ORG_AUTOMATION_NAME_MAX)\n if (!name) return { ok: false, problem: 'Name the automation' }\n const trigger = asObject(body['trigger']) ?? {}\n const event = String(trigger['event'] ?? '').trim()\n if (!isOrgAutomationTriggerEvent(event)) {\n return {\n ok: false,\n problem:\n 'Pick a trigger an org automation can start on — a form, a lead, a ' +\n 'booking, a member or a CRM event',\n }\n }\n const filter = String(trigger['filter'] ?? '')\n .trim()\n .slice(0, FILTER_MAX)\n const conditions = readConditions(trigger['conditions'])\n const combinator = readCombinator(trigger['combinator'])\n const rawSteps = Array.isArray(body['steps']) ? body['steps'] : []\n if (rawSteps.length > ACTION_MAX_STEPS) {\n return {\n ok: false,\n problem: `Org automations are capped at ${ACTION_MAX_STEPS} steps`,\n }\n }\n const steps = rawSteps.map(readStep)\n for (const [index, step] of steps.entries()) {\n const refusal = orgAutomationStepRefusal(step)\n if (refusal) return { ok: false, problem: `Step ${index + 1}: ${refusal}` }\n }\n const problem = validateHostAction({\n name,\n trigger: {\n event,\n ...(filter ? { filter } : {}),\n ...(conditions.length ? { conditions } : {}),\n ...(combinator ? { combinator } : {}),\n },\n steps: steps as HostActionStep[],\n })\n if (problem) return { ok: false, problem }\n const visibleTo = normalizeVisibleTo(\n Array.isArray(body['visibleTo'])\n ? (body['visibleTo'] as unknown[]).filter(\n (token): token is string => typeof token === 'string',\n )\n : [],\n )\n if (!visibleTo) {\n return {\n ok: false,\n problem: 'Choose every site, or up to 30 sites, for it to run on',\n }\n }\n return {\n ok: true,\n value: {\n name,\n trigger: {\n event,\n ...(filter ? { filter } : {}),\n conditions: conditions.length ? conditions : null,\n combinator: conditions.length ? (combinator ?? 'and') : null,\n },\n steps: steps as HostActionStep[],\n enabled: body['enabled'] !== false,\n visibleTo,\n },\n }\n}\n\n/** A stored document's pause list, read defensively. */\nexport function orgAutomationPausedHostIds(\n automation: { pausedHostIds?: unknown } | null | undefined,\n): string[] {\n const paused = automation?.pausedHostIds\n return Array.isArray(paused)\n ? paused.filter((id): id is string => typeof id === 'string')\n : []\n}\n\n/**\n * Why a stored org automation will not run on this site, or null when it\n * will — the one answer the engine asks when an event arrives and again when\n * a person waiting inside the automation is due.\n *\n * Deleted, switched off, taken off the site and paused there are the four\n * ways an organization or a site says \"not here\", and every one of them\n * stops the people already waiting on this site as well as the next run: the\n * kill switch a site action's resume applies, for the same reason.\n */\nexport function orgAutomationStopReason(\n automation:\n | {\n deletedAt?: unknown\n enabled?: unknown\n visibleTo?: unknown\n pausedHostIds?: unknown\n }\n | null\n | undefined,\n hostId: string,\n): string | null {\n if (!automation || automation.deletedAt) {\n return 'the org automation was deleted'\n }\n if (automation.enabled === false) {\n return 'the org automation was switched off'\n }\n if (!visibleToHost(automation.visibleTo as string[] | undefined, hostId)) {\n return 'the org automation no longer runs on this site'\n }\n if (orgAutomationPausedHostIds(automation).includes(hostId)) {\n return 'the org automation is paused on this site'\n }\n return null\n}\n\n/** Whether a stored org automation runs on this site. */\nexport function orgAutomationRunsOnHost(\n automation: Parameters<typeof orgAutomationStopReason>[0],\n hostId: string,\n): boolean {\n return orgAutomationStopReason(automation, hostId) === null\n}\n\n/**\n * A pause list after the placement changed: a site the automation no longer\n * runs on has nothing left to pause, so its entry goes with it, and a site\n * placed on it again later starts unpaused.\n */\nexport function prunePausedHostIds(\n pausedHostIds: readonly string[],\n visibleTo: readonly string[],\n): string[] {\n return pausedHostIds.filter((hostId) => visibleToHost(visibleTo, hostId))\n}\n"],"names":["normalizeVisibleTo","visibleToHost","ACTION_MAX_CONDITIONS","ACTION_MAX_STEPS","TRIGGER_COMBINATORS","TRIGGER_CONDITION_OPS","HOST_ACTION_STEP_LABELS","validateHostAction","ORG_AUTOMATIONS_COLLECTION","ORG_AUTOMATION_API_ROUTES","manage","pause","ORG_AUTOMATIONS_MAX","MAX_TRIGGERED_ORG_AUTOMATIONS","ORG_AUTOMATION_RUN_TARGET","ORG_AUTOMATION_ACTIVITY_TARGET","ORG_AUTOMATION_TRIGGER_EVENTS","ORG_TRIGGER_SET","Set","isOrgAutomationTriggerEvent","event","has","ORG_AUTOMATION_STEP_TYPES","ORG_STEP_SET","isOrgAutomationStepType","type","ORG_AUTOMATION_STEP_KINDS","map","value","label","orgAutomationStepRefusal","step","String","ORG_AUTOMATION_NAME_MAX","FILTER_MAX","CONDITION_FIELD_MAX","CONDITION_VALUE_MAX","STEP_FIELDS","sendEmail","subject","body","toField","topicId","transactional","notifyAdmins","title","enrollList","listId","listName","assignCampaign","campaignId","campaignName","datasetAppend","datasetId","datasetName","updateDataset","setContactStage","lifecycleStage","addContactTag","tag","assignContactOwner","ownerUid","ownerEmail","roundRobin","createCrmTask","kind","priority","dueInDays","assigneeUid","assigneeEmail","logCrmActivity","direction","customEvent","eventName","wait","delayMinutes","waitForEvent","timeoutMinutes","exitFlow","asObject","Array","isArray","readCondition","raw","row","op","includes","field","trim","slice","readConditions","filter","readCombinator","readStep","source","key","Object","entries","undefined","Number","isFinite","when","conditions","length","combinator","readOrgAutomation","input","trigger","name","ok","problem","rawSteps","steps","index","refusal","visibleTo","token","enabled","orgAutomationPausedHostIds","automation","paused","pausedHostIds","id","orgAutomationStopReason","hostId","deletedAt","orgAutomationRunsOnHost","prunePausedHostIds"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAElBC,aAAa,QACR,sCAAqC;AAE5C,SACEC,qBAAqB,EACrBC,gBAAgB,EAChBC,mBAAmB,EACnBC,qBAAqB,QAEhB,2CAA0C;AACjD,SACEC,uBAAuB,EAIvBC,kBAAkB,QACb,oBAAgB;AAEvB;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GAED,+CAA+C,GAC/C,OAAO,MAAMC,6BAA6B,cAAa;AAEvD;;;;;CAKC,GACD,OAAO,MAAMC,4BAA4B;IACvCC,QAAQ;IACRC,OAAO;AACT,EAAU;AAEV;;;;;;;;;CASC,GACD,OAAO,MAAMC,sBAAsB,IAAG;AAEtC;;;;;;CAMC,GACD,OAAO,MAAMC,gCAAgCD,oBAAmB;AAEhE;;;CAGC,GACD,OAAO,MAAME,4BAA4B,gBAAe;AAExD;;;;CAIC,GACD,OAAO,MAAMC,iCAAiC,uBAAsB;AAEpE;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,gCAAgC;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AAMC,OAAO,CAACuC,UACjBA,OAAO7B,MAAM,CAAC,CAAC+B,KAAqB,OAAOA,OAAO,YAClD,EAAE;AACR;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASC,wBACdJ,UAQa,EACbK,MAAc;IAEd,IAAI,CAACL,cAAcA,WAAWM,SAAS,EAAE;QACvC,OAAO;IACT;IACA,IAAIN,WAAWF,OAAO,KAAK,OAAO;QAChC,OAAO;IACT;IACA,IAAI,CAACpH,cAAcsH,WAAWJ,SAAS,EAA0BS,SAAS;QACxE,OAAO;IACT;IACA,IAAIN,2BAA2BC,YAAYjC,QAAQ,CAACsC,SAAS;QAC3D,OAAO;IACT;IACA,OAAO;AACT;AAEA,uDAAuD,GACvD,OAAO,SAASE,wBACdP,UAAyD,EACzDK,MAAc;IAEd,OAAOD,wBAAwBJ,YAAYK,YAAY;AACzD;AAEA;;;;CAIC,GACD,OAAO,SAASG,mBACdN,aAAgC,EAChCN,SAA4B;IAE5B,OAAOM,cAAc9B,MAAM,CAAC,CAACiC,SAAW3H,cAAckH,WAAWS;AACnE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/model/org-automations.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 {\n hostScopeToken,\n normalizeVisibleTo,\n ORG_SCOPE_TOKEN,\n type SCOPE_MODE_ALL_EXCEPT,\n type ScopeSharingChoice,\n scopeSharingOf,\n type ScopeToken,\n visibleToHost,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\nimport type { HostEventType } from '@aglyn/aglyn/app-utils/host-events'\nimport {\n ACTION_MAX_CONDITIONS,\n ACTION_MAX_STEPS,\n TRIGGER_COMBINATORS,\n TRIGGER_CONDITION_OPS,\n type TriggerCombinator,\n} from '@aglyn/aglyn/app-utils/site-interactions'\nimport {\n HOST_ACTION_STEP_LABELS,\n type HostActionStep,\n type HostActionStepType,\n type HostActionTriggerCondition,\n validateHostAction,\n} from './host-actions'\n\n/**\n * ORG AUTOMATIONS (AGL-3302): one automation the organization writes once and\n * places on the sites it chooses.\n *\n * A site's own actions stay where they are, at `hosts/{hostId}/actions`. They\n * are not moved here, and the reasons are the four things a site action can\n * do that an org automation must not:\n *\n * - call the site's functions and variables through a workflow step — the\n * working set a computed variable binds to, which is one site's;\n * - run the steps only a visitor's page can run (overlays, drawers, class\n * toggles, a redirect to a screen), which the `actions` collection also\n * holds for element interactions;\n * - be fired by `/api/events/dispatch`, which is unauthenticated and ties an\n * action id to a site only by its path;\n * - wait, with the resume beat reading a missing document as the kill\n * switch, so a migration would stop every person already inside a flow.\n *\n * An org automation is therefore its own document with a narrower\n * vocabulary: triggers only the server raises, and steps that mean the same\n * thing on whichever site they run. Each run executes AS the site the event\n * happened on — that site's sender, suppressions, consent group, meters and\n * run allowance — so placing one automation on five sites is five sites each\n * running it for themselves, never one site acting for the others.\n *\n * Pure and client-safe: the console's editor, the server routes and the\n * engine read the same definitions from here.\n */\n\n/** `orgs/{orgId}/automations/{automationId}`. */\nexport const ORG_AUTOMATIONS_COLLECTION = 'automations'\n\n/**\n * The two server doors onto the collection, under the plugin's `automations`\n * API prefix: the organization's (`manage`) and a site's own pause\n * (`pause`). Named here so the console's caller and the server's registration\n * read one spelling.\n */\nexport const ORG_AUTOMATION_API_ROUTES = {\n manage: 'automations/manage',\n pause: 'automations/pause',\n} as const\n\n/**\n * How many live org automations one organization may hold.\n *\n * A flat platform cap in the shape `ACTIONS_MAX_PER_HOST` takes, and smaller,\n * because the two are different things: a site action is authored per site\n * and per element, where an org automation is a shared building block placed\n * on many sites at once. A hundred is far past what an organization writes by\n * hand and keeps the org hub's list — which reads every live one — a single\n * bounded window. Soft-deleted documents do not count.\n */\nexport const ORG_AUTOMATIONS_MAX = 100\n\n/**\n * How many org automations one event may run on one site: every one the\n * organization may hold (AGL-3458). The query asks for switched-on ones only\n * — a deletion switches an automation off — so nothing that cannot run takes\n * a place, and a site's own actions are read by a query of their own, so the\n * two cannot crowd each other out.\n */\nexport const MAX_TRIGGERED_ORG_AUTOMATIONS = ORG_AUTOMATIONS_MAX\n\n/**\n * The run history's target type for a run of an org automation, on the\n * activity feed of the site it ran on.\n */\nexport const ORG_AUTOMATION_RUN_TARGET = 'orgAutomation'\n\n/**\n * The org activity target an org automation's own lifecycle rows are filed\n * under: the plugin's namespaced resource (`pluginId:noun`), which the org's\n * feed reads as \"Automation\" — core's target list names only core's resources.\n */\nexport const ORG_AUTOMATION_ACTIVITY_TARGET = 'workflows:automation'\n\n/**\n * The events an org automation may start on: every host event the SERVER\n * raises and a person can be the subject of.\n *\n * Listed rather than derived from `HOST_EVENT_TYPES`, deliberately. The engine\n * queries the organization's automations on every event in this list, so a\n * new host event must not become an org trigger — and a new read on every\n * occurrence of it — by being added to the platform's list. Two are left out\n * on purpose: `pageView` fires on every request to every published page, and\n * an org query on it would be a read per visitor; `memberSignOut` is raised\n * by no door today.\n */\nexport const ORG_AUTOMATION_TRIGGER_EVENTS = [\n 'formSubmission',\n 'lead',\n 'contactCreated',\n 'contactStageChanged',\n 'booking',\n 'memberSignUp',\n 'memberSignIn',\n 'dealStageChanged',\n 'dealWon',\n 'dealLost',\n 'taskCompleted',\n] as const satisfies readonly HostEventType[]\n\nexport type OrgAutomationTriggerEvent =\n (typeof ORG_AUTOMATION_TRIGGER_EVENTS)[number]\n\nconst ORG_TRIGGER_SET: ReadonlySet<string> = new Set(\n ORG_AUTOMATION_TRIGGER_EVENTS,\n)\n\n/** Whether an org automation may start on this event. */\nexport function isOrgAutomationTriggerEvent(\n event: unknown,\n): event is OrgAutomationTriggerEvent {\n return typeof event === 'string' && ORG_TRIGGER_SET.has(event)\n}\n\n/**\n * The steps an org automation may hold: the server steps that read the same\n * on every site.\n *\n * What is left out, and why:\n * - every step the visitor's page runs — overlays, drawers, menus, class\n * toggles, custom HTML and JavaScript, analytics, redirects, the site\n * alert — because an org trigger is a server event with no page to act on;\n * - `runWorkflow`, because a workflow is one site's and calls that site's\n * functions and variables;\n * - `webhookPost`, because a webhook's address and secret are one site's.\n *\n * `customEvent` stays: it fires a custom event ON the site the run is on,\n * which that site's own actions may listen for — the documented way for an\n * org automation to hand over to something site-specific.\n */\nexport const ORG_AUTOMATION_STEP_TYPES = [\n 'sendEmail',\n 'notifyAdmins',\n 'enrollList',\n 'assignCampaign',\n 'datasetAppend',\n 'updateDataset',\n 'setContactStage',\n 'addContactTag',\n 'assignContactOwner',\n 'createCrmTask',\n 'logCrmActivity',\n 'customEvent',\n 'wait',\n 'waitForEvent',\n 'exitFlow',\n] as const satisfies readonly HostActionStepType[]\n\nexport type OrgAutomationStepType = (typeof ORG_AUTOMATION_STEP_TYPES)[number]\n\nconst ORG_STEP_SET: ReadonlySet<string> = new Set(ORG_AUTOMATION_STEP_TYPES)\n\n/** Whether an org automation may run a step of this type. */\nexport function isOrgAutomationStepType(\n type: unknown,\n): type is OrgAutomationStepType {\n return typeof type === 'string' && ORG_STEP_SET.has(type)\n}\n\n/** The org editor's \"Do\" picker: each allowed step with its label, in order. */\nexport const ORG_AUTOMATION_STEP_KINDS: ReadonlyArray<{\n value: OrgAutomationStepType\n label: string\n}> = ORG_AUTOMATION_STEP_TYPES.map((value) => ({\n value,\n label: HOST_ACTION_STEP_LABELS[value],\n}))\n\n/**\n * Why an org automation cannot hold this step, or null when it can.\n *\n * Shared by the save route, which refuses it, and by the engine, which\n * refuses to run one a writer stored anyway.\n */\nexport function orgAutomationStepRefusal(step: {\n type?: unknown\n}): string | null {\n if (isOrgAutomationStepType(step?.type)) return null\n const label = HOST_ACTION_STEP_LABELS[step?.type as HostActionStepType]\n if (!label) return `“${String(step?.type ?? '')}” is not a step`\n return (\n `“${label}” belongs to one site, so an org automation cannot run it — ` +\n 'build it as an action on that site'\n )\n}\n\n/** The trigger an org automation starts on, as it is stored. */\nexport interface OrgAutomationTrigger {\n event: OrgAutomationTriggerEvent\n /** Optional expression over the payload; runs only when truthy. */\n filter?: string\n conditions: HostActionTriggerCondition[] | null\n combinator: TriggerCombinator | null\n}\n\n/**\n * The fields an org automation is written with — by the save route, and by\n * nothing else: the collection is closed to client writes.\n */\nexport interface OrgAutomationFields {\n name: string\n trigger: OrgAutomationTrigger\n steps: HostActionStep[]\n enabled: boolean\n /**\n * The sites it runs on, as scope tokens: `['org']` is every site of the\n * organization, now and later; `['host:{id}', …]` names up to thirty.\n * For one that runs on all sites except some, the sites still in, which\n * the route works out from the workspace's sites when it writes: the\n * reader leaves it empty.\n */\n visibleTo: ScopeToken[]\n /**\n * How the editor chose the sites (AGL-4047), when it said so. Set, it\n * decides: `allExcept` is written by the route as the included sites plus\n * the sweep's marker (`scopeMode`, `scopeExcept`), and `all` or `selected`\n * removes a marker the automation carried. Missing, as from a client that\n * predates it, a save that leaves `visibleTo` as it was keeps the marker,\n * and one that changes it removes it. Never stored under this name.\n */\n sharing?: ScopeSharingChoice\n}\n\n/** `orgs/{orgId}/automations/{id}`, as it is stored. */\nexport interface OrgAutomation extends Omit<OrgAutomationFields, 'sharing'> {\n /**\n * Set on one that runs on all sites except some (AGL-4047): the marker the\n * sweep keeps `visibleTo` up to date from as sites come and go. Only the\n * manage route writes it, and it removes it with a field delete.\n */\n scopeMode?: typeof SCOPE_MODE_ALL_EXCEPT\n /** The sites left out, as scope tokens, beside `scopeMode`. */\n scopeExcept?: ScopeToken[]\n /**\n * The sites that have paused it for themselves — each a site id, never a\n * scope token. The \"host level control\": a site's admin or editor adds or\n * removes their own site here, and only their own.\n */\n pausedHostIds: string[]\n createdBy?: string\n updatedBy?: string\n /**\n * Set when it was deleted. Always written — `null` while live — so the\n * org hub's list can ask for the live ones by equality.\n */\n deletedAt: unknown\n}\n\n/** A stored org automation with its id, as the console lists it. */\nexport type OrgAutomationRow = OrgAutomation & { $id: string }\n\n/** Longest name an org automation may carry: the actions editor's cap. */\nexport const ORG_AUTOMATION_NAME_MAX = 60\n\n/** Longest trigger filter expression. */\nconst FILTER_MAX = 500\n\n/** Longest a condition's field or value may be. */\nconst CONDITION_FIELD_MAX = 64\nconst CONDITION_VALUE_MAX = 200\n\n/**\n * Every field a step of each type may carry beyond `type` and `when`, with\n * the longest a string in it may be. What the save route stores is exactly\n * this: a key a step's type does not list is dropped, so the document holds\n * the vocabulary and nothing a caller made up.\n *\n * The caps follow what the engine reads — it cuts a subject at 200 and a body\n * at 5,000 before sending — so nothing is stored that could not be run.\n */\nconst STEP_FIELDS: Record<\n OrgAutomationStepType,\n Readonly<Record<string, 'string' | 'number' | 'boolean' | number>>\n> = {\n sendEmail: { subject: 200, body: 5000, toField: 64, topicId: 128, transactional: 'boolean' },\n notifyAdmins: { title: 200, body: 500 },\n enrollList: { listId: 128, listName: 200 },\n assignCampaign: { campaignId: 128, campaignName: 200 },\n datasetAppend: { datasetId: 128, datasetName: 200 },\n updateDataset: { datasetId: 128, datasetName: 200 },\n setContactStage: { lifecycleStage: 64 },\n addContactTag: { tag: 200 },\n assignContactOwner: {\n ownerUid: 128,\n ownerEmail: 320,\n roundRobin: 'boolean',\n },\n createCrmTask: {\n title: 200,\n kind: 64,\n priority: 16,\n dueInDays: 'number',\n assigneeUid: 128,\n assigneeEmail: 320,\n },\n logCrmActivity: { kind: 64, body: 2000, direction: 16 },\n customEvent: { eventName: 64 },\n wait: { delayMinutes: 'number' },\n waitForEvent: { eventName: 64, timeoutMinutes: 'number' },\n exitFlow: {},\n}\n\nconst asObject = (value: unknown): Record<string, unknown> | null =>\n value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n\n/** A condition as it is stored, or null for a row that is not one. */\nfunction readCondition(raw: unknown): HostActionTriggerCondition | null {\n const row = asObject(raw)\n if (!row) return null\n const op = row['op']\n if (!(TRIGGER_CONDITION_OPS as readonly unknown[]).includes(op)) {\n // Kept as written so the validator names the missing operator rather\n // than the row silently vanishing.\n return {\n field: String(row['field'] ?? '').trim().slice(0, CONDITION_FIELD_MAX),\n op: op as never,\n }\n }\n return {\n field: String(row['field'] ?? '').trim().slice(0, CONDITION_FIELD_MAX),\n op: op as HostActionTriggerCondition['op'],\n ...(op !== 'notEmpty'\n ? { value: String(row['value'] ?? '').trim().slice(0, CONDITION_VALUE_MAX) }\n : {}),\n }\n}\n\nfunction readConditions(raw: unknown): HostActionTriggerCondition[] {\n return (Array.isArray(raw) ? raw : [])\n .slice(0, ACTION_MAX_CONDITIONS + 1)\n .map(readCondition)\n .filter((row): row is HostActionTriggerCondition => row !== null)\n}\n\nfunction readCombinator(raw: unknown): TriggerCombinator | null {\n return (TRIGGER_COMBINATORS as readonly unknown[]).includes(raw)\n ? (raw as TriggerCombinator)\n : null\n}\n\n/** One step as it would be stored: its own fields only, strings capped. */\nfunction readStep(raw: unknown): HostActionStep | { type: unknown } {\n const source = asObject(raw) ?? {}\n const type = source['type']\n if (!isOrgAutomationStepType(type)) return { type }\n const step: Record<string, unknown> = { type }\n for (const [key, kind] of Object.entries(STEP_FIELDS[type])) {\n const value = source[key]\n if (value === undefined || value === null) continue\n if (kind === 'boolean') {\n if (typeof value === 'boolean') step[key] = value\n } else if (kind === 'number') {\n if (typeof value === 'number' && Number.isFinite(value)) step[key] = value\n } else if (typeof value === 'string') {\n step[key] = value.slice(0, Number(kind))\n }\n }\n const when = asObject(source['when'])\n if (when) {\n const conditions = readConditions(when['conditions'])\n if (conditions.length) {\n step['when'] = {\n conditions,\n combinator: readCombinator(when['combinator']) ?? 'and',\n }\n }\n }\n return step as HostActionStep\n}\n\n/** The most site ids one choice may name: far past any workspace. */\nconst SHARING_CHOICE_MAX_IDS = 1000\n\nconst SHARING_PROBLEM =\n 'Choose every site, the sites, or every site except some, for it to run on'\n\n/**\n * A sharing choice off the wire (AGL-4047), or null when there is none. Ids are\n * held to a document id's shape here; whether they are the workspace's is the\n * route's to ask.\n */\nfunction readSharingChoice(\n raw: unknown,\n): { ok: true; choice: ScopeSharingChoice | null } | { ok: false; problem: string } {\n if (raw === undefined || raw === null) return { ok: true, choice: null }\n const source = asObject(raw)\n const ids = (list: unknown): string[] | null =>\n Array.isArray(list) &&\n list.length <= SHARING_CHOICE_MAX_IDS &&\n list.every((id) => typeof id === 'string' && /^[^:/]+$/.test(id))\n ? [...new Set(list as string[])]\n : null\n if (source?.['mode'] === 'all') return { ok: true, choice: { mode: 'all' } }\n if (source?.['mode'] === 'selected') {\n const hostIds = ids(source['hostIds'])\n return hostIds\n ? { ok: true, choice: { mode: 'selected', hostIds } }\n : { ok: false, problem: SHARING_PROBLEM }\n }\n if (source?.['mode'] === 'allExcept') {\n const exceptHostIds = ids(source['exceptHostIds'])\n if (!exceptHostIds) return { ok: false, problem: SHARING_PROBLEM }\n if (!exceptHostIds.length) {\n return {\n ok: false,\n problem: 'Choose at least one site to leave out, or run it on every site',\n }\n }\n return { ok: true, choice: { mode: 'allExcept', exceptHostIds } }\n }\n return { ok: false, problem: SHARING_PROBLEM }\n}\n\n/** What a caller sends to create or replace an org automation. */\nexport type OrgAutomationInput = Record<string, unknown>\n\n/**\n * Reads an org automation out of an untrusted request body: the fields it may\n * hold, in the shape they are stored, or the first reason it cannot be saved.\n *\n * The rules are the actions builder's own — `validateHostAction` checks the\n * name, the trigger's conditions and every step's fields — and on top of them\n * the two this vocabulary adds: the trigger must be an org trigger and every\n * step an org step. The placement must be a scope a save can store:\n * `normalizeVisibleTo` refuses an empty one and one over thirty sites rather\n * than guessing between sharing wider and taking access away. All sites\n * except some (AGL-4047) must leave at least one site out.\n *\n * Whether each named site belongs to the organization is the route's to ask,\n * because it takes a read, and so is which sites all-but-some reaches.\n */\nexport function readOrgAutomation(\n input: unknown,\n): { ok: true; value: OrgAutomationFields } | { ok: false; problem: string } {\n const body = asObject(input) ?? {}\n const name = String(body['name'] ?? '')\n .trim()\n .slice(0, ORG_AUTOMATION_NAME_MAX)\n if (!name) return { ok: false, problem: 'Name the automation' }\n const trigger = asObject(body['trigger']) ?? {}\n const event = String(trigger['event'] ?? '').trim()\n if (!isOrgAutomationTriggerEvent(event)) {\n return {\n ok: false,\n problem:\n 'Pick a trigger an org automation can start on — a form, a lead, a ' +\n 'booking, a member or a CRM event',\n }\n }\n const filter = String(trigger['filter'] ?? '')\n .trim()\n .slice(0, FILTER_MAX)\n const conditions = readConditions(trigger['conditions'])\n const combinator = readCombinator(trigger['combinator'])\n const rawSteps = Array.isArray(body['steps']) ? body['steps'] : []\n if (rawSteps.length > ACTION_MAX_STEPS) {\n return {\n ok: false,\n problem: `Org automations are capped at ${ACTION_MAX_STEPS} steps`,\n }\n }\n const steps = rawSteps.map(readStep)\n for (const [index, step] of steps.entries()) {\n const refusal = orgAutomationStepRefusal(step)\n if (refusal) return { ok: false, problem: `Step ${index + 1}: ${refusal}` }\n }\n const problem = validateHostAction({\n name,\n trigger: {\n event,\n ...(filter ? { filter } : {}),\n ...(conditions.length ? { conditions } : {}),\n ...(combinator ? { combinator } : {}),\n },\n steps: steps as HostActionStep[],\n })\n if (problem) return { ok: false, problem }\n const sharing = readSharingChoice(body['sharing'])\n if (sharing.ok === false) return { ok: false, problem: sharing.problem }\n const choice = sharing.choice\n /*\n * A choice decides the placement; without one, `visibleTo` does, as it did\n * before there was a choice. All sites except some names no site here: the\n * route works the sites out from the workspace's, in the write.\n */\n const visibleTo: ScopeToken[] | null =\n choice?.mode === 'allExcept'\n ? []\n : choice?.mode === 'all'\n ? [ORG_SCOPE_TOKEN]\n : normalizeVisibleTo(\n choice?.mode === 'selected'\n ? choice.hostIds.map(hostScopeToken)\n : Array.isArray(body['visibleTo'])\n ? (body['visibleTo'] as unknown[]).filter(\n (token): token is string => typeof token === 'string',\n )\n : [],\n )\n if (!visibleTo) {\n return {\n ok: false,\n problem: 'Choose every site, or up to 30 sites, for it to run on',\n }\n }\n return {\n ok: true,\n value: {\n name,\n trigger: {\n event,\n ...(filter ? { filter } : {}),\n conditions: conditions.length ? conditions : null,\n combinator: conditions.length ? (combinator ?? 'and') : null,\n },\n steps: steps as HostActionStep[],\n enabled: body['enabled'] !== false,\n visibleTo,\n ...(choice ? { sharing: choice } : {}),\n },\n }\n}\n\n/**\n * The sharing choice a STORED automation was written with, for a reader that\n * has to say it back (AGL-4047): all sites except some, read off the marker,\n * or null for one whose `visibleTo` already says everything.\n */\nexport function orgAutomationStoredSharing(\n automation: Readonly<Record<string, unknown>> | null | undefined,\n): Extract<ScopeSharingChoice, { mode: 'allExcept' }> | null {\n const sharing = scopeSharingOf(automation)\n return sharing.mode === 'allExcept'\n ? { mode: 'allExcept', exceptHostIds: sharing.exceptHostIds }\n : null\n}\n\n/** A stored document's pause list, read defensively. */\nexport function orgAutomationPausedHostIds(\n automation: { pausedHostIds?: unknown } | null | undefined,\n): string[] {\n const paused = automation?.pausedHostIds\n return Array.isArray(paused)\n ? paused.filter((id): id is string => typeof id === 'string')\n : []\n}\n\n/**\n * Why a stored org automation will not run on this site, or null when it\n * will — the one answer the engine asks when an event arrives and again when\n * a person waiting inside the automation is due.\n *\n * Deleted, switched off, taken off the site and paused there are the four\n * ways an organization or a site says \"not here\", and every one of them\n * stops the people already waiting on this site as well as the next run: the\n * kill switch a site action's resume applies, for the same reason.\n */\nexport function orgAutomationStopReason(\n automation:\n | {\n deletedAt?: unknown\n enabled?: unknown\n visibleTo?: unknown\n pausedHostIds?: unknown\n }\n | null\n | undefined,\n hostId: string,\n): string | null {\n if (!automation || automation.deletedAt) {\n return 'the org automation was deleted'\n }\n if (automation.enabled === false) {\n return 'the org automation was switched off'\n }\n if (!visibleToHost(automation.visibleTo as string[] | undefined, hostId)) {\n return 'the org automation no longer runs on this site'\n }\n if (orgAutomationPausedHostIds(automation).includes(hostId)) {\n return 'the org automation is paused on this site'\n }\n return null\n}\n\n/** Whether a stored org automation runs on this site. */\nexport function orgAutomationRunsOnHost(\n automation: Parameters<typeof orgAutomationStopReason>[0],\n hostId: string,\n): boolean {\n return orgAutomationStopReason(automation, hostId) === null\n}\n\n/**\n * A pause list after the placement changed: a site the automation no longer\n * runs on has nothing left to pause, so its entry goes with it, and a site\n * placed on it again later starts unpaused. A site left out of one that runs\n * on all sites except some is not in `visibleTo`, so its pause goes too\n * (AGL-4047).\n */\nexport function prunePausedHostIds(\n pausedHostIds: readonly string[],\n visibleTo: readonly string[],\n): string[] {\n return pausedHostIds.filter((hostId) => visibleToHost(visibleTo, hostId))\n}\n"],"names":["hostScopeToken","normalizeVisibleTo","ORG_SCOPE_TOKEN","scopeSharingOf","visibleToHost","ACTION_MAX_CONDITIONS","ACTION_MAX_STEPS","TRIGGER_COMBINATORS","TRIGGER_CONDITION_OPS","HOST_ACTION_STEP_LABELS","validateHostAction","ORG_AUTOMATIONS_COLLECTION","ORG_AUTOMATION_API_ROUTES","manage","pause","ORG_AUTOMATIONS_MAX","MAX_TRIGGERED_ORG_AUTOMATIONS","ORG_AUTOMATION_RUN_TARGET","ORG_AUTOMATION_ACTIVITY_TARGET","ORG_AUTOMATION_TRIGGER_EVENTS","ORG_TRIGGER_SET","Set","isOrgAutomationTriggerEvent","event","has","ORG_AUTOMATION_STEP_TYPES","ORG_STEP_SET","isOrgAutomationStepType","type","ORG_AUTOMATION_STEP_KINDS","map","value","label","orgAutomationStepRefusal","step","String","ORG_AUTOMATION_NAME_MAX","FILTER_MAX","CONDITION_FIELD_MAX","CONDITION_VALUE_MAX","STEP_FIELDS","sendEmail","subject","body","toField","topicId","transactional","notifyAdmins","title","enrollList","listId","listName","assignCampaign","campaignId","campaignName","datasetAppend","datasetId","datasetName","updateDataset","setContactStage","lifecycleStage","addContactTag","tag","assignContactOwner","ownerUid","ownerEmail","roundRobin","createCrmTask","kind","priority","dueInDays","assigneeUid","assigneeEmail","logCrmActivity","direction","customEvent","eventName","wait","delayMinutes","waitForEvent","timeoutMinutes","exitFlow","asObject","Array","isArray","readCondition","raw","row","op","includes","field","trim","slice","readConditions","filter","readCombinator","readStep","source","key","Object","entries","undefined","Number","isFinite","when","conditions","length","combinator","SHARING_CHOICE_MAX_IDS","SHARING_PROBLEM","readSharingChoice","ok","choice","ids","list","every","id","test","mode","hostIds","problem","exceptHostIds","readOrgAutomation","input","trigger","name","rawSteps","steps","index","refusal","sharing","visibleTo","token","enabled","orgAutomationStoredSharing","automation","orgAutomationPausedHostIds","paused","pausedHostIds","orgAutomationStopReason","hostId","deletedAt","orgAutomationRunsOnHost","prunePausedHostIds"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,kBAAkB,EAClBC,eAAe,EAGfC,cAAc,EAEdC,aAAa,QACR,sCAAqC;AAE5C,SACEC,qBAAqB,EACrBC,gBAAgB,EAChBC,mBAAmB,EACnBC,qBAAqB,QAEhB,2CAA0C;AACjD,SACEC,uBAAuB,EAIvBC,kBAAkB,QACb,oBAAgB;AAEvB;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GAED,+CAA+C,GAC/C,OAAO,MAAMC,6BAA6B,cAAa;AAEvD;;;;;CAKC,GACD,OAAO,MAAMC,4BAA4B;IACvCC,QAAQ;IACRC,OAAO;AACT,EAAU;AAEV;;;;;;;;;CASC,GACD,OAAO,MAAMC,sBAAsB,IAAG;AAEtC;;;;;;CAMC,GACD,OAAO,MAAMC,gCAAgCD,oBAAmB;AAEhE;;;CAGC,GACD,OAAO,MAAME,4BAA4B,gBAAe;AAExD;;;;CAIC,GACD,OAAO,MAAMC,iCAAiC,uBAAsB;AAEpE;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,gCAAgC;IAC3C;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAA4C;AAK7C,MAAMC,kBAAuC,IAAIC,IAC/CF;AAGF,uDAAuD,GACvD,OAAO,SAASG,4BACdC,KAAc;IAEd,OAAO,OAAOA,UAAU,YAAYH,gBAA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KAAK;YAC7BwF;WACInB,SAAS;YAAEkB,SAASlB;QAAO,IAAI,CAAC;IAExC;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASsB,2BACdC,UAAgE;IAEhE,MAAML,UAAU/H,eAAeoI;IAC/B,OAAOL,QAAQZ,IAAI,KAAK,cACpB;QAAEA,MAAM;QAAaG,eAAeS,QAAQT,aAAa;IAAC,IAC1D;AACN;AAEA,sDAAsD,GACtD,OAAO,SAASe,2BACdD,UAA0D;IAE1D,MAAME,SAASF,8BAAAA,WAAYG,aAAa;IACxC,OAAOvD,MAAMC,OAAO,CAACqD,UACjBA,OAAO3C,MAAM,CAAC,CAACsB,KAAqB,OAAOA,OAAO,YAClD,EAAE;AACR;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASuB,wBACdJ,UAQa,EACbK,MAAc;IAEd,IAAI,CAACL,cAAcA,WAAWM,SAAS,EAAE;QACvC,OAAO;IACT;IACA,IAAIN,WAAWF,OAAO,KAAK,OAAO;QAChC,OAAO;IACT;IACA,IAAI,CAACjI,cAAcmI,WAAWJ,SAAS,EAA0BS,SAAS;QACxE,OAAO;IACT;IACA,IAAIJ,2BAA2BD,YAAY9C,QAAQ,CAACmD,SAAS;QAC3D,OAAO;IACT;IACA,OAAO;AACT;AAEA,uDAAuD,GACvD,OAAO,SAASE,wBACdP,UAAyD,EACzDK,MAAc;IAEd,OAAOD,wBAAwBJ,YAAYK,YAAY;AACzD;AAEA;;;;;;CAMC,GACD,OAAO,SAASG,mBACdL,aAAgC,EAChCP,SAA4B;IAE5B,OAAOO,cAAc5C,MAAM,CAAC,CAAC8C,SAAWxI,cAAc+H,WAAWS;AACnE"}
|
|
@@ -69,12 +69,6 @@ export type OrgAutomationWrite = {
|
|
|
69
69
|
status: number;
|
|
70
70
|
error: string;
|
|
71
71
|
};
|
|
72
|
-
/**
|
|
73
|
-
* Creates an org automation as `automations/manage` does: its sites must be
|
|
74
|
-
* the organization's, and the organization holds at most
|
|
75
|
-
* {@link ORG_AUTOMATIONS_MAX} live ones. The route and the package import
|
|
76
|
-
* (AGL-3535) both create through here.
|
|
77
|
-
*/
|
|
78
72
|
export declare function createOrgAutomationRecord(firestore: FirebaseFirestore.Firestore, input: {
|
|
79
73
|
orgId: string;
|
|
80
74
|
id: string;
|
|
@@ -38,7 +38,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
38
38
|
* org-wide editor; nobody may pause a site through it but the one named.
|
|
39
39
|
*/ import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
|
|
40
40
|
import { holdsStampedSiteKey } from "@aglyn/aglyn/app-utils/host-permissions";
|
|
41
|
-
import { hostIdsFromScope, visibleToHost } from "@aglyn/aglyn/app-utils/scope-tokens";
|
|
41
|
+
import { hostIdsFromScope, sharingFromChoice, visibleToHost } from "@aglyn/aglyn/app-utils/scope-tokens";
|
|
42
42
|
import { isPluginEnabled } from "@aglyn/aglyn/plugin-manager/enabled-plugins";
|
|
43
43
|
import { checkEntitlement, isOrgWideMember, planLabelGrantingFeature } from "@aglyn/aglyn/server";
|
|
44
44
|
/*
|
|
@@ -48,6 +48,7 @@ import { checkEntitlement, isOrgWideMember, planLabelGrantingFeature } from "@ag
|
|
|
48
48
|
*/ import { isDocumentId } from "@aglyn/tenant-data-admin/server/document-id";
|
|
49
49
|
import firebaseAdmin from "@aglyn/tenant-data-admin/server/firebase-admin";
|
|
50
50
|
import { getOrgDoc, logHostActivity, logOrgActivity, memberHasOrgPermission, resolveOrgIdForHost, resolveOrgMembership } from "@aglyn/tenant-data-admin/server/organizations";
|
|
51
|
+
import { fieldsToWrite, orgHostIdsFromDoc } from "@aglyn/tenant-data-admin/server/scope-sharing-sweep";
|
|
51
52
|
import { FieldValue } from "firebase-admin/firestore";
|
|
52
53
|
import { BUNDLE_ID } from "../constants/bundle-common.js";
|
|
53
54
|
import { WORKFLOWS_SITE_PAUSE_PRESET, workflowsPermissionRefusal } from "../model/workflows-permissions.js";
|
|
@@ -119,7 +120,75 @@ function automationsOf(firestore, orgId) {
|
|
|
119
120
|
* the organization's, and the organization holds at most
|
|
120
121
|
* {@link ORG_AUTOMATIONS_MAX} live ones. The route and the package import
|
|
121
122
|
* (AGL-3535) both create through here.
|
|
122
|
-
*/
|
|
123
|
+
*/ /** Two placements name the same sites, in any order. */ function samePlacement(a, b) {
|
|
124
|
+
const before = Array.isArray(a) ? new Set(a) : null;
|
|
125
|
+
return Boolean(before) && (before == null ? void 0 : before.size) === new Set(b).size && b.every((token)=>before == null ? void 0 : before.has(token));
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* What one write stores of where an automation runs (AGL-4047), inside the
|
|
129
|
+
* write's transaction, or why it can't.
|
|
130
|
+
*
|
|
131
|
+
* All sites except some is worked out from the workspace's sites, read in the
|
|
132
|
+
* same transaction: a site being created writes that document too, so it
|
|
133
|
+
* either lands first and is on the list, or lands after and its sweep finds
|
|
134
|
+
* this automation. A site left out that the workspace doesn't hold is dropped,
|
|
135
|
+
* as the dataset route does: it may be one that has just gone.
|
|
136
|
+
*
|
|
137
|
+
* Any other placement removes a marker the automation carried, as a field
|
|
138
|
+
* delete, when the editor chose it (`sharing` set) or the sites moved. A save
|
|
139
|
+
* from a client that predates the choice, sending back the sites it was
|
|
140
|
+
* shown, keeps the marker: it changed nothing about where it runs.
|
|
141
|
+
*/ async function placementToWrite(transaction, firestore, orgId, fields, current) {
|
|
142
|
+
var _fields_sharing;
|
|
143
|
+
if (((_fields_sharing = fields.sharing) == null ? void 0 : _fields_sharing.mode) === 'allExcept') {
|
|
144
|
+
const org = await transaction.get(firestore.collection('orgs').doc(orgId));
|
|
145
|
+
const shared = sharingFromChoice(fields.sharing, orgHostIdsFromDoc(org.data()));
|
|
146
|
+
if (!shared.fields) return {
|
|
147
|
+
ok: false,
|
|
148
|
+
error: shared.problem
|
|
149
|
+
};
|
|
150
|
+
return {
|
|
151
|
+
ok: true,
|
|
152
|
+
data: fieldsToWrite(shared.fields),
|
|
153
|
+
visibleTo: shared.fields.visibleTo
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
const marked = (current == null ? void 0 : current['scopeMode']) !== undefined && (current == null ? void 0 : current['scopeMode']) !== null;
|
|
157
|
+
if (!marked) return {
|
|
158
|
+
ok: true,
|
|
159
|
+
data: {
|
|
160
|
+
visibleTo: fields.visibleTo
|
|
161
|
+
},
|
|
162
|
+
visibleTo: fields.visibleTo
|
|
163
|
+
};
|
|
164
|
+
if (!fields.sharing && samePlacement(current == null ? void 0 : current['visibleTo'], fields.visibleTo)) {
|
|
165
|
+
// Left exactly as the sweep keeps it.
|
|
166
|
+
return {
|
|
167
|
+
ok: true,
|
|
168
|
+
data: {},
|
|
169
|
+
visibleTo: current == null ? void 0 : current['visibleTo']
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
return {
|
|
173
|
+
ok: true,
|
|
174
|
+
data: fieldsToWrite({
|
|
175
|
+
visibleTo: fields.visibleTo,
|
|
176
|
+
scopeMode: null,
|
|
177
|
+
scopeExcept: null
|
|
178
|
+
}),
|
|
179
|
+
visibleTo: fields.visibleTo
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
/** The fields a write stores beside its placement: never the choice itself. */ function storedFieldsOf(fields) {
|
|
183
|
+
return {
|
|
184
|
+
name: fields.name,
|
|
185
|
+
trigger: fields.trigger,
|
|
186
|
+
steps: fields.steps,
|
|
187
|
+
enabled: fields.enabled
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
export async function createOrgAutomationRecord(firestore, input) {
|
|
191
|
+
var _input_fields_sharing;
|
|
123
192
|
if (!await placementIsTheOrgs(firestore, input.orgId, input.fields.visibleTo)) {
|
|
124
193
|
return {
|
|
125
194
|
ok: false,
|
|
@@ -141,14 +210,35 @@ function automationsOf(firestore, orgId) {
|
|
|
141
210
|
error: `An organization holds at most ${ORG_AUTOMATIONS_MAX} org automations — delete one you no longer use first`
|
|
142
211
|
};
|
|
143
212
|
}
|
|
144
|
-
|
|
213
|
+
const stamped = {
|
|
145
214
|
pausedHostIds: [],
|
|
146
215
|
deletedAt: null,
|
|
147
216
|
createdAt: FieldValue.serverTimestamp(),
|
|
148
217
|
createdBy: input.actorUid,
|
|
149
218
|
updatedAt: FieldValue.serverTimestamp(),
|
|
150
219
|
updatedBy: input.actorUid
|
|
151
|
-
}
|
|
220
|
+
};
|
|
221
|
+
if (((_input_fields_sharing = input.fields.sharing) == null ? void 0 : _input_fields_sharing.mode) === 'allExcept') {
|
|
222
|
+
// The workspace's sites are read in the write's own transaction; see
|
|
223
|
+
// `placementToWrite`. A new document carries no marker to remove.
|
|
224
|
+
const error = await firestore.runTransaction(async (transaction)=>{
|
|
225
|
+
const placed = await placementToWrite(transaction, firestore, input.orgId, input.fields, undefined);
|
|
226
|
+
if (placed.ok === false) return placed.error;
|
|
227
|
+
transaction.create(collection.doc(input.id), _extends({}, storedFieldsOf(input.fields), placed.data, stamped));
|
|
228
|
+
return null;
|
|
229
|
+
});
|
|
230
|
+
return error ? {
|
|
231
|
+
ok: false,
|
|
232
|
+
status: 400,
|
|
233
|
+
error
|
|
234
|
+
} : {
|
|
235
|
+
ok: true,
|
|
236
|
+
id: input.id
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
await collection.doc(input.id).create(_extends({}, storedFieldsOf(input.fields), {
|
|
240
|
+
visibleTo: input.fields.visibleTo
|
|
241
|
+
}, stamped));
|
|
152
242
|
return {
|
|
153
243
|
ok: true,
|
|
154
244
|
id: input.id
|
|
@@ -166,20 +256,36 @@ function automationsOf(firestore, orgId) {
|
|
|
166
256
|
const outcome = await firestore.runTransaction(async (transaction)=>{
|
|
167
257
|
const ref = collection.doc(input.id);
|
|
168
258
|
const current = await transaction.get(ref);
|
|
169
|
-
if (!current.exists || current.get('deletedAt')) return
|
|
170
|
-
|
|
259
|
+
if (!current.exists || current.get('deletedAt')) return {
|
|
260
|
+
missing: true
|
|
261
|
+
};
|
|
262
|
+
const placed = await placementToWrite(transaction, firestore, input.orgId, input.fields, current.data());
|
|
263
|
+
if (placed.ok === false) return {
|
|
264
|
+
missing: false,
|
|
265
|
+
error: placed.error
|
|
266
|
+
};
|
|
267
|
+
transaction.update(ref, _extends({}, storedFieldsOf(input.fields), placed.data, {
|
|
171
268
|
// A site the automation no longer runs on has nothing left to
|
|
172
|
-
// pause: its entry goes, so a later placement starts unpaused.
|
|
173
|
-
|
|
269
|
+
// pause: its entry goes, so a later placement starts unpaused. That
|
|
270
|
+
// includes a site left out of all sites except some (AGL-4047).
|
|
271
|
+
pausedHostIds: prunePausedHostIds(orgAutomationPausedHostIds(current.data()), placed.visibleTo),
|
|
174
272
|
updatedAt: FieldValue.serverTimestamp(),
|
|
175
273
|
updatedBy: input.actorUid
|
|
176
274
|
}));
|
|
177
|
-
return
|
|
275
|
+
return {
|
|
276
|
+
missing: false,
|
|
277
|
+
error: null
|
|
278
|
+
};
|
|
178
279
|
});
|
|
179
|
-
|
|
280
|
+
if (outcome.missing) return {
|
|
180
281
|
ok: false,
|
|
181
282
|
status: 404,
|
|
182
283
|
error: 'Unknown org automation'
|
|
284
|
+
};
|
|
285
|
+
return outcome.error ? {
|
|
286
|
+
ok: false,
|
|
287
|
+
status: 400,
|
|
288
|
+
error: outcome.error
|
|
183
289
|
} : {
|
|
184
290
|
ok: true,
|
|
185
291
|
id: input.id
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/server/org-automations-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * WRITING AN ORG AUTOMATION, and pausing one on a site (AGL-3302).\n *\n * `orgs/{orgId}/automations` is closed to every client write, the way the\n * outreach collections are: an org automation runs on every site it is\n * placed on, as that site, so its trigger, its steps and its placement are\n * decisions the server checks — the vocabulary, the organization's sites, the\n * plan — and nothing a browser may write around.\n *\n * ## Two doors\n *\n * `automations/manage` is the organization's: it creates, edits, switches on\n * and off, and deletes. It names the org and NO site, so it declares a\n * subject resolver for the dispatchers' release gate and asks the org's\n * plugin switch itself; the caller must be an org-wide owner, admin or\n * editor.\n *\n * `automations/pause` is the SITE's — the host level control. It names the\n * site, so the dispatcher applies that site's plugin switch as for any site\n * request, and it changes one thing: whether this automation is paused on\n * THIS site. The site's own admins and editors may use it, and so may an\n * org-wide editor; nobody may pause a site through it but the one named.\n */\n\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { holdsStampedSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { hostIdsFromScope, visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { isPluginEnabled } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\nimport {\n type AglynOrgMember,\n checkEntitlement,\n isOrgWideMember,\n type PluginApiHandler,\n type PluginApiRequestSubject,\n planLabelGrantingFeature,\n} from '@aglyn/aglyn/server'\n/*\n * The MODULES, not the barrel: `@aglyn/tenant-data-admin`'s index reaches the\n * Next render cache, and everything these doors need is the Admin SDK handle,\n * the id predicate and the org reads.\n */\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport firebaseAdmin from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport {\n getOrgDoc,\n logHostActivity,\n logOrgActivity,\n memberHasOrgPermission,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n WORKFLOWS_SITE_PAUSE_PRESET,\n workflowsPermissionRefusal,\n type WorkflowsPermission,\n} from '../model/workflows-permissions'\nimport {\n ORG_AUTOMATION_ACTIVITY_TARGET,\n ORG_AUTOMATION_API_ROUTES,\n ORG_AUTOMATIONS_COLLECTION,\n ORG_AUTOMATIONS_MAX,\n orgAutomationPausedHostIds,\n prunePausedHostIds,\n readOrgAutomation,\n type OrgAutomationFields,\n} from '../model/org-automations'\n\nexport { ORG_AUTOMATION_API_ROUTES }\n\n/** What `automations/manage` may be asked to do. */\nexport const ORG_AUTOMATION_MANAGE_ACTIONS = [\n 'create',\n 'update',\n 'setEnabled',\n 'delete',\n] as const\n\ntype ManageAction = (typeof ORG_AUTOMATION_MANAGE_ACTIONS)[number]\n\n\n/** What the doors reach outside this module; specs hand in their own. */\nexport interface OrgAutomationRouteDeps {\n firestore(): FirebaseFirestore.Firestore\n verifyIdToken(token: string): Promise<{ uid: string; email?: string | null }>\n resolveOrgMembership(\n uid: string,\n orgId: string,\n ): Promise<{ orgId: string; member: Partial<AglynOrgMember> } | null>\n getOrgDoc(orgId: string): Promise<Record<string, unknown> | null>\n resolveOrgIdForHost(hostId: string): Promise<string | null>\n /** Whether a member holds a workspace key with no site named (AGL-4047): `memberHasOrgPermission`. */\n holdsOrgKey(orgId: string, member: Partial<AglynOrgMember>, key: WorkflowsPermission): Promise<boolean>\n logOrgActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n action: string,\n target: { type: typeof ORG_AUTOMATION_ACTIVITY_TARGET; id: string; name?: string },\n ): Promise<void>\n logHostActivity(\n hostId: string,\n actor: { uid: string; email?: string | null },\n action: string,\n target: { type: 'workflow'; id: string; name?: string },\n ): Promise<void>\n newId(): string\n}\n\nfunction defaultDeps(): OrgAutomationRouteDeps {\n return {\n firestore: () =>\n firebaseAdmin.app().firestore() as unknown as FirebaseFirestore.Firestore,\n verifyIdToken: async (token) => {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(token)\n return { uid: decoded.uid, email: decoded.email ?? null }\n },\n resolveOrgMembership: async (uid, orgId) =>\n (await resolveOrgMembership(uid, orgId)) as never,\n getOrgDoc: async (orgId) =>\n ((await getOrgDoc(orgId)) as Record<string, unknown> | null) ?? null,\n resolveOrgIdForHost,\n holdsOrgKey: (orgId, member, key) => memberHasOrgPermission(orgId, member, key as never),\n logOrgActivity: (orgId, actor, action, target) =>\n logOrgActivity(orgId, actor, action, target),\n logHostActivity: (hostId, actor, action, target) =>\n logHostActivity(hostId, actor, action, target),\n newId: createResourceUid,\n }\n}\n\n/** The bearer token a request carries, or null. */\nfunction bearerToken(headers: Partial<Record<string, string | string[]>>): string | null {\n const authorization = String(headers['authorization'] ?? '')\n return authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length) || null\n : null\n}\n\nfunction automationsOf(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): FirebaseFirestore.CollectionReference {\n return firestore\n .collection('orgs')\n .doc(orgId)\n .collection(ORG_AUTOMATIONS_COLLECTION)\n}\n\n/**\n * Whether every site a placement names belongs to this organization — asked\n * of `hostIndex`, the mirror `resolveOrgIdForHost` reads, in one round trip.\n * `['org']` names no site and always answers yes.\n */\nasync function placementIsTheOrgs(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n visibleTo: readonly string[],\n): Promise<boolean> {\n const hostIds = hostIdsFromScope(visibleTo)\n if (!hostIds.length) return true\n if (!hostIds.every(isDocumentId)) return false\n const entries = await firestore.getAll(\n ...hostIds.map((hostId) => firestore.collection('hostIndex').doc(hostId)),\n )\n return entries.every((entry) => entry.exists && entry.get('orgId') === orgId)\n}\n\n/**\n * The organization a `automations/manage` request is for, read off its JSON\n * body, so the dispatchers' release gate asks about the right organization.\n * Consulted only for a request that names no site. Unverified, exactly as a\n * `hostId` is: the handler refuses anyone who is not an org-wide member.\n */\nexport async function orgAutomationsManageSubject(\n request: Request,\n): Promise<PluginApiRequestSubject | null> {\n if (request.method !== 'POST') return null\n const body = (await request.json().catch(() => null)) as {\n orgId?: unknown\n } | null\n const orgId = typeof body?.orgId === 'string' ? body.orgId : ''\n return isDocumentId(orgId) ? { orgId } : null\n}\n\n/** What writing an org automation came to: its id, or the refusal the route answers with. */\nexport type OrgAutomationWrite = { ok: true; id: string } | { ok: false; status: number; error: string }\n\n/**\n * Creates an org automation as `automations/manage` does: its sites must be\n * the organization's, and the organization holds at most\n * {@link ORG_AUTOMATIONS_MAX} live ones. The route and the package import\n * (AGL-3535) both create through here.\n */\nexport async function createOrgAutomationRecord(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; id: string; fields: OrgAutomationFields; actorUid: string },\n): Promise<OrgAutomationWrite> {\n if (!(await placementIsTheOrgs(firestore, input.orgId, input.fields.visibleTo))) {\n return { ok: false, status: 400, error: 'A site you chose is not in this organization' }\n }\n const collection = automationsOf(firestore, input.orgId)\n /*\n * Counted before the write rather than inside a transaction. The\n * cap bounds storage, not money, so the overshoot two simultaneous\n * saves can buy is one document — the trade the site actions cap\n * makes for the same reason.\n */\n const live = (await collection.where('deletedAt', '==', null).count().get()).data().count\n if (live >= ORG_AUTOMATIONS_MAX) {\n return {\n ok: false,\n status: 409,\n error: `An organization holds at most ${ORG_AUTOMATIONS_MAX} org automations — delete one you no longer use first`,\n }\n }\n await collection.doc(input.id).create({\n ...input.fields,\n pausedHostIds: [],\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n createdBy: input.actorUid,\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: input.actorUid,\n })\n return { ok: true, id: input.id }\n}\n\n/** Rewrites a live org automation as `automations/manage` does; a site it no longer runs on leaves its pause list. */\nexport async function updateOrgAutomationRecord(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; id: string; fields: OrgAutomationFields; actorUid: string },\n): Promise<OrgAutomationWrite> {\n if (!(await placementIsTheOrgs(firestore, input.orgId, input.fields.visibleTo))) {\n return { ok: false, status: 400, error: 'A site you chose is not in this organization' }\n }\n const collection = automationsOf(firestore, input.orgId)\n const outcome = await firestore.runTransaction(async (transaction) => {\n const ref = collection.doc(input.id)\n const current = await transaction.get(ref)\n if (!current.exists || current.get('deletedAt')) return 'missing'\n transaction.update(ref, {\n ...input.fields,\n // A site the automation no longer runs on has nothing left to\n // pause: its entry goes, so a later placement starts unpaused.\n pausedHostIds: prunePausedHostIds(orgAutomationPausedHostIds(current.data()), input.fields.visibleTo),\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: input.actorUid,\n })\n return 'updated'\n })\n return outcome === 'missing' ? { ok: false, status: 404, error: 'Unknown org automation' } : { ok: true, id: input.id }\n}\n\n/**\n * Deletes an org automation as `automations/manage` does — softly, switched\n * off (see the handler). `null` for one that does not exist; `again` for\n * one already deleted.\n */\nexport async function deleteOrgAutomationRecord(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; id: string; actorUid: string },\n): Promise<{ name: string; again: boolean } | null> {\n return firestore.runTransaction(async (transaction) => {\n const ref = automationsOf(firestore, input.orgId).doc(input.id)\n const current = await transaction.get(ref)\n if (!current.exists) return null\n // Deleting twice is the same request answered again.\n if (current.get('deletedAt')) return { name: '', again: true }\n transaction.update(ref, {\n deletedAt: FieldValue.serverTimestamp(),\n deletedBy: input.actorUid,\n // Off as well, so the engine's query — which asks for switched-on\n // automations only — never spends one of its places on it.\n enabled: false,\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: input.actorUid,\n })\n return { name: String(current.get('name') ?? ''), again: false }\n })\n}\n\n/**\n * `automations/manage`: create, edit, switch on or off, and delete one of the\n * organization's automations.\n *\n * A DELETE is soft — `deletedAt` stamped and the automation switched off —\n * because the id is what every run history row and every waiting person\n * names: the rows keep a name to show, and the people waiting inside it are\n * stopped by the resume's kill switch on their next beat. Deleting and\n * switching off are never refused for want of a plan, so an organization\n * that downgraded can always stop what it built.\n */\nexport function createOrgAutomationsManageHandler(\n overrides: Partial<OrgAutomationRouteDeps> = {},\n): PluginApiHandler {\n return async (req, res) => {\n const deps = { ...defaultDeps(), ...overrides }\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const orgId = String(req.body?.orgId ?? '')\n const action = String(req.body?.action ?? '') as ManageAction\n if (!isDocumentId(orgId)) {\n return res.status(400).json({ error: 'Invalid orgId' })\n }\n if (!(ORG_AUTOMATION_MANAGE_ACTIONS as readonly string[]).includes(action)) {\n return res.status(400).json({ error: 'Unknown action' })\n }\n const automationId = String(req.body?.automationId ?? '')\n if (action !== 'create' && !isDocumentId(automationId)) {\n return res.status(400).json({ error: 'Invalid automationId' })\n }\n const token = bearerToken(req.headers)\n if (!token) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const caller = await deps.verifyIdToken(token).catch(() => null)\n if (!caller) return res.status(401).json({ error: 'Unauthenticated' })\n const membership = await deps.resolveOrgMembership(caller.uid, orgId)\n const member = membership?.member\n // \"Manage org automations\" (AGL-4047), for members of the whole\n // workspace: its default is the owner, admins and editors this asked\n // for before, then their custom role and their own permissions.\n if (\n !member ||\n !isOrgWideMember(member) ||\n !(await deps.holdsOrgKey(orgId, member, 'workflows.orgAutomations'))\n ) {\n return res.status(403).json({ error: workflowsPermissionRefusal('workflows.orgAutomations') })\n }\n /*\n * A request naming no site reaches here past only the release gate —\n * the dispatcher's per-site switch needs a site — so the organization's\n * own switch is asked here.\n */\n const org = await deps.getOrgDoc(orgId)\n if (!org || !isPluginEnabled(org as never, BUNDLE_ID)) {\n return res.status(404).json({ error: 'Not found' })\n }\n const enabling =\n action === 'create' ||\n action === 'update' ||\n (action === 'setEnabled' && req.body?.enabled === true)\n if (enabling && !checkEntitlement(org as never, 'actions')) {\n return res.status(403).json({\n error: `Org automations need the ${planLabelGrantingFeature('actions') ?? 'Pro'} plan`,\n })\n }\n\n const firestore = deps.firestore()\n const collection = automationsOf(firestore, orgId)\n const actor = { uid: caller.uid, email: caller.email ?? null }\n const logged = (verb: string, id: string, name: string) =>\n deps.logOrgActivity(orgId, actor, verb, {\n type: ORG_AUTOMATION_ACTIVITY_TARGET,\n id,\n name,\n })\n\n if (action === 'create' || action === 'update') {\n const read = readOrgAutomation(req.body?.automation)\n if (read.ok === false) {\n return res.status(400).json({ error: read.problem })\n }\n const written =\n action === 'create'\n ? await createOrgAutomationRecord(firestore, { orgId, id: deps.newId(), fields: read.value, actorUid: caller.uid })\n : await updateOrgAutomationRecord(firestore, { orgId, id: automationId, fields: read.value, actorUid: caller.uid })\n if (written.ok === false) {\n return res.status(written.status).json({ error: written.error })\n }\n await logged(action === 'create' ? 'Created an org automation' : 'Edited an org automation', written.id, read.value.name)\n return res.status(200).json({ automationId: written.id })\n }\n\n if (action === 'setEnabled') {\n if (typeof req.body?.enabled !== 'boolean') {\n return res.status(400).json({ error: 'Say whether it is enabled' })\n }\n const enabled = req.body.enabled as boolean\n const name = await firestore.runTransaction(async (transaction) => {\n const ref = collection.doc(automationId)\n const current = await transaction.get(ref)\n if (!current.exists || current.get('deletedAt')) return null\n transaction.update(ref, {\n enabled,\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: caller.uid,\n })\n return String(current.get('name') ?? '')\n })\n if (name === null) {\n return res.status(404).json({ error: 'Unknown org automation' })\n }\n await logged(\n enabled ? 'Switched on an org automation' : 'Switched off an org automation',\n automationId,\n name,\n )\n return res.status(200).json({ automationId, enabled })\n }\n\n // delete\n const deleted = await deleteOrgAutomationRecord(firestore, { orgId, id: automationId, actorUid: caller.uid })\n if (!deleted) {\n return res.status(404).json({ error: 'Unknown org automation' })\n }\n if (!deleted.again) {\n await logged('Deleted an org automation', automationId, deleted.name)\n }\n return res.status(200).json({ automationId, deleted: true })\n } catch (error) {\n console.error('[org automations] manage failed', orgId, action, error)\n return res\n .status(500)\n .json({ error: 'The request could not be completed' })\n }\n }\n}\n\n/**\n * `automations/pause`: pause or resume one org automation on ONE site.\n *\n * `pausedHostIds` is changed with `arrayUnion`/`arrayRemove` of the named\n * site alone, inside a transaction that first confirms the automation runs\n * there — so a site's editor can take their own site out of an org\n * automation and put it back, and can never touch another site's entry or\n * the automation itself. Pausing stops the people already waiting inside it\n * on this site as well, on their next beat: the resume reads a pause as the\n * kill switch.\n *\n * Never refused for want of a plan: a pause is how a site stops something,\n * and stopping is always allowed.\n */\nexport function createOrgAutomationPauseHandler(\n overrides: Partial<OrgAutomationRouteDeps> = {},\n): PluginApiHandler {\n return async (req, res) => {\n const deps = { ...defaultDeps(), ...overrides }\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const automationId = String(req.body?.automationId ?? '')\n const paused = req.body?.paused\n if (!isDocumentId(hostId)) {\n return res.status(400).json({ error: 'Invalid hostId' })\n }\n if (!isDocumentId(automationId)) {\n return res.status(400).json({ error: 'Invalid automationId' })\n }\n if (typeof paused !== 'boolean') {\n return res.status(400).json({ error: 'Say whether it is paused' })\n }\n const token = bearerToken(req.headers)\n if (!token) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const caller = await deps.verifyIdToken(token).catch(() => null)\n if (!caller) return res.status(401).json({ error: 'Unauthenticated' })\n const firestore = deps.firestore()\n const host = await firestore.collection('hosts').doc(hostId).get()\n if (!host.exists) return res.status(404).json({ error: 'Unknown site' })\n const orgId = await deps.resolveOrgIdForHost(hostId)\n if (!orgId) {\n return res.status(409).json({\n error: 'This site is not part of an organization, so it runs no org automations.',\n })\n }\n const requestedOrgId = String(req.body?.orgId ?? '')\n if (requestedOrgId && requestedOrgId !== orgId) {\n return res.status(400).json({ error: 'That site is not in this organization' })\n }\n /*\n * The site's own admins and editors, read off the host's `memberRoles`\n * projection — the same answer every site door asks — or an org-wide\n * editor, asked of the membership itself so a projection that has not\n * caught up cannot refuse the organization's own managers.\n */\n // \"Pause org automations on a site\" (AGL-4047): the site's stamp, else\n // the preset of the member's site role, the Admin and Editor this asked\n // for; or \"Manage org automations\" for a member of the whole workspace.\n let allowed = holdsStampedSiteKey(host, caller.uid, 'workflows.sitePause', WORKFLOWS_SITE_PAUSE_PRESET)\n if (!allowed) {\n const membership = await deps.resolveOrgMembership(caller.uid, orgId)\n const member = membership?.member\n allowed =\n Boolean(member) &&\n isOrgWideMember(member) &&\n (await deps.holdsOrgKey(orgId, member as Partial<AglynOrgMember>, 'workflows.orgAutomations'))\n }\n if (!allowed) {\n return res.status(403).json({ error: workflowsPermissionRefusal('workflows.sitePause') })\n }\n\n const name = await firestore.runTransaction(async (transaction) => {\n const ref = automationsOf(firestore, orgId).doc(automationId)\n const current = await transaction.get(ref)\n if (\n !current.exists ||\n current.get('deletedAt') ||\n !visibleToHost(current.get('visibleTo') as string[] | undefined, hostId)\n ) {\n return null\n }\n transaction.update(ref, {\n pausedHostIds: paused\n ? FieldValue.arrayUnion(hostId)\n : FieldValue.arrayRemove(hostId),\n })\n return String(current.get('name') ?? '')\n })\n if (name === null) {\n return res\n .status(404)\n .json({ error: 'No org automation by that id runs on this site' })\n }\n await deps.logHostActivity(\n hostId,\n { uid: caller.uid, email: caller.email ?? null },\n paused\n ? 'Paused an org automation on this site'\n : 'Resumed an org automation on this site',\n { type: 'workflow', id: automationId, name },\n )\n return res.status(200).json({ automationId, hostId, paused })\n } catch (error) {\n console.error('[org automations] pause failed', hostId, automationId, error)\n return res\n .status(500)\n .json({ error: 'The request could not be completed' })\n }\n }\n}\n\nexport const orgAutomationsManageHandler = createOrgAutomationsManageHandler()\nexport const orgAutomationPauseHandler = createOrgAutomationPauseHandler()\n"],"names":["createResourceUid","holdsStampedSiteKey","hostIdsFromScope","visibleToHost","isPluginEnabled","checkEntitlement","isOrgWideMember","planLabelGrantingFeature","isDocumentId","firebaseAdmin","getOrgDoc","logHostActivity","logOrgActivity","memberHasOrgPermission","resolveOrgIdForHost","resolveOrgMembership","FieldValue","BUNDLE_ID","WORKFLOWS_SITE_PAUSE_PRESET","workflowsPermissionRefusal","ORG_AUTOMATION_ACTIVITY_TARGET","ORG_AUTOMATION_API_ROUTES","ORG_AUTOMATIONS_COLLECTION","ORG_AUTOMATIONS_MAX","orgAutomationPausedHostIds","prunePausedHostIds","readOrgAutomation","ORG_AUTOMATION_MANAGE_ACTIONS","defaultDeps","firestore","app","verifyIdToken","token","decoded","auth","uid","email","orgId","holdsOrgKey","member","key","actor","action","target","hostId","newId","bearerToken","headers","authorization","String","startsWith","slice","length","automationsOf","collection","doc","placementIsTheOrgs","visibleTo","hostIds","every","entries","getAll","map","entry","exists","get","orgAutomationsManageSubject","request","method","body","json","catch","createOrgAutomationRecord","input","fields","ok","status","error","live","where","count","data","id","create","pausedHostIds","deletedAt","createdAt","serverTimestamp","createdBy","actorUid","updatedAt","updatedBy","updateOrgAutomationRecord","outcome","runTransaction","transaction","ref","current","update","deleteOrgAutomationRecord","name","again","deletedBy","enabled","createOrgAutomationsManageHandler","overrides","req","res","deps","includes","automationId","caller","membership","org","enabling","logged","verb","type","read","automation","problem","written","value","deleted","console","createOrgAutomationPauseHandler","paused","host","requestedOrgId","allowed","Boolean","arrayUnion","arrayRemove","orgAutomationsManageHandler","orgAutomationPauseHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,mBAAmB,QAAQ,0CAAyC;AAC7E,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,sCAAqC;AACrF,SAASC,eAAe,QAAQ,8CAA6C;AAC7E,SAEEC,gBAAgB,EAChBC,eAAe,EAGfC,wBAAwB,QACnB,sBAAqB;AAC5B;;;;CAIC,GACD,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,OAAOC,mBAAmB,iDAAgD;AAC1E,SACEC,SAAS,EACTC,eAAe,EACfC,cAAc,EACdC,sBAAsB,EACtBC,mBAAmB,EACnBC,oBAAoB,QACf,gDAA+C;AACtD,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,2BAA2B,EAC3BC,0BAA0B,QAErB,oCAAgC;AACvC,SACEC,8BAA8B,EAC9BC,yBAAyB,EACzBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,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,GAAG;gBAAEC,KAAK,GAAE2E,gBAAAA,OAAO3E,KAAK,YAAZ2E,gBAAgB;YAAK,GAC/Ce,SACI,0CACA,0CACJ;gBAAET,MAAM;gBAAYnC,IAAI4B;gBAAcV;YAAK;YAE7C,OAAOO,IAAI/B,MAAM,CAAC,KAAKN,IAAI,CAAC;gBAAEwC;gBAAclE;gBAAQkF;YAAO;QAC7D,EAAE,OAAOjD,OAAO;YACd+C,QAAQ/C,KAAK,CAAC,kCAAkCjC,QAAQkE,cAAcjC;YACtE,OAAO8B,IACJ/B,MAAM,CAAC,KACPN,IAAI,CAAC;gBAAEO,OAAO;YAAqC;QACxD;IACF;AACF;AAEA,OAAO,MAAMwD,8BAA8B7B,oCAAmC;AAC9E,OAAO,MAAM8B,4BAA4BT,kCAAiC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/server/org-automations-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * WRITING AN ORG AUTOMATION, and pausing one on a site (AGL-3302).\n *\n * `orgs/{orgId}/automations` is closed to every client write, the way the\n * outreach collections are: an org automation runs on every site it is\n * placed on, as that site, so its trigger, its steps and its placement are\n * decisions the server checks — the vocabulary, the organization's sites, the\n * plan — and nothing a browser may write around.\n *\n * ## Two doors\n *\n * `automations/manage` is the organization's: it creates, edits, switches on\n * and off, and deletes. It names the org and NO site, so it declares a\n * subject resolver for the dispatchers' release gate and asks the org's\n * plugin switch itself; the caller must be an org-wide owner, admin or\n * editor.\n *\n * `automations/pause` is the SITE's — the host level control. It names the\n * site, so the dispatcher applies that site's plugin switch as for any site\n * request, and it changes one thing: whether this automation is paused on\n * THIS site. The site's own admins and editors may use it, and so may an\n * org-wide editor; nobody may pause a site through it but the one named.\n */\n\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { holdsStampedSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport {\n hostIdsFromScope,\n sharingFromChoice,\n visibleToHost,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { isPluginEnabled } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\nimport {\n type AglynOrgMember,\n checkEntitlement,\n isOrgWideMember,\n type PluginApiHandler,\n type PluginApiRequestSubject,\n planLabelGrantingFeature,\n} from '@aglyn/aglyn/server'\n/*\n * The MODULES, not the barrel: `@aglyn/tenant-data-admin`'s index reaches the\n * Next render cache, and everything these doors need is the Admin SDK handle,\n * the id predicate and the org reads.\n */\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport firebaseAdmin from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport {\n getOrgDoc,\n logHostActivity,\n logOrgActivity,\n memberHasOrgPermission,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { fieldsToWrite, orgHostIdsFromDoc } from '@aglyn/tenant-data-admin/server/scope-sharing-sweep'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n WORKFLOWS_SITE_PAUSE_PRESET,\n workflowsPermissionRefusal,\n type WorkflowsPermission,\n} from '../model/workflows-permissions'\nimport {\n ORG_AUTOMATION_ACTIVITY_TARGET,\n ORG_AUTOMATION_API_ROUTES,\n ORG_AUTOMATIONS_COLLECTION,\n ORG_AUTOMATIONS_MAX,\n orgAutomationPausedHostIds,\n prunePausedHostIds,\n readOrgAutomation,\n type OrgAutomationFields,\n} from '../model/org-automations'\n\nexport { ORG_AUTOMATION_API_ROUTES }\n\n/** What `automations/manage` may be asked to do. */\nexport const ORG_AUTOMATION_MANAGE_ACTIONS = [\n 'create',\n 'update',\n 'setEnabled',\n 'delete',\n] as const\n\ntype ManageAction = (typeof ORG_AUTOMATION_MANAGE_ACTIONS)[number]\n\n\n/** What the doors reach outside this module; specs hand in their own. */\nexport interface OrgAutomationRouteDeps {\n firestore(): FirebaseFirestore.Firestore\n verifyIdToken(token: string): Promise<{ uid: string; email?: string | null }>\n resolveOrgMembership(\n uid: string,\n orgId: string,\n ): Promise<{ orgId: string; member: Partial<AglynOrgMember> } | null>\n getOrgDoc(orgId: string): Promise<Record<string, unknown> | null>\n resolveOrgIdForHost(hostId: string): Promise<string | null>\n /** Whether a member holds a workspace key with no site named (AGL-4047): `memberHasOrgPermission`. */\n holdsOrgKey(orgId: string, member: Partial<AglynOrgMember>, key: WorkflowsPermission): Promise<boolean>\n logOrgActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n action: string,\n target: { type: typeof ORG_AUTOMATION_ACTIVITY_TARGET; id: string; name?: string },\n ): Promise<void>\n logHostActivity(\n hostId: string,\n actor: { uid: string; email?: string | null },\n action: string,\n target: { type: 'workflow'; id: string; name?: string },\n ): Promise<void>\n newId(): string\n}\n\nfunction defaultDeps(): OrgAutomationRouteDeps {\n return {\n firestore: () =>\n firebaseAdmin.app().firestore() as unknown as FirebaseFirestore.Firestore,\n verifyIdToken: async (token) => {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(token)\n return { uid: decoded.uid, email: decoded.email ?? null }\n },\n resolveOrgMembership: async (uid, orgId) =>\n (await resolveOrgMembership(uid, orgId)) as never,\n getOrgDoc: async (orgId) =>\n ((await getOrgDoc(orgId)) as Record<string, unknown> | null) ?? null,\n resolveOrgIdForHost,\n holdsOrgKey: (orgId, member, key) => memberHasOrgPermission(orgId, member, key as never),\n logOrgActivity: (orgId, actor, action, target) =>\n logOrgActivity(orgId, actor, action, target),\n logHostActivity: (hostId, actor, action, target) =>\n logHostActivity(hostId, actor, action, target),\n newId: createResourceUid,\n }\n}\n\n/** The bearer token a request carries, or null. */\nfunction bearerToken(headers: Partial<Record<string, string | string[]>>): string | null {\n const authorization = String(headers['authorization'] ?? '')\n return authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length) || null\n : null\n}\n\nfunction automationsOf(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): FirebaseFirestore.CollectionReference {\n return firestore\n .collection('orgs')\n .doc(orgId)\n .collection(ORG_AUTOMATIONS_COLLECTION)\n}\n\n/**\n * Whether every site a placement names belongs to this organization — asked\n * of `hostIndex`, the mirror `resolveOrgIdForHost` reads, in one round trip.\n * `['org']` names no site and always answers yes.\n */\nasync function placementIsTheOrgs(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n visibleTo: readonly string[],\n): Promise<boolean> {\n const hostIds = hostIdsFromScope(visibleTo)\n if (!hostIds.length) return true\n if (!hostIds.every(isDocumentId)) return false\n const entries = await firestore.getAll(\n ...hostIds.map((hostId) => firestore.collection('hostIndex').doc(hostId)),\n )\n return entries.every((entry) => entry.exists && entry.get('orgId') === orgId)\n}\n\n/**\n * The organization a `automations/manage` request is for, read off its JSON\n * body, so the dispatchers' release gate asks about the right organization.\n * Consulted only for a request that names no site. Unverified, exactly as a\n * `hostId` is: the handler refuses anyone who is not an org-wide member.\n */\nexport async function orgAutomationsManageSubject(\n request: Request,\n): Promise<PluginApiRequestSubject | null> {\n if (request.method !== 'POST') return null\n const body = (await request.json().catch(() => null)) as {\n orgId?: unknown\n } | null\n const orgId = typeof body?.orgId === 'string' ? body.orgId : ''\n return isDocumentId(orgId) ? { orgId } : null\n}\n\n/** What writing an org automation came to: its id, or the refusal the route answers with. */\nexport type OrgAutomationWrite = { ok: true; id: string } | { ok: false; status: number; error: string }\n\n/**\n * Creates an org automation as `automations/manage` does: its sites must be\n * the organization's, and the organization holds at most\n * {@link ORG_AUTOMATIONS_MAX} live ones. The route and the package import\n * (AGL-3535) both create through here.\n */\n/** Two placements name the same sites, in any order. */\nfunction samePlacement(a: unknown, b: readonly string[]): boolean {\n const before = Array.isArray(a) ? new Set(a as string[]) : null\n return Boolean(before) && before?.size === new Set(b).size && b.every((token) => before?.has(token))\n}\n\n/**\n * What one write stores of where an automation runs (AGL-4047), inside the\n * write's transaction, or why it can't.\n *\n * All sites except some is worked out from the workspace's sites, read in the\n * same transaction: a site being created writes that document too, so it\n * either lands first and is on the list, or lands after and its sweep finds\n * this automation. A site left out that the workspace doesn't hold is dropped,\n * as the dataset route does: it may be one that has just gone.\n *\n * Any other placement removes a marker the automation carried, as a field\n * delete, when the editor chose it (`sharing` set) or the sites moved. A save\n * from a client that predates the choice, sending back the sites it was\n * shown, keeps the marker: it changed nothing about where it runs.\n */\nasync function placementToWrite(\n transaction: FirebaseFirestore.Transaction,\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n fields: OrgAutomationFields,\n current: Readonly<Record<string, unknown>> | undefined,\n): Promise<{ ok: true; data: Record<string, unknown>; visibleTo: string[] } | { ok: false; error: string }> {\n if (fields.sharing?.mode === 'allExcept') {\n const org = await transaction.get(firestore.collection('orgs').doc(orgId))\n const shared = sharingFromChoice(fields.sharing, orgHostIdsFromDoc(org.data()))\n if (!shared.fields) return { ok: false, error: shared.problem }\n return { ok: true, data: fieldsToWrite(shared.fields), visibleTo: shared.fields.visibleTo }\n }\n const marked = current?.['scopeMode'] !== undefined && current?.['scopeMode'] !== null\n if (!marked) return { ok: true, data: { visibleTo: fields.visibleTo }, visibleTo: fields.visibleTo }\n if (!fields.sharing && samePlacement(current?.['visibleTo'], fields.visibleTo)) {\n // Left exactly as the sweep keeps it.\n return { ok: true, data: {}, visibleTo: current?.['visibleTo'] as string[] }\n }\n return {\n ok: true,\n data: fieldsToWrite({ visibleTo: fields.visibleTo, scopeMode: null, scopeExcept: null }),\n visibleTo: fields.visibleTo,\n }\n}\n\n/** The fields a write stores beside its placement: never the choice itself. */\nfunction storedFieldsOf(fields: OrgAutomationFields): Omit<OrgAutomationFields, 'sharing' | 'visibleTo'> {\n return { name: fields.name, trigger: fields.trigger, steps: fields.steps, enabled: fields.enabled }\n}\n\nexport async function createOrgAutomationRecord(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; id: string; fields: OrgAutomationFields; actorUid: string },\n): Promise<OrgAutomationWrite> {\n if (!(await placementIsTheOrgs(firestore, input.orgId, input.fields.visibleTo))) {\n return { ok: false, status: 400, error: 'A site you chose is not in this organization' }\n }\n const collection = automationsOf(firestore, input.orgId)\n /*\n * Counted before the write rather than inside a transaction. The\n * cap bounds storage, not money, so the overshoot two simultaneous\n * saves can buy is one document — the trade the site actions cap\n * makes for the same reason.\n */\n const live = (await collection.where('deletedAt', '==', null).count().get()).data().count\n if (live >= ORG_AUTOMATIONS_MAX) {\n return {\n ok: false,\n status: 409,\n error: `An organization holds at most ${ORG_AUTOMATIONS_MAX} org automations — delete one you no longer use first`,\n }\n }\n const stamped = {\n pausedHostIds: [],\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n createdBy: input.actorUid,\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: input.actorUid,\n }\n if (input.fields.sharing?.mode === 'allExcept') {\n // The workspace's sites are read in the write's own transaction; see\n // `placementToWrite`. A new document carries no marker to remove.\n const error = await firestore.runTransaction(async (transaction) => {\n const placed = await placementToWrite(transaction, firestore, input.orgId, input.fields, undefined)\n if (placed.ok === false) return placed.error\n transaction.create(collection.doc(input.id), { ...storedFieldsOf(input.fields), ...placed.data, ...stamped })\n return null\n })\n return error ? { ok: false, status: 400, error } : { ok: true, id: input.id }\n }\n await collection.doc(input.id).create({\n ...storedFieldsOf(input.fields),\n visibleTo: input.fields.visibleTo,\n ...stamped,\n })\n return { ok: true, id: input.id }\n}\n\n/** Rewrites a live org automation as `automations/manage` does; a site it no longer runs on leaves its pause list. */\nexport async function updateOrgAutomationRecord(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; id: string; fields: OrgAutomationFields; actorUid: string },\n): Promise<OrgAutomationWrite> {\n if (!(await placementIsTheOrgs(firestore, input.orgId, input.fields.visibleTo))) {\n return { ok: false, status: 400, error: 'A site you chose is not in this organization' }\n }\n const collection = automationsOf(firestore, input.orgId)\n const outcome = await firestore.runTransaction(async (transaction) => {\n const ref = collection.doc(input.id)\n const current = await transaction.get(ref)\n if (!current.exists || current.get('deletedAt')) return { missing: true as const }\n const placed = await placementToWrite(transaction, firestore, input.orgId, input.fields, current.data())\n if (placed.ok === false) return { missing: false as const, error: placed.error }\n transaction.update(ref, {\n ...storedFieldsOf(input.fields),\n ...placed.data,\n // A site the automation no longer runs on has nothing left to\n // pause: its entry goes, so a later placement starts unpaused. That\n // includes a site left out of all sites except some (AGL-4047).\n pausedHostIds: prunePausedHostIds(orgAutomationPausedHostIds(current.data()), placed.visibleTo),\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: input.actorUid,\n })\n return { missing: false as const, error: null }\n })\n if (outcome.missing) return { ok: false, status: 404, error: 'Unknown org automation' }\n return outcome.error ? { ok: false, status: 400, error: outcome.error } : { ok: true, id: input.id }\n}\n\n/**\n * Deletes an org automation as `automations/manage` does — softly, switched\n * off (see the handler). `null` for one that does not exist; `again` for\n * one already deleted.\n */\nexport async function deleteOrgAutomationRecord(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; id: string; actorUid: string },\n): Promise<{ name: string; again: boolean } | null> {\n return firestore.runTransaction(async (transaction) => {\n const ref = automationsOf(firestore, input.orgId).doc(input.id)\n const current = await transaction.get(ref)\n if (!current.exists) return null\n // Deleting twice is the same request answered again.\n if (current.get('deletedAt')) return { name: '', again: true }\n transaction.update(ref, {\n deletedAt: FieldValue.serverTimestamp(),\n deletedBy: input.actorUid,\n // Off as well, so the engine's query — which asks for switched-on\n // automations only — never spends one of its places on it.\n enabled: false,\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: input.actorUid,\n })\n return { name: String(current.get('name') ?? ''), again: false }\n })\n}\n\n/**\n * `automations/manage`: create, edit, switch on or off, and delete one of the\n * organization's automations.\n *\n * A DELETE is soft — `deletedAt` stamped and the automation switched off —\n * because the id is what every run history row and every waiting person\n * names: the rows keep a name to show, and the people waiting inside it are\n * stopped by the resume's kill switch on their next beat. Deleting and\n * switching off are never refused for want of a plan, so an organization\n * that downgraded can always stop what it built.\n */\nexport function createOrgAutomationsManageHandler(\n overrides: Partial<OrgAutomationRouteDeps> = {},\n): PluginApiHandler {\n return async (req, res) => {\n const deps = { ...defaultDeps(), ...overrides }\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const orgId = String(req.body?.orgId ?? '')\n const action = String(req.body?.action ?? '') as ManageAction\n if (!isDocumentId(orgId)) {\n return res.status(400).json({ error: 'Invalid orgId' })\n }\n if (!(ORG_AUTOMATION_MANAGE_ACTIONS as readonly string[]).includes(action)) {\n return res.status(400).json({ error: 'Unknown action' })\n }\n const automationId = String(req.body?.automationId ?? '')\n if (action !== 'create' && !isDocumentId(automationId)) {\n return res.status(400).json({ error: 'Invalid automationId' })\n }\n const token = bearerToken(req.headers)\n if (!token) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const caller = await deps.verifyIdToken(token).catch(() => null)\n if (!caller) return res.status(401).json({ error: 'Unauthenticated' })\n const membership = await deps.resolveOrgMembership(caller.uid, orgId)\n const member = membership?.member\n // \"Manage org automations\" (AGL-4047), for members of the whole\n // workspace: its default is the owner, admins and editors this asked\n // for before, then their custom role and their own permissions.\n if (\n !member ||\n !isOrgWideMember(member) ||\n !(await deps.holdsOrgKey(orgId, member, 'workflows.orgAutomations'))\n ) {\n return res.status(403).json({ error: workflowsPermissionRefusal('workflows.orgAutomations') })\n }\n /*\n * A request naming no site reaches here past only the release gate —\n * the dispatcher's per-site switch needs a site — so the organization's\n * own switch is asked here.\n */\n const org = await deps.getOrgDoc(orgId)\n if (!org || !isPluginEnabled(org as never, BUNDLE_ID)) {\n return res.status(404).json({ error: 'Not found' })\n }\n const enabling =\n action === 'create' ||\n action === 'update' ||\n (action === 'setEnabled' && req.body?.enabled === true)\n if (enabling && !checkEntitlement(org as never, 'actions')) {\n return res.status(403).json({\n error: `Org automations need the ${planLabelGrantingFeature('actions') ?? 'Pro'} plan`,\n })\n }\n\n const firestore = deps.firestore()\n const collection = automationsOf(firestore, orgId)\n const actor = { uid: caller.uid, email: caller.email ?? null }\n const logged = (verb: string, id: string, name: string) =>\n deps.logOrgActivity(orgId, actor, verb, {\n type: ORG_AUTOMATION_ACTIVITY_TARGET,\n id,\n name,\n })\n\n if (action === 'create' || action === 'update') {\n const read = readOrgAutomation(req.body?.automation)\n if (read.ok === false) {\n return res.status(400).json({ error: read.problem })\n }\n const written =\n action === 'create'\n ? await createOrgAutomationRecord(firestore, { orgId, id: deps.newId(), fields: read.value, actorUid: caller.uid })\n : await updateOrgAutomationRecord(firestore, { orgId, id: automationId, fields: read.value, actorUid: caller.uid })\n if (written.ok === false) {\n return res.status(written.status).json({ error: written.error })\n }\n await logged(action === 'create' ? 'Created an org automation' : 'Edited an org automation', written.id, read.value.name)\n return res.status(200).json({ automationId: written.id })\n }\n\n if (action === 'setEnabled') {\n if (typeof req.body?.enabled !== 'boolean') {\n return res.status(400).json({ error: 'Say whether it is enabled' })\n }\n const enabled = req.body.enabled as boolean\n const name = await firestore.runTransaction(async (transaction) => {\n const ref = collection.doc(automationId)\n const current = await transaction.get(ref)\n if (!current.exists || current.get('deletedAt')) return null\n transaction.update(ref, {\n enabled,\n updatedAt: FieldValue.serverTimestamp(),\n updatedBy: caller.uid,\n })\n return String(current.get('name') ?? '')\n })\n if (name === null) {\n return res.status(404).json({ error: 'Unknown org automation' })\n }\n await logged(\n enabled ? 'Switched on an org automation' : 'Switched off an org automation',\n automationId,\n name,\n )\n return res.status(200).json({ automationId, enabled })\n }\n\n // delete\n const deleted = await deleteOrgAutomationRecord(firestore, { orgId, id: automationId, actorUid: caller.uid })\n if (!deleted) {\n return res.status(404).json({ error: 'Unknown org automation' })\n }\n if (!deleted.again) {\n await logged('Deleted an org automation', automationId, deleted.name)\n }\n return res.status(200).json({ automationId, deleted: true })\n } catch (error) {\n console.error('[org automations] manage failed', orgId, action, error)\n return res\n .status(500)\n .json({ error: 'The request could not be completed' })\n }\n }\n}\n\n/**\n * `automations/pause`: pause or resume one org automation on ONE site.\n *\n * `pausedHostIds` is changed with `arrayUnion`/`arrayRemove` of the named\n * site alone, inside a transaction that first confirms the automation runs\n * there — so a site's editor can take their own site out of an org\n * automation and put it back, and can never touch another site's entry or\n * the automation itself. Pausing stops the people already waiting inside it\n * on this site as well, on their next beat: the resume reads a pause as the\n * kill switch.\n *\n * Never refused for want of a plan: a pause is how a site stops something,\n * and stopping is always allowed.\n */\nexport function createOrgAutomationPauseHandler(\n overrides: Partial<OrgAutomationRouteDeps> = {},\n): PluginApiHandler {\n return async (req, res) => {\n const deps = { ...defaultDeps(), ...overrides }\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const automationId = String(req.body?.automationId ?? '')\n const paused = req.body?.paused\n if (!isDocumentId(hostId)) {\n return res.status(400).json({ error: 'Invalid hostId' })\n }\n if (!isDocumentId(automationId)) {\n return res.status(400).json({ error: 'Invalid automationId' })\n }\n if (typeof paused !== 'boolean') {\n return res.status(400).json({ error: 'Say whether it is paused' })\n }\n const token = bearerToken(req.headers)\n if (!token) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const caller = await deps.verifyIdToken(token).catch(() => null)\n if (!caller) return res.status(401).json({ error: 'Unauthenticated' })\n const firestore = deps.firestore()\n const host = await firestore.collection('hosts').doc(hostId).get()\n if (!host.exists) return res.status(404).json({ error: 'Unknown site' })\n const orgId = await deps.resolveOrgIdForHost(hostId)\n if (!orgId) {\n return res.status(409).json({\n error: 'This site is not part of an organization, so it runs no org automations.',\n })\n }\n const requestedOrgId = String(req.body?.orgId ?? '')\n if (requestedOrgId && requestedOrgId !== orgId) {\n return res.status(400).json({ error: 'That site is not in this organization' })\n }\n /*\n * The site's own admins and editors, read off the host's `memberRoles`\n * projection — the same answer every site door asks — or an org-wide\n * editor, asked of the membership itself so a projection that has not\n * caught up cannot refuse the organization's own managers.\n */\n // \"Pause org automations on a site\" (AGL-4047): the site's stamp, else\n // the preset of the member's site role, the Admin and Editor this asked\n // for; or \"Manage org automations\" for a member of the whole workspace.\n let allowed = holdsStampedSiteKey(host, caller.uid, 'workflows.sitePause', WORKFLOWS_SITE_PAUSE_PRESET)\n if (!allowed) {\n const membership = await deps.resolveOrgMembership(caller.uid, orgId)\n const member = membership?.member\n allowed =\n Boolean(member) &&\n isOrgWideMember(member) &&\n (await deps.holdsOrgKey(orgId, member as Partial<AglynOrgMember>, 'workflows.orgAutomations'))\n }\n if (!allowed) {\n return res.status(403).json({ error: workflowsPermissionRefusal('workflows.sitePause') })\n }\n\n const name = await firestore.runTransaction(async (transaction) => {\n const ref = automationsOf(firestore, orgId).doc(automationId)\n const current = await transaction.get(ref)\n if (\n !current.exists ||\n current.get('deletedAt') ||\n !visibleToHost(current.get('visibleTo') as string[] | undefined, hostId)\n ) {\n return null\n }\n transaction.update(ref, {\n pausedHostIds: paused\n ? FieldValue.arrayUnion(hostId)\n : FieldValue.arrayRemove(hostId),\n })\n return String(current.get('name') ?? '')\n })\n if (name === null) {\n return res\n .status(404)\n .json({ error: 'No org automation by that id runs on this site' })\n }\n await deps.logHostActivity(\n hostId,\n { uid: caller.uid, email: caller.email ?? null },\n paused\n ? 'Paused an org automation on this site'\n : 'Resumed an org automation on this site',\n { type: 'workflow', id: automationId, name },\n )\n return res.status(200).json({ automationId, hostId, paused })\n } catch (error) {\n console.error('[org automations] pause failed', hostId, automationId, error)\n return res\n .status(500)\n .json({ error: 'The request could not be completed' })\n }\n }\n}\n\nexport const orgAutomationsManageHandler = createOrgAutomationsManageHandler()\nexport const orgAutomationPauseHandler = createOrgAutomationPauseHandler()\n"],"names":["createResourceUid","holdsStampedSiteKey","hostIdsFromScope","sharingFromChoice","visibleToHost","isPluginEnabled","checkEntitlement","isOrgWideMember","planLabelGrantingFeature","isDocumentId","firebaseAdmin","getOrgDoc","logHostActivity","logOrgActivity","memberHasOrgPermission","resolveOrgIdForHost","resolveOrgMembership","fieldsToWrite","orgHostIdsFromDoc","FieldValue","BUNDLE_ID","WORKFLOWS_SITE_PAUSE_PRESET","workflowsPermissionRefusal","ORG_AUTOMATION_ACTIVITY_TARGET","ORG_AUTOMATION_API_ROUTES","ORG_AUTOMATIONS_COLLECTION","ORG_AUTOMATIONS_MAX","orgAutomationPausedHostIds","prunePausedHostIds","readOrgAutomation","ORG_AUTOMATION_MANAGE_ACTIONS","defaultDeps","firestore","app","verifyIdToken","token","decoded","auth","uid","email","orgId","holdsOrgKey","member","key","actor","action","target","hostId","newId","bearerToken","headers","authorization","String","startsWith","slice","length","automationsOf","collection","doc","placementIsTheOrgs","visibleTo","hostIds","every","entries","getAll","map","entry","exists","get","orgAutomationsManageSubject","request","method","body","json","catch","samePlacement","a","b","before","Array","isArray","Set","Boolean","size","has","placementToWrite","transaction","fields","current","sharing","mode","org","shared","data","ok","error","problem","marked","undefined","scopeMode","scopeExcept","storedFieldsOf","name","trigger","steps","enabled","createOrgAutomationRecord","input","status","live","where","count","stamped","pausedHostIds","deletedAt","createdAt","serverTimestamp","createdBy","actorUid","updatedAt","updatedBy","runTransaction","placed","create","id","updateOrgAutomationRecord","outcome","ref","missing","update","deleteOrgAutomationRecord","again","deletedBy","createOrgAutomationsManageHandler","overrides","req","res","deps","includes","automationId","caller","membership","enabling","logged","verb","type","read","automation","written","value","deleted","console","createOrgAutomationPauseHandler","paused","host","requestedOrgId","allowed","arrayUnion","arrayRemove","orgAutomationsManageHandler","orgAutomationPauseHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,mBAAmB,QAAQ,0CAAyC;AAC7E,SACEC,gBAAgB,EAChBC,i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