@aglyn/plugins-workflows 1.18.0 → 1.20.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.
@@ -33,7 +33,7 @@
33
33
  *=========================================*/ import { _ as _extends } from "@swc/helpers/_/_extends";
34
34
  import { remapPackageReference, TRANSFER_SITE_KIND } from "@aglyn/aglyn/data-transfer/package-plan";
35
35
  import { hostIdsFromScope, hostScopeToken, ORG_SCOPE_TOKEN } from "@aglyn/aglyn/app-utils/scope-tokens";
36
- import { readOrgAutomation } from "../model/org-automations.js";
36
+ import { orgAutomationStoredSharing, readOrgAutomation } from "../model/org-automations.js";
37
37
  /** The resource key, and so the kind every automation item carries. */ export const ORG_AUTOMATIONS_TRANSFER_KEY = 'workflows.org-automations';
38
38
  /** The kinds a step's references are named under. */ export const ORG_AUTOMATION_REFERENCE_KINDS = {
39
39
  list: 'email.lists',
@@ -73,20 +73,30 @@ import { readOrgAutomation } from "../model/org-automations.js";
73
73
  * by the save route's own reader — so an item the reader refuses is `null`
74
74
  * here and a problem at the dry run.
75
75
  */ export function orgAutomationPackageContent(source) {
76
- const read = readOrgAutomation(source);
76
+ /*
77
+ * A stored automation that runs on all sites except some carries that as the
78
+ * sweep's marker, never as `sharing`. The package says it as the choice
79
+ * (AGL-4047), so an import works the sites out from the workspace it lands
80
+ * in, and a new site there gets it as it would here.
81
+ */ const stored = source && typeof source === 'object' && !('sharing' in source) ? orgAutomationStoredSharing(source) : null;
82
+ const read = readOrgAutomation(stored ? _extends({}, source, {
83
+ sharing: stored
84
+ }) : source);
77
85
  if (read.ok === false) return null;
78
- const { name, trigger, steps, visibleTo } = read.value;
79
- return {
86
+ const { name, trigger, steps, visibleTo, sharing } = read.value;
87
+ return _extends({
80
88
  name,
81
89
  trigger,
82
90
  steps,
83
91
  visibleTo
84
- };
92
+ }, (sharing == null ? void 0 : sharing.mode) === 'allExcept' ? {
93
+ sharing
94
+ } : {});
85
95
  }
86
96
  /** The incoming content as stored, before it is judged: whatever the file holds, shaped like an automation. */ export function rawOrgAutomationContent(source) {
87
97
  var _raw_name, _raw_trigger;
88
98
  const raw = source && typeof source === 'object' ? source : {};
89
- return {
99
+ return _extends({
90
100
  name: String((_raw_name = raw.name) != null ? _raw_name : ''),
91
101
  trigger: (_raw_trigger = raw.trigger) != null ? _raw_trigger : {
92
102
  event: '',
@@ -95,7 +105,13 @@ import { readOrgAutomation } from "../model/org-automations.js";
95
105
  },
96
106
  steps: Array.isArray(raw.steps) ? raw.steps : [],
97
107
  visibleTo: Array.isArray(raw.visibleTo) ? raw.visibleTo : []
98
- };
108
+ }, raw.sharing ? {
109
+ sharing: raw.sharing
110
+ } : {});
111
+ }
112
+ /** The sites an all-sites-except automation leaves out, or none. */ function exceptHostIdsOf(content) {
113
+ var _content_sharing;
114
+ return ((_content_sharing = content.sharing) == null ? void 0 : _content_sharing.mode) === 'allExcept' ? content.sharing.exceptHostIds : [];
99
115
  }
100
116
  export function orgAutomationDependencies(content) {
101
117
  var _content_steps;
@@ -110,6 +126,7 @@ export function orgAutomationDependencies(content) {
110
126
  });
111
127
  };
112
128
  for (const hostId of hostIdsFromScope(content.visibleTo))add(TRANSFER_SITE_KIND, hostId);
129
+ for (const hostId of exceptHostIdsOf(content))add(TRANSFER_SITE_KIND, hostId);
113
130
  for (const step of (_content_steps = content.steps) != null ? _content_steps : []){
114
131
  for (const { field, kind } of STEP_REFERENCES)add(kind, step[field]);
115
132
  }
@@ -121,6 +138,7 @@ export function orgAutomationDependencies(content) {
121
138
  * its name (see the block header).
122
139
  */ export function remapOrgAutomationIds(content, idMap) {
123
140
  var _content_steps;
141
+ var _content_sharing;
124
142
  const visibleTo = content.visibleTo.flatMap((token)=>{
125
143
  if (token === ORG_SCOPE_TOKEN) return [
126
144
  token
@@ -146,10 +164,25 @@ export function orgAutomationDependencies(content) {
146
164
  }
147
165
  return record;
148
166
  });
167
+ /*
168
+ * A site left out that the plan drops stays out of nothing: it is not
169
+ * there. If none is left, the reader refuses it rather than run it on
170
+ * every site (AGL-4047).
171
+ */ const sharing = ((_content_sharing = content.sharing) == null ? void 0 : _content_sharing.mode) === 'allExcept' ? {
172
+ sharing: {
173
+ mode: 'allExcept',
174
+ exceptHostIds: exceptHostIdsOf(content).flatMap((hostId)=>{
175
+ const mapped = remapPackageReference(idMap, TRANSFER_SITE_KIND, hostId);
176
+ return mapped ? [
177
+ mapped
178
+ ] : [];
179
+ })
180
+ }
181
+ } : {};
149
182
  return _extends({}, content, {
150
183
  visibleTo: visibleTo,
151
184
  steps
152
- });
185
+ }, sharing);
153
186
  }
154
187
  export const ORG_AUTOMATION_PACKAGE_RULES = [
155
188
  {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/transfer/org-automations-package.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 * ORG AUTOMATIONS AS PACKAGE ITEMS (AGL-3535).\n *\n * An item is what an org automation does: its name, trigger, steps and\n * the sites it runs on. Never whether it is switched on, which sites\n * paused it, or who wrote it — so one exported and imported back is\n * `identical`, and an import never switches anything on.\n *\n * What it names: its sites (`site`), and what its steps reach — an email\n * list, a campaign, a dataset, a subscription topic, a member who owns or\n * is assigned. A step names a list, a campaign and a dataset by id AND by\n * name, and the engine finds one by its name when the id is empty — so a\n * dropped reference clears the id and keeps the name, and the step finds\n * the workspace's own list of that name when it runs.\n *\n * Pure: the server half (`org-automations-package.server.ts`) reads and\n * writes.\n *=========================================*/\n\nimport type { PackageDependency } from '@aglyn/aglyn/data-transfer/package'\nimport { remapPackageReference, TRANSFER_SITE_KIND } from '@aglyn/aglyn/data-transfer/package-plan'\nimport { hostIdsFromScope, hostScopeToken, ORG_SCOPE_TOKEN } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { readOrgAutomation, type OrgAutomationFields } from '../model/org-automations'\n\n/** The resource key, and so the kind every automation item carries. */\nexport const ORG_AUTOMATIONS_TRANSFER_KEY = 'workflows.org-automations'\n\n/** The kinds a step's references are named under. */\nexport const ORG_AUTOMATION_REFERENCE_KINDS = {\n list: 'email.lists',\n campaign: 'marketing.campaigns',\n dataset: 'data.datasets',\n topic: 'email.topics',\n member: 'member',\n} as const\n\n/** An org automation as a package carries it. */\nexport type OrgAutomationPackageContent = Omit<OrgAutomationFields, 'enabled'>\n\ntype StepRecord = Record<string, unknown>\n\n/** Each step field that names something, with the kind it names. */\nconst STEP_REFERENCES: ReadonlyArray<{ field: string; kind: string }> = [\n { field: 'listId', kind: ORG_AUTOMATION_REFERENCE_KINDS.list },\n { field: 'campaignId', kind: ORG_AUTOMATION_REFERENCE_KINDS.campaign },\n { field: 'datasetId', kind: ORG_AUTOMATION_REFERENCE_KINDS.dataset },\n { field: 'topicId', kind: ORG_AUTOMATION_REFERENCE_KINDS.topic },\n { field: 'ownerUid', kind: ORG_AUTOMATION_REFERENCE_KINDS.member },\n { field: 'assigneeUid', kind: ORG_AUTOMATION_REFERENCE_KINDS.member },\n]\n\n/**\n * The package content of a stored automation, or of an incoming item, read\n * by the save route's own reader — so an item the reader refuses is `null`\n * here and a problem at the dry run.\n */\nexport function orgAutomationPackageContent(source: unknown): OrgAutomationPackageContent | null {\n const read = readOrgAutomation(source)\n if (read.ok === false) return null\n const { name, trigger, steps, visibleTo } = read.value\n return { name, trigger, steps, visibleTo }\n}\n\n/** The incoming content as stored, before it is judged: whatever the file holds, shaped like an automation. */\nexport function rawOrgAutomationContent(source: unknown): OrgAutomationPackageContent {\n const raw = (source && typeof source === 'object' ? source : {}) as Partial<OrgAutomationPackageContent>\n return {\n name: String(raw.name ?? ''),\n trigger: (raw.trigger ?? { event: '', conditions: null, combinator: null }) as OrgAutomationPackageContent['trigger'],\n steps: Array.isArray(raw.steps) ? raw.steps : [],\n visibleTo: Array.isArray(raw.visibleTo) ? raw.visibleTo : [],\n }\n}\n\nexport function orgAutomationDependencies(content: OrgAutomationPackageContent): PackageDependency[] {\n const deps: PackageDependency[] = []\n const seen = new Set<string>()\n const add = (kind: string, id: unknown) => {\n if (typeof id !== 'string' || !id.trim() || seen.has(`${kind}/${id}`)) return\n seen.add(`${kind}/${id}`)\n deps.push({ kind, id })\n }\n for (const hostId of hostIdsFromScope(content.visibleTo)) add(TRANSFER_SITE_KIND, hostId)\n for (const step of content.steps ?? []) {\n for (const { field, kind } of STEP_REFERENCES) add(kind, (step as unknown as StepRecord)[field])\n }\n return deps\n}\n\n/**\n * The automation with every reference moved through `idMap`. A dropped site\n * leaves the placement; a dropped step reference clears its id and keeps\n * its name (see the block header).\n */\nexport function remapOrgAutomationIds(\n content: OrgAutomationPackageContent,\n idMap: ReadonlyMap<string, string>,\n): OrgAutomationPackageContent {\n const visibleTo = content.visibleTo.flatMap((token) => {\n if (token === ORG_SCOPE_TOKEN) return [token]\n const [hostId] = hostIdsFromScope([token])\n if (!hostId) return [token]\n const mapped = remapPackageReference(idMap, TRANSFER_SITE_KIND, hostId)\n return mapped ? [hostScopeToken(mapped)] : []\n })\n const steps = (content.steps ?? []).map((step) => {\n const record = { ...(step as unknown as StepRecord) }\n for (const { field, kind } of STEP_REFERENCES) {\n const id = record[field]\n if (typeof id !== 'string' || !id) continue\n record[field] = remapPackageReference(idMap, kind, id) ?? ''\n }\n return record as unknown as OrgAutomationPackageContent['steps'][number]\n })\n return { ...content, visibleTo: visibleTo as OrgAutomationPackageContent['visibleTo'], steps }\n}\n\nexport const ORG_AUTOMATION_PACKAGE_RULES = [\n {\n id: 'off',\n label: 'An imported automation arrives switched off',\n reason:\n 'An automation acts on every site it runs on the moment it is on, so an import never switches one on. One you replace keeps whether it was on.',\n },\n {\n id: 'pauses',\n label: 'Each site’s own pause stays',\n reason: 'Pausing an automation is a site’s own decision, so a replace keeps the sites that paused it, and nothing about pausing travels in a package.',\n },\n] as const\n"],"names":["remapPackageReference","TRANSFER_SITE_KIND","hostIdsFromScope","hostScopeToken","ORG_SCOPE_TOKEN","readOrgAutomation","ORG_AUTOMATIONS_TRANSFER_KEY","ORG_AUTOMATION_REFERENCE_KINDS","list","campaign","dataset","topic","member","STEP_REFERENCES","field","kind","orgAutomationPackageContent","source","read","ok","name","trigger","steps","visibleTo","value","rawOrgAutomationContent","raw","String","event","conditions","combinator","Array","isArray","orgAutomationDependencies","content","deps","seen","Set","add","id","trim","has","push","hostId","step","remapOrgAutomationIds","idMap","flatMap","token","mapped","map","record","ORG_AUTOMATION_PACKAGE_RULES","label","reason"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;2CAiB2C;AAG3C,SAASA,qBAAqB,EAAEC,kBAAkB,QAAQ,0CAAyC;AACnG,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,eAAe,QAAQ,sCAAqC;AACvG,SAASC,iBAAiB,QAAkC,8BAA0B;AAEtF,qEAAqE,GACrE,OAAO,MAAMC,+BAA+B,4BAA2B;AAEvE,mDAAmD,GACnD,OAAO,MAAMC,iCAAiC;IAC5CC,MAAM;IACNC,UAAU;IACVC,SAAS;IACTC,OAAO;IACPC,QAAQ;AACV,EAAU;AAOV,kEAAkE,GAClE,MAAMC,kBAAkE;IACtE;QAAEC,OAAO;QAAUC,MAAMR,+BAA+BC,IAAI;IAAC;IAC7D;QAAEM,OAAO;QAAcC,MAAMR,+BAA+BE,QAAQ;IAAC;IACrE;QAAEK,OAAO;QAAaC,MAAMR,+BAA+BG,OAAO;IAAC;IACnE;QAAEI,OAAO;QAAWC,MAAMR,+BAA+BI,KAAK;IAAC;IAC/D;QAAEG,OAAO;QAAYC,MAAMR,+BAA+BK,MAAM;IAAC;IACjE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flows/src/lib/transfer/org-automations-package.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 * ORG AUTOMATIONS AS PACKAGE ITEMS (AGL-3535).\n *\n * An item is what an org automation does: its name, trigger, steps and\n * the sites it runs on. Never whether it is switched on, which sites\n * paused it, or who wrote it — so one exported and imported back is\n * `identical`, and an import never switches anything on.\n *\n * What it names: its sites (`site`), and what its steps reach — an email\n * list, a campaign, a dataset, a subscription topic, a member who owns or\n * is assigned. A step names a list, a campaign and a dataset by id AND by\n * name, and the engine finds one by its name when the id is empty — so a\n * dropped reference clears the id and keeps the name, and the step finds\n * the workspace's own list of that name when it runs.\n *\n * Pure: the server half (`org-automations-package.server.ts`) reads and\n * writes.\n *=========================================*/\n\nimport type { PackageDependency } from '@aglyn/aglyn/data-transfer/package'\nimport { remapPackageReference, TRANSFER_SITE_KIND } from '@aglyn/aglyn/data-transfer/package-plan'\nimport { hostIdsFromScope, hostScopeToken, ORG_SCOPE_TOKEN } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n orgAutomationStoredSharing,\n readOrgAutomation,\n type OrgAutomationFields,\n} from '../model/org-automations'\n\n/** The resource key, and so the kind every automation item carries. */\nexport const ORG_AUTOMATIONS_TRANSFER_KEY = 'workflows.org-automations'\n\n/** The kinds a step's references are named under. */\nexport const ORG_AUTOMATION_REFERENCE_KINDS = {\n list: 'email.lists',\n campaign: 'marketing.campaigns',\n dataset: 'data.datasets',\n topic: 'email.topics',\n member: 'member',\n} as const\n\n/** An org automation as a package carries it. */\nexport type OrgAutomationPackageContent = Omit<OrgAutomationFields, 'enabled'>\n\ntype StepRecord = Record<string, unknown>\n\n/** Each step field that names something, with the kind it names. */\nconst STEP_REFERENCES: ReadonlyArray<{ field: string; kind: string }> = [\n { field: 'listId', kind: ORG_AUTOMATION_REFERENCE_KINDS.list },\n { field: 'campaignId', kind: ORG_AUTOMATION_REFERENCE_KINDS.campaign },\n { field: 'datasetId', kind: ORG_AUTOMATION_REFERENCE_KINDS.dataset },\n { field: 'topicId', kind: ORG_AUTOMATION_REFERENCE_KINDS.topic },\n { field: 'ownerUid', kind: ORG_AUTOMATION_REFERENCE_KINDS.member },\n { field: 'assigneeUid', kind: ORG_AUTOMATION_REFERENCE_KINDS.member },\n]\n\n/**\n * The package content of a stored automation, or of an incoming item, read\n * by the save route's own reader — so an item the reader refuses is `null`\n * here and a problem at the dry run.\n */\nexport function orgAutomationPackageContent(source: unknown): OrgAutomationPackageContent | null {\n /*\n * A stored automation that runs on all sites except some carries that as the\n * sweep's marker, never as `sharing`. The package says it as the choice\n * (AGL-4047), so an import works the sites out from the workspace it lands\n * in, and a new site there gets it as it would here.\n */\n const stored = source && typeof source === 'object' && !('sharing' in source)\n ? orgAutomationStoredSharing(source as Record<string, unknown>)\n : null\n const read = readOrgAutomation(stored ? { ...(source as Record<string, unknown>), sharing: stored } : source)\n if (read.ok === false) return null\n const { name, trigger, steps, visibleTo, sharing } = read.value\n return { name, trigger, steps, visibleTo, ...(sharing?.mode === 'allExcept' ? { sharing } : {}) }\n}\n\n/** The incoming content as stored, before it is judged: whatever the file holds, shaped like an automation. */\nexport function rawOrgAutomationContent(source: unknown): OrgAutomationPackageContent {\n const raw = (source && typeof source === 'object' ? source : {}) as Partial<OrgAutomationPackageContent>\n return {\n name: String(raw.name ?? ''),\n trigger: (raw.trigger ?? { event: '', conditions: null, combinator: null }) as OrgAutomationPackageContent['trigger'],\n steps: Array.isArray(raw.steps) ? raw.steps : [],\n visibleTo: Array.isArray(raw.visibleTo) ? raw.visibleTo : [],\n ...(raw.sharing ? { sharing: raw.sharing } : {}),\n }\n}\n\n/** The sites an all-sites-except automation leaves out, or none. */\nfunction exceptHostIdsOf(content: OrgAutomationPackageContent): readonly string[] {\n return content.sharing?.mode === 'allExcept' ? content.sharing.exceptHostIds : []\n}\n\nexport function orgAutomationDependencies(content: OrgAutomationPackageContent): PackageDependency[] {\n const deps: PackageDependency[] = []\n const seen = new Set<string>()\n const add = (kind: string, id: unknown) => {\n if (typeof id !== 'string' || !id.trim() || seen.has(`${kind}/${id}`)) return\n seen.add(`${kind}/${id}`)\n deps.push({ kind, id })\n }\n for (const hostId of hostIdsFromScope(content.visibleTo)) add(TRANSFER_SITE_KIND, hostId)\n for (const hostId of exceptHostIdsOf(content)) add(TRANSFER_SITE_KIND, hostId)\n for (const step of content.steps ?? []) {\n for (const { field, kind } of STEP_REFERENCES) add(kind, (step as unknown as StepRecord)[field])\n }\n return deps\n}\n\n/**\n * The automation with every reference moved through `idMap`. A dropped site\n * leaves the placement; a dropped step reference clears its id and keeps\n * its name (see the block header).\n */\nexport function remapOrgAutomationIds(\n content: OrgAutomationPackageContent,\n idMap: ReadonlyMap<string, string>,\n): OrgAutomationPackageContent {\n const visibleTo = content.visibleTo.flatMap((token) => {\n if (token === ORG_SCOPE_TOKEN) return [token]\n const [hostId] = hostIdsFromScope([token])\n if (!hostId) return [token]\n const mapped = remapPackageReference(idMap, TRANSFER_SITE_KIND, hostId)\n return mapped ? [hostScopeToken(mapped)] : []\n })\n const steps = (content.steps ?? []).map((step) => {\n const record = { ...(step as unknown as StepRecord) }\n for (const { field, kind } of STEP_REFERENCES) {\n const id = record[field]\n if (typeof id !== 'string' || !id) continue\n record[field] = remapPackageReference(idMap, kind, id) ?? ''\n }\n return record as unknown as OrgAutomationPackageContent['steps'][number]\n })\n /*\n * A site left out that the plan drops stays out of nothing: it is not\n * there. If none is left, the reader refuses it rather than run it on\n * every site (AGL-4047).\n */\n const sharing =\n content.sharing?.mode === 'allExcept'\n ? {\n sharing: {\n mode: 'allExcept' as const,\n exceptHostIds: exceptHostIdsOf(content).flatMap((hostId) => {\n const mapped = remapPackageReference(idMap, TRANSFER_SITE_KIND, hostId)\n return mapped ? [mapped] : []\n }),\n },\n }\n : {}\n return { ...content, visibleTo: visibleTo as OrgAutomationPackageContent['visibleTo'], steps, ...sharing }\n}\n\nexport const ORG_AUTOMATION_PACKAGE_RULES = [\n {\n id: 'off',\n label: 'An imported automation arrives switched off',\n reason:\n 'An automation acts on every site it runs on the moment it is on, so an import never switches one on. One you replace keeps whether it was on.',\n },\n {\n id: 'pauses',\n label: 'Each site’s own pause stays',\n reason: 'Pausing an automation is a site’s own decision, so a replace keeps the sites that paused it, and nothing about pausing travels in a package.',\n },\n] as const\n"],"names":["remapPackageReference","TRANSFER_SITE_KIND","hostIdsFromScope","hostScopeToken","ORG_SCOPE_TOKEN","orgAutomationStoredSharing","readOrgAutomation","ORG_AUTOMATIONS_TRANSFER_KEY","ORG_AUTOMATION_REFERENCE_KINDS","list","campaign","dataset","topic","member","STEP_REFERENCES","field","kind","orgAutomationPackageContent","source","stored","read","sharing","ok","name","trigger","steps","visibleTo","value","mode","rawOrgAutomationContent","raw","String","event","conditions","combinator","Array","isArray","exceptHostIdsOf","content","exceptHostIds","orgAutomationDependencies","deps","seen","Set","add","id","trim","has","push","hostId","step","remapOrgAutomationIds","idMap","flatMap","token","mapped","map","record","ORG_AUTOMATION_PACKAGE_RULES","label","reason"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;2CAiB2C;AAG3C,SAASA,qBAAqB,EAAEC,kBAAkB,QAAQ,0CAAyC;AACnG,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,eAAe,QAAQ,sCAAqC;AACvG,SACEC,0BAA0B,EAC1BC,iBAAiB,QAEZ,8BAA0B;AAEjC,qEAAqE,GACrE,OAAO,MAAMC,+BAA+B,4BAA2B;AAEvE,mDAAmD,GACnD,OAAO,MAAMC,iCAAiC;IAC5CC,MA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} from "@swc/helpers/_/_extends";
25
25
  * running Workflows on a plan with org automations — so an import can do
26
26
  * nothing that door would refuse. A new automation lands switched off; a
27
27
  * replaced one keeps whether it was on.
28
- *=========================================*/ import { DECLARED_SUBSCRIPTION_TOPICS } from "@aglyn/aglyn/app-utils/subscription-topics";
28
+ *=========================================*/ import { hostIdsFromScope, isOrgWideScope } from "@aglyn/aglyn/app-utils/scope-tokens";
29
+ import { DECLARED_SUBSCRIPTION_TOPICS } from "@aglyn/aglyn/app-utils/subscription-topics";
29
30
  import { existingPackageItemsOf } from "@aglyn/aglyn/data-transfer";
30
31
  import { isPluginEnabled } from "@aglyn/aglyn/plugin-manager/enabled-plugins";
31
32
  import { checkEntitlement, isOrgWideMember, planLabelGrantingFeature } from "@aglyn/aglyn/server";
@@ -90,10 +91,23 @@ async function readAll(deps, orgId, ids) {
90
91
  ] : [];
91
92
  });
92
93
  }
93
- /** The fields one write stores: the content, read by the route's reader, switched on only if it already was. */ function fieldsOf(content, name, enabled) {
94
+ /**
95
+ * The fields one write stores: the content, read by the route's reader, switched on only if it already was.
96
+ *
97
+ * The package's placement is said as a choice (AGL-4047), so a replace puts the automation where the package
98
+ * says, and takes off a marker the one it replaces carried, even when the sites happen to match.
99
+ */ function fieldsOf(content, name, enabled) {
100
+ var _content_sharing;
101
+ const sharing = (_content_sharing = content.sharing) != null ? _content_sharing : isOrgWideScope(content.visibleTo) ? {
102
+ mode: 'all'
103
+ } : {
104
+ mode: 'selected',
105
+ hostIds: hostIdsFromScope(content.visibleTo)
106
+ };
94
107
  return readOrgAutomation(_extends({}, content, {
95
108
  name,
96
- enabled
109
+ enabled,
110
+ sharing
97
111
  }));
98
112
  }
99
113
  export function createOrgAutomationsPackage(deps = defaultDeps()) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/transfer/org-automations-package.server.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 * ORG AUTOMATIONS IN A WORKSPACE PACKAGE — the server half (AGL-3535).\n *\n * Written through `automations/manage`'s own writes\n * (`createOrgAutomationRecord`, `updateOrgAutomationRecord`,\n * `deleteOrgAutomationRecord`): its reader, its placement check, its cap,\n * its soft delete and its activity lines. The importer is held to that\n * door's rules too — an org-wide owner, admin or editor, in a workspace\n * running Workflows on a plan with org automations — so an import can do\n * nothing that door would refuse. A new automation lands switched off; a\n * replaced one keeps whether it was on.\n *=========================================*/\n\nimport { DECLARED_SUBSCRIPTION_TOPICS } from '@aglyn/aglyn/app-utils/subscription-topics'\nimport { existingPackageItemsOf, type ExistingPackageItem, type TransferReferenceKind, type TransferRowResult } from '@aglyn/aglyn/data-transfer'\nimport { isPluginEnabled } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\nimport type {\n TransferApplyResult,\n TransferApplyWriter,\n TransferPackageItemContent,\n TransferPackageItemWrite,\n TransferPackageRevertResult,\n TransferPackageRevertStep,\n TransferResourceContext,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { checkEntitlement, isOrgWideMember, planLabelGrantingFeature } from '@aglyn/aglyn/server'\nimport firebaseAdmin from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport {\n getOrgDoc,\n logOrgActivity,\n memberHasOrgPermission,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { workflowsPermissionRefusal } from '../model/workflows-permissions'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n ORG_AUTOMATION_ACTIVITY_TARGET,\n ORG_AUTOMATIONS_COLLECTION,\n ORG_AUTOMATIONS_MAX,\n readOrgAutomation,\n} from '../model/org-automations'\nimport {\n createOrgAutomationRecord,\n deleteOrgAutomationRecord,\n updateOrgAutomationRecord,\n} from '../server/org-automations-routes'\nimport {\n ORG_AUTOMATION_REFERENCE_KINDS,\n ORG_AUTOMATIONS_TRANSFER_KEY,\n orgAutomationPackageContent,\n rawOrgAutomationContent,\n type OrgAutomationPackageContent,\n} from './org-automations-package'\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface OrgAutomationsPackageDeps {\n firestore(): Firestore\n readOrg(orgId: string): Promise<Record<string, unknown> | null>\n memberOf(uid: string, orgId: string): Promise<Record<string, unknown> | null>\n /** Whether a member holds \"Manage org automations\" (AGL-4047): `memberHasOrgPermission`. */\n holdsOrgAutomations(orgId: string, member: Record<string, unknown>): Promise<boolean>\n logOrgActivity(orgId: string, uid: string, action: string, target: { id: string; name: string }): Promise<void>\n}\n\nfunction defaultDeps(): OrgAutomationsPackageDeps {\n return {\n firestore: () => firebaseAdmin.app().firestore() as unknown as Firestore,\n readOrg: async (orgId) => ((await getOrgDoc(orgId)) as Record<string, unknown> | null) ?? null,\n memberOf: async (uid, orgId) => ((await resolveOrgMembership(uid, orgId))?.member as Record<string, unknown> | undefined) ?? null,\n holdsOrgAutomations: (orgId, member) => memberHasOrgPermission(orgId, member as never, 'workflows.orgAutomations' as never),\n logOrgActivity: (orgId, uid, action, target) =>\n logOrgActivity(orgId, { uid, email: null }, action, { type: ORG_AUTOMATION_ACTIVITY_TARGET, ...target }),\n }\n}\n\nconst automationsOf = (firestore: Firestore, orgId: string) =>\n firestore.collection('orgs').doc(orgId).collection(ORG_AUTOMATIONS_COLLECTION)\n\n/** Why `automations/manage` would refuse this importer, or `null` when it would not. */\nasync function importerRefusal(deps: OrgAutomationsPackageDeps, ctx: TransferResourceContext): Promise<string | null> {\n if (!ctx.actorUid) return 'Org automations are imported by a member of the organization.'\n const member = await deps.memberOf(ctx.actorUid, ctx.orgId)\n // \"Manage org automations\" (AGL-4047), for members of the whole workspace,\n // as `automations/manage` asks it.\n if (!member || !isOrgWideMember(member as never) || !(await deps.holdsOrgAutomations(ctx.orgId, member))) {\n return workflowsPermissionRefusal('workflows.orgAutomations')\n }\n const org = await deps.readOrg(ctx.orgId)\n if (!org || !isPluginEnabled(org as never, BUNDLE_ID)) return 'Workflows is not on for this workspace.'\n if (!checkEntitlement(org as never, 'actions')) {\n return `Org automations need the ${planLabelGrantingFeature('actions') ?? 'Pro'} plan.`\n }\n return null\n}\n\nasync function readAll(\n deps: OrgAutomationsPackageDeps,\n orgId: string,\n ids?: readonly string[],\n): Promise<Array<TransferPackageItemContent<OrgAutomationPackageContent>>> {\n const collection = automationsOf(deps.firestore(), orgId)\n const docs = ids\n ? (await Promise.all(ids.map((id) => collection.doc(id).get()))).filter((doc) => doc.exists)\n : (await collection.where('deletedAt', '==', null).get()).docs\n return docs.flatMap((doc) => {\n if (doc.get('deletedAt')) return []\n const content = orgAutomationPackageContent(doc.data())\n return content ? [{ kind: ORG_AUTOMATIONS_TRANSFER_KEY, id: doc.id, name: content.name, content }] : []\n })\n}\n\n/** The fields one write stores: the content, read by the route's reader, switched on only if it already was. */\nfunction fieldsOf(content: OrgAutomationPackageContent, name: string, enabled: boolean) {\n return readOrgAutomation({ ...content, name, enabled })\n}\n\nexport function createOrgAutomationsPackage(deps: OrgAutomationsPackageDeps = defaultDeps()) {\n /** Whether the automation is on now; a new one is off. */\n const enabledNow = async (orgId: string, id: string) =>\n (await automationsOf(deps.firestore(), orgId).doc(id).get()).get('enabled') === true\n\n return {\n async items(ctx: TransferResourceContext): Promise<ExistingPackageItem[]> {\n return existingPackageItemsOf(ORG_AUTOMATIONS_TRANSFER_KEY, await readAll(deps, ctx.orgId))\n },\n\n async readItems(ctx: TransferResourceContext, ids: readonly string[]) {\n return readAll(deps, ctx.orgId, ids)\n },\n\n async problems(ctx: TransferResourceContext, write: TransferPackageItemWrite<OrgAutomationPackageContent>) {\n const refusal = await importerRefusal(deps, ctx)\n if (refusal) return [refusal]\n const content = rawOrgAutomationContent(write.content)\n const read = fieldsOf(content, write.rename?.name ?? content.name, false)\n if (read.ok === false) return [read.problem]\n const problems: string[] = []\n if (write.decision !== 'replace') {\n const collection = automationsOf(deps.firestore(), ctx.orgId)\n if ((await collection.doc(write.targetId).get()).exists) {\n problems.push('An automation with this id was deleted from this workspace, so it cannot come back under it.')\n }\n const live = (await collection.where('deletedAt', '==', null).count().get()).data().count\n if (live >= ORG_AUTOMATIONS_MAX) {\n problems.push(`An organization holds at most ${ORG_AUTOMATIONS_MAX} org automations — delete one you no longer use first.`)\n }\n }\n return problems\n },\n\n async referenceTargets(ctx: TransferResourceContext, kinds: readonly string[]): Promise<TransferReferenceKind[]> {\n const org = deps.firestore().collection('orgs').doc(ctx.orgId)\n const named = async (collection: string, field: string) =>\n (await org.collection(collection).get()).docs\n .filter((doc) => !doc.get('deletedAt'))\n .map((doc) => {\n const name = String(doc.get(field) ?? doc.get('label') ?? '').trim()\n return { id: doc.id, ...(name ? { name } : {}) }\n })\n const answers: TransferReferenceKind[] = []\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.list)) {\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.list, label: 'Email list', targets: await named('lists', 'name') })\n }\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.topic)) {\n // Asked only when the email plugin, which owns the topic catalog and answers `email.topics`\n // (AGL-3550), is not running here — and without it the catalog is the built-ins the plugins declare.\n const targets = DECLARED_SUBSCRIPTION_TOPICS.map((topic) => ({ id: topic.id, name: topic.name }))\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.topic, label: 'Subscription topic', targets })\n }\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.member)) {\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.member, label: 'Member', targets: await named('members', 'email') })\n }\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.dataset)) {\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.dataset, label: 'Dataset', targets: await named('datasets', 'name') })\n }\n return answers\n },\n\n async writeItems(\n ctx: TransferResourceContext,\n items: ReadonlyArray<TransferPackageItemWrite<OrgAutomationPackageContent>>,\n writer: TransferApplyWriter,\n ): Promise<TransferApplyResult> {\n const refusal = await importerRefusal(deps, ctx)\n const firestore = deps.firestore()\n const results: TransferRowResult[] = []\n for (const write of items) {\n const before = await writer.alreadyApplied(write.row)\n if (before) {\n results.push(before)\n continue\n }\n const content = rawOrgAutomationContent(write.content)\n const name = write.rename?.name ?? content.name\n const replacing = write.decision === 'replace'\n const read = fieldsOf(content, name, replacing ? await enabledNow(ctx.orgId, write.targetId) : false)\n let result: TransferRowResult\n if (refusal) result = { row: write.row, outcome: 'failed', message: refusal }\n else if (read.ok === false) result = { row: write.row, outcome: 'failed', message: read.problem }\n else {\n const input = { orgId: ctx.orgId, id: write.targetId, fields: read.value, actorUid: ctx.actorUid ?? '' }\n const written = replacing ? await updateOrgAutomationRecord(firestore, input) : await createOrgAutomationRecord(firestore, input)\n if (written.ok === false) result = { row: write.row, outcome: 'failed', recordId: write.targetId, message: written.error }\n else {\n await deps.logOrgActivity(ctx.orgId, ctx.actorUid ?? '', replacing ? 'Edited an org automation' : 'Created an org automation', {\n id: written.id,\n name: read.value.name,\n })\n result = { row: write.row, outcome: replacing ? 'updated' : 'created', recordId: written.id }\n }\n }\n await writer.markApplied(result)\n results.push(result)\n }\n return { results, undo: [] }\n },\n\n async revertItems(\n ctx: TransferResourceContext,\n steps: ReadonlyArray<TransferPackageRevertStep<OrgAutomationPackageContent>>,\n ): Promise<TransferPackageRevertResult> {\n const firestore = deps.firestore()\n const outcome: TransferPackageRevertResult = { done: [], refused: [] }\n for (const step of steps) {\n if (step.action === 'delete') {\n const deleted = await deleteOrgAutomationRecord(firestore, { orgId: ctx.orgId, id: step.id, actorUid: ctx.actorUid ?? '' })\n if (deleted && !deleted.again) {\n await deps.logOrgActivity(ctx.orgId, ctx.actorUid ?? '', 'Deleted an org automation', { id: step.id, name: deleted.name })\n }\n outcome.done.push(step.id)\n continue\n }\n const content = rawOrgAutomationContent(step.content)\n const read = fieldsOf(content, content.name, await enabledNow(ctx.orgId, step.id))\n if (read.ok === false) {\n outcome.refused.push({ id: step.id, reason: read.problem })\n continue\n }\n const written = await updateOrgAutomationRecord(firestore, { orgId: ctx.orgId, id: step.id, fields: read.value, actorUid: ctx.actorUid ?? '' })\n if (written.ok === false) outcome.refused.push({ id: step.id, reason: written.error })\n else outcome.done.push(step.id)\n }\n return outcome\n },\n }\n}\n"],"names":["DECLARED_SUBSCRIPTION_TOPICS","existingPackageItemsOf","isPluginEnabled","checkEntitlement","isOrgWideMember","planLabelGrantingFeature","firebaseAdmin","getOrgDoc","logOrgActivity","memberHasOrgPermission","resolveOrgMembership","workflowsPermissionRefusal","BUNDLE_ID","ORG_AUTOMATION_ACTIVITY_TARGET","ORG_AUTOMATIONS_COLLECTION","ORG_AUTOMATIONS_MAX","readOrgAutomation","createOrgAutomationRecord","deleteOrgAutomationRecord","updateOrgAutomationRecord","ORG_AUTOMATION_REFERENCE_KINDS","ORG_AUTOMATIONS_TRANSFER_KEY","orgAutomationPackageContent","rawOrgAutomationContent","defaultDeps","firestore","app","readOrg","orgId","memberOf","uid","member","holdsOrgAutomations","action","target","email","type","automationsOf","collection","doc","importerRefusal","deps","ctx","actorUid","org","readAll","ids","docs","Promise","all","map","id","get","filter","exists","where","flatMap","content","data","kind","name","fieldsOf","enabled","createOrgAutomationsPackage","enabledNow","items","readItems","problems","write","refusal","read","rename","ok","problem","decision","targetId","push","live","count","referenceTargets","kinds","named","field","String","trim","answers","includes","list","label","targets","topic","dataset","writeItems","writer","results","before","alreadyApplied","row","replacing","result","outcome","message","input","fields","value","written","recordId","error","markApplied","undo","revertItems","steps","done","refused","step","deleted","again","reason"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;2CAW2C,GAE3C,SAASA,4BAA4B,QAA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AK;gBAAC;qBAC/EP,QAAQY,IAAI,CAACpC,IAAI,CAACsC,KAAK/D,EAAE;YAChC;YACA,OAAOiD;QACT;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/transfer/org-automations-package.server.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 * ORG AUTOMATIONS IN A WORKSPACE PACKAGE — the server half (AGL-3535).\n *\n * Written through `automations/manage`'s own writes\n * (`createOrgAutomationRecord`, `updateOrgAutomationRecord`,\n * `deleteOrgAutomationRecord`): its reader, its placement check, its cap,\n * its soft delete and its activity lines. The importer is held to that\n * door's rules too — an org-wide owner, admin or editor, in a workspace\n * running Workflows on a plan with org automations — so an import can do\n * nothing that door would refuse. A new automation lands switched off; a\n * replaced one keeps whether it was on.\n *=========================================*/\n\nimport {\n hostIdsFromScope,\n isOrgWideScope,\n type ScopeSharingChoice,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { DECLARED_SUBSCRIPTION_TOPICS } from '@aglyn/aglyn/app-utils/subscription-topics'\nimport { existingPackageItemsOf, type ExistingPackageItem, type TransferReferenceKind, type TransferRowResult } from '@aglyn/aglyn/data-transfer'\nimport { isPluginEnabled } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\nimport type {\n TransferApplyResult,\n TransferApplyWriter,\n TransferPackageItemContent,\n TransferPackageItemWrite,\n TransferPackageRevertResult,\n TransferPackageRevertStep,\n TransferResourceContext,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { checkEntitlement, isOrgWideMember, planLabelGrantingFeature } from '@aglyn/aglyn/server'\nimport firebaseAdmin from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport {\n getOrgDoc,\n logOrgActivity,\n memberHasOrgPermission,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { workflowsPermissionRefusal } from '../model/workflows-permissions'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n ORG_AUTOMATION_ACTIVITY_TARGET,\n ORG_AUTOMATIONS_COLLECTION,\n ORG_AUTOMATIONS_MAX,\n readOrgAutomation,\n} from '../model/org-automations'\nimport {\n createOrgAutomationRecord,\n deleteOrgAutomationRecord,\n updateOrgAutomationRecord,\n} from '../server/org-automations-routes'\nimport {\n ORG_AUTOMATION_REFERENCE_KINDS,\n ORG_AUTOMATIONS_TRANSFER_KEY,\n orgAutomationPackageContent,\n rawOrgAutomationContent,\n type OrgAutomationPackageContent,\n} from './org-automations-package'\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface OrgAutomationsPackageDeps {\n firestore(): Firestore\n readOrg(orgId: string): Promise<Record<string, unknown> | null>\n memberOf(uid: string, orgId: string): Promise<Record<string, unknown> | null>\n /** Whether a member holds \"Manage org automations\" (AGL-4047): `memberHasOrgPermission`. */\n holdsOrgAutomations(orgId: string, member: Record<string, unknown>): Promise<boolean>\n logOrgActivity(orgId: string, uid: string, action: string, target: { id: string; name: string }): Promise<void>\n}\n\nfunction defaultDeps(): OrgAutomationsPackageDeps {\n return {\n firestore: () => firebaseAdmin.app().firestore() as unknown as Firestore,\n readOrg: async (orgId) => ((await getOrgDoc(orgId)) as Record<string, unknown> | null) ?? null,\n memberOf: async (uid, orgId) => ((await resolveOrgMembership(uid, orgId))?.member as Record<string, unknown> | undefined) ?? null,\n holdsOrgAutomations: (orgId, member) => memberHasOrgPermission(orgId, member as never, 'workflows.orgAutomations' as never),\n logOrgActivity: (orgId, uid, action, target) =>\n logOrgActivity(orgId, { uid, email: null }, action, { type: ORG_AUTOMATION_ACTIVITY_TARGET, ...target }),\n }\n}\n\nconst automationsOf = (firestore: Firestore, orgId: string) =>\n firestore.collection('orgs').doc(orgId).collection(ORG_AUTOMATIONS_COLLECTION)\n\n/** Why `automations/manage` would refuse this importer, or `null` when it would not. */\nasync function importerRefusal(deps: OrgAutomationsPackageDeps, ctx: TransferResourceContext): Promise<string | null> {\n if (!ctx.actorUid) return 'Org automations are imported by a member of the organization.'\n const member = await deps.memberOf(ctx.actorUid, ctx.orgId)\n // \"Manage org automations\" (AGL-4047), for members of the whole workspace,\n // as `automations/manage` asks it.\n if (!member || !isOrgWideMember(member as never) || !(await deps.holdsOrgAutomations(ctx.orgId, member))) {\n return workflowsPermissionRefusal('workflows.orgAutomations')\n }\n const org = await deps.readOrg(ctx.orgId)\n if (!org || !isPluginEnabled(org as never, BUNDLE_ID)) return 'Workflows is not on for this workspace.'\n if (!checkEntitlement(org as never, 'actions')) {\n return `Org automations need the ${planLabelGrantingFeature('actions') ?? 'Pro'} plan.`\n }\n return null\n}\n\nasync function readAll(\n deps: OrgAutomationsPackageDeps,\n orgId: string,\n ids?: readonly string[],\n): Promise<Array<TransferPackageItemContent<OrgAutomationPackageContent>>> {\n const collection = automationsOf(deps.firestore(), orgId)\n const docs = ids\n ? (await Promise.all(ids.map((id) => collection.doc(id).get()))).filter((doc) => doc.exists)\n : (await collection.where('deletedAt', '==', null).get()).docs\n return docs.flatMap((doc) => {\n if (doc.get('deletedAt')) return []\n const content = orgAutomationPackageContent(doc.data())\n return content ? [{ kind: ORG_AUTOMATIONS_TRANSFER_KEY, id: doc.id, name: content.name, content }] : []\n })\n}\n\n/**\n * The fields one write stores: the content, read by the route's reader, switched on only if it already was.\n *\n * The package's placement is said as a choice (AGL-4047), so a replace puts the automation where the package\n * says, and takes off a marker the one it replaces carried, even when the sites happen to match.\n */\nfunction fieldsOf(content: OrgAutomationPackageContent, name: string, enabled: boolean) {\n const sharing: ScopeSharingChoice =\n content.sharing ??\n (isOrgWideScope(content.visibleTo)\n ? { mode: 'all' }\n : { mode: 'selected', hostIds: hostIdsFromScope(content.visibleTo) })\n return readOrgAutomation({ ...content, name, enabled, sharing })\n}\n\nexport function createOrgAutomationsPackage(deps: OrgAutomationsPackageDeps = defaultDeps()) {\n /** Whether the automation is on now; a new one is off. */\n const enabledNow = async (orgId: string, id: string) =>\n (await automationsOf(deps.firestore(), orgId).doc(id).get()).get('enabled') === true\n\n return {\n async items(ctx: TransferResourceContext): Promise<ExistingPackageItem[]> {\n return existingPackageItemsOf(ORG_AUTOMATIONS_TRANSFER_KEY, await readAll(deps, ctx.orgId))\n },\n\n async readItems(ctx: TransferResourceContext, ids: readonly string[]) {\n return readAll(deps, ctx.orgId, ids)\n },\n\n async problems(ctx: TransferResourceContext, write: TransferPackageItemWrite<OrgAutomationPackageContent>) {\n const refusal = await importerRefusal(deps, ctx)\n if (refusal) return [refusal]\n const content = rawOrgAutomationContent(write.content)\n const read = fieldsOf(content, write.rename?.name ?? content.name, false)\n if (read.ok === false) return [read.problem]\n const problems: string[] = []\n if (write.decision !== 'replace') {\n const collection = automationsOf(deps.firestore(), ctx.orgId)\n if ((await collection.doc(write.targetId).get()).exists) {\n problems.push('An automation with this id was deleted from this workspace, so it cannot come back under it.')\n }\n const live = (await collection.where('deletedAt', '==', null).count().get()).data().count\n if (live >= ORG_AUTOMATIONS_MAX) {\n problems.push(`An organization holds at most ${ORG_AUTOMATIONS_MAX} org automations — delete one you no longer use first.`)\n }\n }\n return problems\n },\n\n async referenceTargets(ctx: TransferResourceContext, kinds: readonly string[]): Promise<TransferReferenceKind[]> {\n const org = deps.firestore().collection('orgs').doc(ctx.orgId)\n const named = async (collection: string, field: string) =>\n (await org.collection(collection).get()).docs\n .filter((doc) => !doc.get('deletedAt'))\n .map((doc) => {\n const name = String(doc.get(field) ?? doc.get('label') ?? '').trim()\n return { id: doc.id, ...(name ? { name } : {}) }\n })\n const answers: TransferReferenceKind[] = []\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.list)) {\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.list, label: 'Email list', targets: await named('lists', 'name') })\n }\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.topic)) {\n // Asked only when the email plugin, which owns the topic catalog and answers `email.topics`\n // (AGL-3550), is not running here — and without it the catalog is the built-ins the plugins declare.\n const targets = DECLARED_SUBSCRIPTION_TOPICS.map((topic) => ({ id: topic.id, name: topic.name }))\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.topic, label: 'Subscription topic', targets })\n }\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.member)) {\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.member, label: 'Member', targets: await named('members', 'email') })\n }\n if (kinds.includes(ORG_AUTOMATION_REFERENCE_KINDS.dataset)) {\n answers.push({ kind: ORG_AUTOMATION_REFERENCE_KINDS.dataset, label: 'Dataset', targets: await named('datasets', 'name') })\n }\n return answers\n },\n\n async writeItems(\n ctx: TransferResourceContext,\n items: ReadonlyArray<TransferPackageItemWrite<OrgAutomationPackageContent>>,\n writer: TransferApplyWriter,\n ): Promise<TransferApplyResult> {\n const refusal = await importerRefusal(deps, ctx)\n const firestore = deps.firestore()\n const results: TransferRowResult[] = []\n for (const write of items) {\n const before = await writer.alreadyApplied(write.row)\n if (before) {\n results.push(before)\n continue\n }\n const content = rawOrgAutomationContent(write.content)\n const name = write.rename?.name ?? content.name\n const replacing = write.decision === 'replace'\n const read = fieldsOf(content, name, replacing ? await enabledNow(ctx.orgId, write.targetId) : false)\n let result: TransferRowResult\n if (refusal) result = { row: write.row, outcome: 'failed', message: refusal }\n else if (read.ok === false) result = { row: write.row, outcome: 'failed', message: read.problem }\n else {\n const input = { orgId: ctx.orgId, id: write.targetId, fields: read.value, actorUid: ctx.actorUid ?? '' }\n const written = replacing ? await updateOrgAutomationRecord(firestore, input) : await createOrgAutomationRecord(firestore, input)\n if (written.ok === false) result = { row: write.row, outcome: 'failed', recordId: write.targetId, message: written.error }\n else {\n await deps.logOrgActivity(ctx.orgId, ctx.actorUid ?? '', replacing ? 'Edited an org automation' : 'Created an org automation', {\n id: written.id,\n name: read.value.name,\n })\n result = { row: write.row, outcome: replacing ? 'updated' : 'created', recordId: written.id }\n }\n }\n await writer.markApplied(result)\n results.push(result)\n }\n return { results, undo: [] }\n },\n\n async revertItems(\n ctx: TransferResourceContext,\n steps: ReadonlyArray<TransferPackageRevertStep<OrgAutomationPackageContent>>,\n ): Promise<TransferPackageRevertResult> {\n const firestore = deps.firestore()\n const outcome: TransferPackageRevertResult = { done: [], refused: [] }\n for (const step of steps) {\n if (step.action === 'delete') {\n const deleted = await deleteOrgAutomationRecord(firestore, { orgId: ctx.orgId, id: step.id, actorUid: ctx.actorUid ?? '' })\n if (deleted && !deleted.again) {\n await deps.logOrgActivity(ctx.orgId, ctx.actorUid ?? '', 'Deleted an org automation', { id: step.id, name: deleted.name })\n }\n outcome.done.push(step.id)\n continue\n }\n const content = rawOrgAutomationContent(step.content)\n const read = fieldsOf(content, content.name, await enabledNow(ctx.orgId, step.id))\n if (read.ok === false) {\n outcome.refused.push({ id: step.id, reason: read.problem })\n continue\n }\n const written = await updateOrgAutomationRecord(firestore, { orgId: ctx.orgId, id: step.id, fields: read.value, actorUid: ctx.actorUid ?? '' })\n if (written.ok === false) outcome.refused.push({ id: step.id, reason: written.error })\n else outcome.done.push(step.id)\n }\n return outcome\n },\n }\n}\n"],"names":["hostIdsFromScope","isOrgWideScope","DECLARED_SUBSCRIPTION_TOPICS","existingPackageItemsOf","isPluginEnabled","checkEntitlement","isOrgWideMember","planLabelGrantingFeature","firebaseAdmin","getOrgDoc","logOrgActivity","memberHasOrgPermission","resolveOrgMembership","workflowsPermissionRefusal","BUNDLE_ID","ORG_AUTOMATION_ACTIVITY_TARGET","ORG_AUTOMATIONS_COLLECTION","ORG_AUTOMATIONS_MAX","readOrgAutomation","createOrgAutomationRecord","deleteOrgAutomationRecord","updateOrgAutomationRecord","ORG_AUTOMATION_REFERENCE_KINDS","ORG_AUTOMATIONS_TRANSFER_KEY","orgAutomationPackageContent","rawOrgAutomationContent","defaultDeps","firestore","app","readOrg","orgId","memberOf","uid","member","holdsOrgAutomations","action","target","email","type","automationsOf","collection","doc","importerRefusal","deps","ctx","actorUid","org","readAll","ids","docs","Promise","all","map","id","get","filter","exists","where","flatMap","content","data","kind","name","fieldsOf","enabled","sharing","visibleTo","mode","hostIds","createOrgAutomationsPackage","enabledNow","items","readItems","problems","write","refusal","read","rename","ok","problem","decision","targetId","push","live","count","referenceTargets","kinds","named","field","String","trim","answers","includes","list","label","targets","topic","dataset","writeItems","writer","results","before","alreadyApplied","row","replacing","result","outcome","message","input","fields","value","written","recordId","error","markApplied","undo","revertItems","steps","done","refused","step","deleted","again","reason"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;2CAW2C,GAE3C,SACEA,gBAAgB,EAChBC,cAAc,QAET,sCAAqC;AAC5C,SAASC,4BAA4B,QAAQ,6CAA4C;AACzF,SAASC,sBAAsB,QAAsF,6BAA4B;AACjJ,SAASC,eAAe,QAAQ,8CAA6C;AAU7E,SAASC,gBAAgB,EAAEC,eAAe,EAAEC,wBAAwB,QAAQ,sBAAqB;AACjG,OAAOC,mBAAmB,iDAAgD;AAC1E,SACEC,SAAS,EACTC,cAAc,EACdC,sBAAsB,EACtBC,oBAAoB,QACf,gDAA+C;AACtD,SAASC,0BAA0B,QAAQ,oCAAgC;AAC3E,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,mBAAmB,EACnBC,iBAAiB,QACZ,8BAA0B;AACjC,SACEC,yBAAyB,EACzBC,yBAAyB,EACzBC,yBAAyB,QACpB,sCAAkC;AACzC,SACEC,8BAA8B,EAC9BC,4BAA4B,EAC5BC,2BAA2B,EAC3BC,uBAAuB,QAElB,+BAA2B;AAalC,SAASC;IACP,OAAO;QACLC,WAAW,IAAMnB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