@aglyn/plugins-email 1.0.0-beta.218 → 1.0.0-beta.220

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.
Files changed (56) hide show
  1. package/package.json +18 -18
  2. package/src/lib/components/campaign-topic-options-widget.js +2 -2
  3. package/src/lib/components/campaign-topic-options-widget.js.map +1 -1
  4. package/src/lib/components/campaign-topic-select.js +3 -3
  5. package/src/lib/components/campaign-topic-select.js.map +1 -1
  6. package/src/lib/components/consent-group-review.js +2 -2
  7. package/src/lib/components/consent-group-review.js.map +1 -1
  8. package/src/lib/components/dynamic-list-rule-fields.d.ts +20 -4
  9. package/src/lib/components/dynamic-list-rule-fields.js +537 -439
  10. package/src/lib/components/dynamic-list-rule-fields.js.map +1 -1
  11. package/src/lib/components/email-topic-detail.d.ts +1 -1
  12. package/src/lib/components/email-topic-detail.js +5 -5
  13. package/src/lib/components/email-topic-detail.js.map +1 -1
  14. package/src/lib/components/email-topics-card.d.ts +1 -1
  15. package/src/lib/components/email-topics-card.js +6 -5
  16. package/src/lib/components/email-topics-card.js.map +1 -1
  17. package/src/lib/components/emails-console-sections.js +3 -2
  18. package/src/lib/components/emails-console-sections.js.map +1 -1
  19. package/src/lib/components/list-import-drawer.js +2 -2
  20. package/src/lib/components/list-import-drawer.js.map +1 -1
  21. package/src/lib/components/use-org-email-topics.d.ts +4 -4
  22. package/src/lib/components/use-org-email-topics.js +6 -5
  23. package/src/lib/components/use-org-email-topics.js.map +1 -1
  24. package/src/lib/list-import.d.ts +149 -0
  25. package/src/lib/list-import.js +324 -0
  26. package/src/lib/list-import.js.map +1 -0
  27. package/src/lib/model/email-record-routes.d.ts +22 -0
  28. package/src/lib/model/email-record-routes.js +75 -0
  29. package/src/lib/model/email-record-routes.js.map +1 -0
  30. package/src/lib/model/email-topic-catalog.d.ts +36 -0
  31. package/src/lib/model/email-topic-catalog.js +36 -0
  32. package/src/lib/model/email-topic-catalog.js.map +1 -0
  33. package/src/lib/model/index.d.ts +0 -7
  34. package/src/lib/model/index.js +0 -6
  35. package/src/lib/model/index.js.map +1 -1
  36. package/src/lib/model/template-provenance.d.ts +1 -1
  37. package/src/lib/model/template-provenance.js +1 -1
  38. package/src/lib/model/template-provenance.js.map +1 -1
  39. package/src/lib/plugin.js +5 -1
  40. package/src/lib/plugin.js.map +1 -1
  41. package/src/lib/server-console.js +6 -2
  42. package/src/lib/server-console.js.map +1 -1
  43. package/src/lib/server-email-drafts.js +2 -2
  44. package/src/lib/server-email-drafts.js.map +1 -1
  45. package/src/lib/server-list-gate.js +35 -10
  46. package/src/lib/server-list-gate.js.map +1 -1
  47. package/src/lib/server-list-import.js +4 -3
  48. package/src/lib/server-list-import.js.map +1 -1
  49. package/src/lib/server-topic-index.d.ts +52 -0
  50. package/src/lib/server-topic-index.js +92 -0
  51. package/src/lib/server-topic-index.js.map +1 -0
  52. package/src/lib/server.js +11 -11
  53. package/src/lib/server.js.map +1 -1
  54. package/src/lib/unsubscribe-link.d.ts +1 -1
  55. package/src/lib/unsubscribe-link.js +2 -2
  56. package/src/lib/unsubscribe-link.js.map +1 -1
@@ -15,7 +15,8 @@
15
15
  * limitations under the License.
16
16
  */ 'use client';
17
17
  import { _ as _extends } from "@swc/helpers/_/_extends";
18
- import { EMAIL_TOPICS_COLLECTION, mergeEmailTopics, normalizeEmailTopic } from "@aglyn/aglyn";
18
+ import { mergeSubscriptionTopics, normalizeSubscriptionTopic } from "@aglyn/aglyn";
19
+ import { EMAIL_TOPICS_COLLECTION } from "../model/email-topic-catalog.js";
19
20
  import { collection, deleteField, doc, limit, orderBy, query, setDoc } from "firebase/firestore";
20
21
  import { useMemo } from "react";
21
22
  import { useFirestore, useFirestoreCollection, useOrgDataScope } from "@aglyn/tenant-feature-instance";
@@ -37,7 +38,7 @@ import { useFirestore, useFirestoreCollection, useOrgDataScope } from "@aglyn/te
37
38
  *
38
39
  * ## Why a built-in saves the same way
39
40
  *
40
- * `DEFAULT_EMAIL_TOPICS` is the FLOOR of the catalog, not its initial
41
+ * `DECLARED_SUBSCRIPTION_TOPICS` is the FLOOR of the catalog, not its initial
41
42
  * contents: the four built-ins have no stored document until somebody changes
42
43
  * one. `setDoc` at the built-in's own id is what creates the override, so the
43
44
  * same call serves a custom topic and a built-in being retired for the first
@@ -72,7 +73,7 @@ import { useFirestore, useFirestoreCollection, useOrgDataScope } from "@aglyn/te
72
73
  * different merge rules is how the composer comes to send a campaign under a
73
74
  * topic nobody can unsubscribe from.
74
75
  *
75
- * ORG-scoped, following `lists` (AGL-254) — see `email-topics.ts` for why the
76
+ * ORG-scoped, following `lists` (AGL-254) — see `subscription-topics.ts` for why the
76
77
  * definitions are org-shared while the recipient's opt-outs are per site.
77
78
  *
78
79
  * Ordered by the server rather than capped and re-sorted here (AGL-2501,
@@ -97,9 +98,9 @@ import { useFirestore, useFirestoreCollection, useOrgDataScope } from "@aglyn/te
97
98
  ], {
98
99
  idField: '$id'
99
100
  });
100
- const topics = useMemo(()=>mergeEmailTopics((stored != null ? stored : []).map((doc)=>{
101
+ const topics = useMemo(()=>mergeSubscriptionTopics((stored != null ? stored : []).map((doc)=>{
101
102
  var _doc_$id;
102
- return normalizeEmailTopic(String((_doc_$id = doc['$id']) != null ? _doc_$id : ''), doc);
103
+ return normalizeSubscriptionTopic(String((_doc_$id = doc['$id']) != null ? _doc_$id : ''), doc);
103
104
  }).filter((topic)=>!!topic)), [
104
105
  stored
105
106
  ]);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/email/src/lib/components/use-org-email-topics.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'use client'\n\nimport {\n EMAIL_TOPICS_COLLECTION,\n mergeEmailTopics,\n normalizeEmailTopic,\n type EmailTopic,\n} from '@aglyn/aglyn'\nimport type { Firestore } from 'firebase/firestore'\nimport {\n collection,\n deleteField,\n doc,\n limit,\n orderBy,\n query,\n setDoc,\n} from 'firebase/firestore'\nimport { useMemo } from 'react'\nimport {\n useFirestore,\n useFirestoreCollection,\n useOrgDataScope,\n} from '@aglyn/tenant-feature-instance'\n\n/**\n * Write one topic's document — the ONE writer of the topic catalog.\n *\n * Two surfaces change a topic: its own page, which edits the name and the\n * description, and the list card's row menu, which retires and restores. They\n * write the same document and have to agree about its shape, so the write\n * lives here rather than once in each.\n *\n * ## Why it is a complete statement and not a patch\n *\n * `archived` is written on every save rather than only when it changes. A\n * merge that omitted it would leave a restored topic carrying `archived: true`\n * from an earlier save — which reads on screen as restored and behaves as\n * retired, because the composer's picker and the recipient's preference page\n * both read the stored flag.\n *\n * ## Why a built-in saves the same way\n *\n * `DEFAULT_EMAIL_TOPICS` is the FLOOR of the catalog, not its initial\n * contents: the four built-ins have no stored document until somebody changes\n * one. `setDoc` at the built-in's own id is what creates the override, so the\n * same call serves a custom topic and a built-in being retired for the first\n * time.\n */\nexport async function writeEmailTopic(\n firestore: Firestore,\n scope: readonly [string, string],\n topic: {\n id: string\n name: string\n description: string\n archived: boolean\n /**\n * Whether this stream needs a confirmation click, or `null`/omitted for\n * \"whatever the site says\".\n *\n * The only field on this document with THREE states, which is why it is\n * the only one written conditionally: `archived` is written on every save\n * because a merge that omitted it would carry an old value forward, and a\n * `doubleOptIn` written on every save could never be un-chosen back to\n * the site default. `deleteField()` is what returns it, so clearing is a\n * real act rather than a value that happens to look like an absence.\n */\n doubleOptIn?: boolean | null\n },\n): Promise<void> {\n await setDoc(\n doc(firestore, scope[0], scope[1], EMAIL_TOPICS_COLLECTION, topic.id),\n {\n name: topic.name,\n description: topic.description,\n archived: topic.archived,\n ...(topic.doubleOptIn === undefined\n ? {}\n : {\n doubleOptIn:\n topic.doubleOptIn === null ? deleteField() : topic.doubleOptIn,\n }),\n },\n { merge: true },\n )\n}\n\n/**\n * How many stored topics one read fetches.\n *\n * A ceiling on the READ, not on the catalog. A preference page stops being a\n * preference page somewhere well before two hundred checkboxes, so an org that\n * reaches this has a different problem than a truncated list — and the read is\n * ordered, so what a merchant past it loses is the tail of the alphabet rather\n * than an arbitrary sample.\n */\nconst TOPIC_READ_CEILING = 200\n\n/**\n * The org's email topic catalog, as both the console card and the composer's\n * picker read it.\n *\n * ONE hook for both surfaces, because they have to agree: a topic the composer\n * offers must be one the preference page can render, and a topic the card\n * archives must leave the picker. Two reads of the same collection with two\n * different merge rules is how the composer comes to send a campaign under a\n * topic nobody can unsubscribe from.\n *\n * ORG-scoped, following `lists` (AGL-254) — see `email-topics.ts` for why the\n * definitions are org-shared while the recipient's opt-outs are per site.\n *\n * Ordered by the server rather than capped and re-sorted here (AGL-2501,\n * AGL-2292). `name` is safe to order on because every writer of this\n * collection is the topics card, which refuses to save a nameless topic —\n * `orderBy` DROPS documents that lack the field rather than mis-sorting them,\n * so that claim is about the writers and not a preference.\n */\nexport function useOrgEmailTopics(\n /** The site the catalog is read through, or `null` on the org page. */\n hostId: string | null,\n options?: {\n /**\n * Whether to read at all. Default true.\n *\n * For a caller whose only use of the catalog is a picker inside a control\n * somebody has to open — a create drawer, an edit drawer — where reading\n * on mount charges every reader of the list for a field none of them\n * asked for. A `false` here opens no listener, exactly as a null query\n * does, and the catalog reads as empty until it flips.\n */\n enabled?: boolean\n /**\n * The organization itself, for a caller mounted over the org rather than\n * under one of its sites. It skips the site's org lookup, and it is the\n * only way the catalog can be read with no site at all.\n */\n orgId?: string | null\n },\n): {\n topics: EmailTopic[]\n /** `['orgs', orgId]`, or null until the org lookup settles. */\n scope: readonly [string, string] | null\n} {\n const firestore = useFirestore()\n const enabled = options?.enabled ?? true\n // The org lookup is async (AGL-1061): null until it settles, and null\n // forever for a host with no owning org. An explicit org is ready at once.\n const { scope } = useOrgDataScope({\n hostId: hostId || undefined,\n orgId: options?.orgId || undefined,\n })\n const { data: stored } = useFirestoreCollection<Record<string, unknown>>(\n () =>\n scope && enabled\n ? query(\n collection(firestore, scope[0], scope[1], EMAIL_TOPICS_COLLECTION),\n orderBy('name'),\n limit(TOPIC_READ_CEILING),\n )\n : null,\n [firestore, scope, enabled],\n { idField: '$id' },\n )\n const topics = useMemo(\n () =>\n mergeEmailTopics(\n (stored ?? [])\n .map((doc) => normalizeEmailTopic(String(doc['$id'] ?? ''), doc))\n .filter((topic): topic is EmailTopic => !!topic),\n ),\n [stored],\n )\n return { topics, scope: scope as readonly [string, string] | null }\n}\n"],"names":["EMAIL_TOPICS_COLLECTION","mergeEmailTopics","normalizeEmailTopic","collection","deleteField","doc","limit","orderBy","query","setDoc","useMemo","useFirestore","useFirestoreCollection","useOrgDataScope","writeEmailTopic","firestore","scope","topic","id","name","description","archived","doubleOptIn","undefined","merge","TOPIC_READ_CEILING","useOrgEmailTopics","hostId","options","enabled","orgId","data","stored","idField","topics","map","String","filter"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,uBAAuB,EACvBC,gBAAgB,EAChBC,mBAAmB,QAEd,eAAc;AAErB,SACEC,UAAU,EACVC,WAAW,EACXC,GAAG,EACHC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,MAAM,QACD,qBAAoB;AAC3B,SAASC,OAAO,QAAQ,QAAO;AAC/B,SACEC,YAAY,EACZC,sBAAsB,EACtBC,eAAe,QACV,iCAAgC;AAEvC;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,eAAeC,gBACpBC,SAAoB,EACpBC,KAAgC,EAChCC,KAiBC;IAED,MAAMR,OACJJ,IAAIU,WAAWC,KAAK,CAAC,EAAE,EAAEA,KAAK,CAAC,EAAE,EAAEhB,yBAAyBiB,MAAMC,EAAE,GACpE;QACEC,MAAMF,MAAME,IAAI;QAChBC,aAAaH,MAAMG,WAAW;QAC9BC,UAAUJ,MAAMI,QAAQ;OACpBJ,MAAMK,WAAW,KAAKC,YACtB,CAAC,IACD;QACED,aACEL,MAAMK,WAAW,KAAK,OAAOlB,gBAAgBa,MAAMK,WAAW;IAClE,IAEN;QAAEE,OAAO;IAAK;AAElB;AAEA;;;;;;;;CAQC,GACD,MAAMC,qBAAqB;AAE3B;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASC,kBACd,qEAAqE,GACrEC,MAAqB,EACrBC,OAiBC;;IAMD,MAAMb,YAAYJ;IAClB,MAAMkB,kBAAUD,2BAAAA,QAASC,OAAO,mBAAI;IACpC,sEAAsE;IACtE,2EAA2E;IAC3E,MAAM,EAAEb,KAAK,EAAE,GAAGH,gBAAgB;QAChCc,QAAQA,UAAUJ;QAClBO,OAAOF,CAAAA,2BAAAA,QAASE,KAAK,KAAIP;IAC3B;IACA,MAAM,EAAEQ,MAAMC,MAAM,EAAE,GAAGpB,uBACvB,IACEI,SAASa,UACLrB,MACEL,WAAWY,WAAWC,KAAK,CAAC,EAAE,EAAEA,KAAK,CAAC,EAAE,EAAEhB,0BAC1CO,QAAQ,SACRD,MAAMmB,uBAER,MACN;QAACV;QAAWC;QAAOa;KAAQ,EAC3B;QAAEI,SAAS;IAAM;IAEnB,MAAMC,SAASxB,QACb,IACET,iBACE,CAAC+B,iBAAAA,SAAU,EAAE,EACVG,GAAG,CAAC,CAAC9B;gBAAmCA;mBAA3BH,oBAAoBkC,QAAO/B,WAAAA,GAAG,CAAC,MAAM,YAAVA,WAAc,KAAKA;WAC3DgC,MAAM,CAAC,CAACpB,QAA+B,CAAC,CAACA,SAEhD;QAACe;KAAO;IAEV,OAAO;QAAEE;QAAQlB,OAAOA;IAA0C;AACpE"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/email/src/lib/components/use-org-email-topics.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'use client'\n\nimport {\n mergeSubscriptionTopics,\n normalizeSubscriptionTopic,\n type SubscriptionTopic,\n} from '@aglyn/aglyn'\nimport { EMAIL_TOPICS_COLLECTION } from '../model/email-topic-catalog'\nimport type { Firestore } from 'firebase/firestore'\nimport {\n collection,\n deleteField,\n doc,\n limit,\n orderBy,\n query,\n setDoc,\n} from 'firebase/firestore'\nimport { useMemo } from 'react'\nimport {\n useFirestore,\n useFirestoreCollection,\n useOrgDataScope,\n} from '@aglyn/tenant-feature-instance'\n\n/**\n * Write one topic's document — the ONE writer of the topic catalog.\n *\n * Two surfaces change a topic: its own page, which edits the name and the\n * description, and the list card's row menu, which retires and restores. They\n * write the same document and have to agree about its shape, so the write\n * lives here rather than once in each.\n *\n * ## Why it is a complete statement and not a patch\n *\n * `archived` is written on every save rather than only when it changes. A\n * merge that omitted it would leave a restored topic carrying `archived: true`\n * from an earlier save — which reads on screen as restored and behaves as\n * retired, because the composer's picker and the recipient's preference page\n * both read the stored flag.\n *\n * ## Why a built-in saves the same way\n *\n * `DECLARED_SUBSCRIPTION_TOPICS` is the FLOOR of the catalog, not its initial\n * contents: the four built-ins have no stored document until somebody changes\n * one. `setDoc` at the built-in's own id is what creates the override, so the\n * same call serves a custom topic and a built-in being retired for the first\n * time.\n */\nexport async function writeEmailTopic(\n firestore: Firestore,\n scope: readonly [string, string],\n topic: {\n id: string\n name: string\n description: string\n archived: boolean\n /**\n * Whether this stream needs a confirmation click, or `null`/omitted for\n * \"whatever the site says\".\n *\n * The only field on this document with THREE states, which is why it is\n * the only one written conditionally: `archived` is written on every save\n * because a merge that omitted it would carry an old value forward, and a\n * `doubleOptIn` written on every save could never be un-chosen back to\n * the site default. `deleteField()` is what returns it, so clearing is a\n * real act rather than a value that happens to look like an absence.\n */\n doubleOptIn?: boolean | null\n },\n): Promise<void> {\n await setDoc(\n doc(firestore, scope[0], scope[1], EMAIL_TOPICS_COLLECTION, topic.id),\n {\n name: topic.name,\n description: topic.description,\n archived: topic.archived,\n ...(topic.doubleOptIn === undefined\n ? {}\n : {\n doubleOptIn:\n topic.doubleOptIn === null ? deleteField() : topic.doubleOptIn,\n }),\n },\n { merge: true },\n )\n}\n\n/**\n * How many stored topics one read fetches.\n *\n * A ceiling on the READ, not on the catalog. A preference page stops being a\n * preference page somewhere well before two hundred checkboxes, so an org that\n * reaches this has a different problem than a truncated list — and the read is\n * ordered, so what a merchant past it loses is the tail of the alphabet rather\n * than an arbitrary sample.\n */\nconst TOPIC_READ_CEILING = 200\n\n/**\n * The org's email topic catalog, as both the console card and the composer's\n * picker read it.\n *\n * ONE hook for both surfaces, because they have to agree: a topic the composer\n * offers must be one the preference page can render, and a topic the card\n * archives must leave the picker. Two reads of the same collection with two\n * different merge rules is how the composer comes to send a campaign under a\n * topic nobody can unsubscribe from.\n *\n * ORG-scoped, following `lists` (AGL-254) — see `subscription-topics.ts` for why the\n * definitions are org-shared while the recipient's opt-outs are per site.\n *\n * Ordered by the server rather than capped and re-sorted here (AGL-2501,\n * AGL-2292). `name` is safe to order on because every writer of this\n * collection is the topics card, which refuses to save a nameless topic —\n * `orderBy` DROPS documents that lack the field rather than mis-sorting them,\n * so that claim is about the writers and not a preference.\n */\nexport function useOrgEmailTopics(\n /** The site the catalog is read through, or `null` on the org page. */\n hostId: string | null,\n options?: {\n /**\n * Whether to read at all. Default true.\n *\n * For a caller whose only use of the catalog is a picker inside a control\n * somebody has to open — a create drawer, an edit drawer — where reading\n * on mount charges every reader of the list for a field none of them\n * asked for. A `false` here opens no listener, exactly as a null query\n * does, and the catalog reads as empty until it flips.\n */\n enabled?: boolean\n /**\n * The organization itself, for a caller mounted over the org rather than\n * under one of its sites. It skips the site's org lookup, and it is the\n * only way the catalog can be read with no site at all.\n */\n orgId?: string | null\n },\n): {\n topics: SubscriptionTopic[]\n /** `['orgs', orgId]`, or null until the org lookup settles. */\n scope: readonly [string, string] | null\n} {\n const firestore = useFirestore()\n const enabled = options?.enabled ?? true\n // The org lookup is async (AGL-1061): null until it settles, and null\n // forever for a host with no owning org. An explicit org is ready at once.\n const { scope } = useOrgDataScope({\n hostId: hostId || undefined,\n orgId: options?.orgId || undefined,\n })\n const { data: stored } = useFirestoreCollection<Record<string, unknown>>(\n () =>\n scope && enabled\n ? query(\n collection(firestore, scope[0], scope[1], EMAIL_TOPICS_COLLECTION),\n orderBy('name'),\n limit(TOPIC_READ_CEILING),\n )\n : null,\n [firestore, scope, enabled],\n { idField: '$id' },\n )\n const topics = useMemo(\n () =>\n mergeSubscriptionTopics(\n (stored ?? [])\n .map((doc) => normalizeSubscriptionTopic(String(doc['$id'] ?? ''), doc))\n .filter((topic): topic is SubscriptionTopic => !!topic),\n ),\n [stored],\n )\n return { topics, scope: scope as readonly [string, string] | null }\n}\n"],"names":["mergeSubscriptionTopics","normalizeSubscriptionTopic","EMAIL_TOPICS_COLLECTION","collection","deleteField","doc","limit","orderBy","query","setDoc","useMemo","useFirestore","useFirestoreCollection","useOrgDataScope","writeEmailTopic","firestore","scope","topic","id","name","description","archived","doubleOptIn","undefined","merge","TOPIC_READ_CEILING","useOrgEmailTopics","hostId","options","enabled","orgId","data","stored","idField","topics","map","String","filter"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,uBAAuB,EACvBC,0BAA0B,QAErB,eAAc;AACrB,SAASC,uBAAuB,QAAQ,kCAA8B;AAEtE,SACEC,UAAU,EACVC,WAAW,EACXC,GAAG,EACHC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,MAAM,QACD,qBAAoB;AAC3B,SAASC,OAAO,QAAQ,QAAO;AAC/B,SACEC,YAAY,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GAAG,CAAC,MAAM,YAAVA,WAAc,KAAKA;WAClEgC,MAAM,CAAC,CAACpB,QAAsC,CAAC,CAACA,SAEvD;QAACe;KAAO;IAEV,OAAO;QAAEE;QAAQlB,OAAOA;IAA0C;AACpE"}
@@ -0,0 +1,149 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * The most addresses one uploaded file may name.
19
+ *
20
+ * A bound on the WORK an import represents, not a capacity limit: it refuses
21
+ * a FILE, before anything is written, and it can never drop a person already
22
+ * on a list or trim one to make room. A merchant with more than this splits
23
+ * the file, which is a nuisance; a merchant whose audience got silently
24
+ * truncated has an audience they cannot reason about.
25
+ *
26
+ * 50,000 is Klaviyo's shape rather than a number of our own — its only
27
+ * published hard import limit is a 50 MB CSV, which is the same statement in
28
+ * bytes. Above this the parse itself is the cost, and it happens in one
29
+ * request.
30
+ */
31
+ export declare const LIST_IMPORT_MAX_ADDRESSES = 50000;
32
+ /**
33
+ * Local parts that make an address a ROLE account.
34
+ *
35
+ * A mailbox several people read, or none. M3AAWG's Vetting BCP: their
36
+ * appearance on a customer list "may be indicative of poor acquisition
37
+ * practices" — a list built by scraping a website collects these, a list
38
+ * built from signups does not.
39
+ *
40
+ * Reported, never dropped. A merchant importing their own supplier contacts
41
+ * legitimately has `orders@`, and an importer that quietly removed addresses
42
+ * would be telling the operator a different number went on the list than did.
43
+ */
44
+ export declare const ROLE_ACCOUNT_LOCAL_PARTS: readonly string[];
45
+ /**
46
+ * Column names that say where the file came from, when the answer is "not
47
+ * from people who asked".
48
+ *
49
+ * M3AAWG names `jigsaw` and `append` specifically. The rest are the same tell
50
+ * in the vocabulary the data brokers actually use, and they are matched as
51
+ * substrings of a normalized header so `Appended Email` and `append_date`
52
+ * both hit.
53
+ *
54
+ * Every vendor surveyed prohibits purchased lists outright, Apple bans
55
+ * purchased, rented and appended lists, and M3AAWG calls appending "a direct
56
+ * violation of core M3AAWG values". This is not a policy we invented and the
57
+ * screening exists so that a merchant cannot attest their way past it without
58
+ * having been shown it.
59
+ */
60
+ export declare const PURCHASE_TELL_COLUMNS: readonly string[];
61
+ /** What the merchant's file says about one person. */
62
+ export interface ListImportRow {
63
+ /** The source line, verbatim, so a bad one can be pointed at on screen. */
64
+ input: string;
65
+ /** The normalized address, or `null` when the line does not carry one. */
66
+ email: string | null;
67
+ /** A display name from the file, or `''`. */
68
+ name: string;
69
+ /**
70
+ * Where the file says this person opted in, or `''`.
71
+ *
72
+ * Evidence for the operator's assertion and never a basis of its own — see
73
+ * the module note.
74
+ */
75
+ declaredSource: string;
76
+ /** When the file says they opted in, or `''`, kept as written. */
77
+ declaredAt: string;
78
+ }
79
+ /** What one file turned out to be. */
80
+ export interface ParsedListImport {
81
+ /** The header row's column names, or `[]` for a bare list of addresses. */
82
+ columns: string[];
83
+ /**
84
+ * One row per usable, first-seen address, plus one per unusable line.
85
+ *
86
+ * A repeat of an address already seen is collapsed and counted in
87
+ * {@link duplicates} rather than carried: the membership is keyed by the
88
+ * normalized address, so two lines would be one row and reporting them as
89
+ * two would tell the operator they are attesting for more people than they
90
+ * are. That is exactly the rule `resolveAddresses` applies to a paste.
91
+ */
92
+ rows: ListImportRow[];
93
+ /** Rows carrying a usable address. */
94
+ usable: number;
95
+ /** Lines that are not addresses. Reported, never dropped. */
96
+ unusable: number;
97
+ /** Repeat appearances of an address already counted. */
98
+ duplicates: number;
99
+ /** True when the file names more than {@link LIST_IMPORT_MAX_ADDRESSES}. */
100
+ overCeiling: boolean;
101
+ }
102
+ /** What the mechanical screening found. Signals, not verdicts. */
103
+ export interface ListImportScreening {
104
+ /** Addresses at a shared or unattended mailbox. */
105
+ roleAccounts: string[];
106
+ /** Column names in the file that read as purchase or append tells. */
107
+ purchaseTellColumns: string[];
108
+ /** True when the file declares an opt-in source or date per row. */
109
+ declaresBasis: boolean;
110
+ }
111
+ /**
112
+ * Reads an uploaded or pasted file into rows.
113
+ *
114
+ * Handles the two shapes a merchant's list actually arrives in: a CSV with a
115
+ * header, and a bare column of addresses with no header at all. Both go
116
+ * through one parser — `parseCsv` — because a newline-separated list of
117
+ * addresses IS a single-column CSV, and a second code path for it would be a
118
+ * second place for the quoting rules to differ.
119
+ *
120
+ * ## Every line comes back, including the bad ones
121
+ *
122
+ * A file that silently discarded its malformed lines would tell an operator
123
+ * that 100 addresses went on the list when 94 did, and the six they never
124
+ * hear about are the six they typed wrong. This is the rule `resolveAddresses`
125
+ * already applies to a paste, restated for a file.
126
+ */
127
+ export declare function parseListImport(text: string): ParsedListImport;
128
+ /**
129
+ * The mechanical checks, over a parsed file.
130
+ *
131
+ * Cheap by construction: two substring passes and one set membership per
132
+ * address. It is deliberately not a deliverability service — Omnisend's own
133
+ * caveat on the one that exists is that "list cleaning confirms
134
+ * deliverability only and does not establish recipient consent", and consent
135
+ * is the only question this import actually turns on.
136
+ */
137
+ export declare function screenListImport(parsed: Pick<ParsedListImport, 'columns' | 'rows'>): ListImportScreening;
138
+ /**
139
+ * The sentence recorded as the REASON behind an imported person's basis.
140
+ *
141
+ * One line, built from what the file actually declared, so a compliance
142
+ * question about one address gets an answer about that address rather than
143
+ * "somebody ticked a box on an import once". Empty declarations produce the
144
+ * plain sentence rather than a sentence with holes in it.
145
+ */
146
+ export declare function importedBasisReason(row: {
147
+ declaredSource: string;
148
+ declaredAt: string;
149
+ }): string;
@@ -0,0 +1,324 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /**
17
+ * READING A MERCHANT'S CONTACT FILE, and saying what is in it.
18
+ *
19
+ * `docs/specs/email-competitive-gaps.md` G5 is the product gap — a customer
20
+ * arriving with a list has no way to bring it — and P4 is its condition: an
21
+ * importer is simultaneously the biggest onboarding blocker and the biggest
22
+ * abuse vector, so it ships WITH its controls or not at all. This module is
23
+ * the pure half of those controls. It parses, it de-duplicates, and it
24
+ * SCREENS. It decides nothing about consent and it enrolls nobody: the
25
+ * consent question belongs to `enrollment-basis`, which the one-address
26
+ * add path already asks, and an import that answered it a second way would be
27
+ * exactly the defect class the register has a P1 entry for.
28
+ *
29
+ * ## The screening reports, it never refuses
30
+ *
31
+ * M3AAWG's Vetting BCP supplies two cheap mechanical checks and both are
32
+ * signals rather than verdicts. A role account (`sales@`, `info@`) is, in
33
+ * M3AAWG's words, indicative of poor acquisition practice — it is not proof
34
+ * of one, and plenty of legitimate B2B lists carry a handful. A column named
35
+ * `jigsaw` or `append` is a purchase tell, and again a merchant may simply
36
+ * have named a column badly.
37
+ *
38
+ * So neither one drops an address. Both are put in front of the operator
39
+ * BEFORE they attest, because the attestation is the thing with teeth: an
40
+ * operator who states they have permission for a file whose headers say it
41
+ * was appended has made a claim their own console showed them the evidence
42
+ * against. That is what makes the record worth keeping.
43
+ *
44
+ * ## A declared basis per address, and why it is still an assertion
45
+ *
46
+ * P4 asks for "a declared basis per address, not one checkbox over the file".
47
+ * A file may carry an opt-in source and an opt-in date per row, and when it
48
+ * does they are read here and carried onto the import as evidence. They do
49
+ * NOT become the person's own opt-in. Nothing arriving in a spreadsheet is a
50
+ * checkbox somebody ticked; it is the merchant telling us about one, which is
51
+ * an operator assertion however many columns it arrives in. The basis stays
52
+ * `operator-attested` and the declared source rides along as the reason.
53
+ */ import { normalizeContactEmail } from "@aglyn/aglyn/app-utils/contacts";
54
+ import { parseCsv } from "@aglyn/aglyn/app-utils/csv";
55
+ /**
56
+ * The most addresses one uploaded file may name.
57
+ *
58
+ * A bound on the WORK an import represents, not a capacity limit: it refuses
59
+ * a FILE, before anything is written, and it can never drop a person already
60
+ * on a list or trim one to make room. A merchant with more than this splits
61
+ * the file, which is a nuisance; a merchant whose audience got silently
62
+ * truncated has an audience they cannot reason about.
63
+ *
64
+ * 50,000 is Klaviyo's shape rather than a number of our own — its only
65
+ * published hard import limit is a 50 MB CSV, which is the same statement in
66
+ * bytes. Above this the parse itself is the cost, and it happens in one
67
+ * request.
68
+ */ export const LIST_IMPORT_MAX_ADDRESSES = 50000;
69
+ /**
70
+ * Local parts that make an address a ROLE account.
71
+ *
72
+ * A mailbox several people read, or none. M3AAWG's Vetting BCP: their
73
+ * appearance on a customer list "may be indicative of poor acquisition
74
+ * practices" — a list built by scraping a website collects these, a list
75
+ * built from signups does not.
76
+ *
77
+ * Reported, never dropped. A merchant importing their own supplier contacts
78
+ * legitimately has `orders@`, and an importer that quietly removed addresses
79
+ * would be telling the operator a different number went on the list than did.
80
+ */ export const ROLE_ACCOUNT_LOCAL_PARTS = [
81
+ 'abuse',
82
+ 'admin',
83
+ 'billing',
84
+ 'contact',
85
+ 'enquiries',
86
+ 'help',
87
+ 'hello',
88
+ 'hr',
89
+ 'info',
90
+ 'inquiries',
91
+ 'mail',
92
+ 'marketing',
93
+ 'noreply',
94
+ 'no-reply',
95
+ 'office',
96
+ 'orders',
97
+ 'postmaster',
98
+ 'sales',
99
+ 'security',
100
+ 'staff',
101
+ 'support',
102
+ 'team',
103
+ 'webmaster'
104
+ ];
105
+ /**
106
+ * Column names that say where the file came from, when the answer is "not
107
+ * from people who asked".
108
+ *
109
+ * M3AAWG names `jigsaw` and `append` specifically. The rest are the same tell
110
+ * in the vocabulary the data brokers actually use, and they are matched as
111
+ * substrings of a normalized header so `Appended Email` and `append_date`
112
+ * both hit.
113
+ *
114
+ * Every vendor surveyed prohibits purchased lists outright, Apple bans
115
+ * purchased, rented and appended lists, and M3AAWG calls appending "a direct
116
+ * violation of core M3AAWG values". This is not a policy we invented and the
117
+ * screening exists so that a merchant cannot attest their way past it without
118
+ * having been shown it.
119
+ */ export const PURCHASE_TELL_COLUMNS = [
120
+ 'jigsaw',
121
+ 'append',
122
+ 'purchased',
123
+ 'rented',
124
+ 'databroker',
125
+ 'data broker',
126
+ 'leadgen',
127
+ 'lead gen',
128
+ 'scraped'
129
+ ];
130
+ /** Header aliases that name the address column. */ const EMAIL_COLUMNS = [
131
+ 'email',
132
+ 'emailaddress',
133
+ 'email address',
134
+ 'e-mail',
135
+ 'e-mail address',
136
+ 'mail',
137
+ 'contact email',
138
+ 'primary email'
139
+ ];
140
+ /** Header aliases that name a display name. */ const NAME_COLUMNS = [
141
+ 'name',
142
+ 'full name',
143
+ 'fullname',
144
+ 'display name',
145
+ 'contact name',
146
+ 'first name',
147
+ 'firstname',
148
+ 'given name'
149
+ ];
150
+ /** Header aliases carrying the merchant's declared opt-in source. */ const OPT_IN_SOURCE_COLUMNS = [
151
+ 'opt-in source',
152
+ 'optin source',
153
+ 'opt in source',
154
+ 'consent source',
155
+ 'signup source',
156
+ 'subscription source',
157
+ 'source'
158
+ ];
159
+ /** Header aliases carrying the merchant's declared opt-in date. */ const OPT_IN_DATE_COLUMNS = [
160
+ 'opt-in date',
161
+ 'optin date',
162
+ 'opt in date',
163
+ 'consent date',
164
+ 'signup date',
165
+ 'subscribed at',
166
+ 'date subscribed',
167
+ 'confirmed at'
168
+ ];
169
+ /** Normalizes a header cell for alias matching. */ function headerKey(value) {
170
+ return String(value != null ? value : '').trim().toLowerCase().replace(/[_]+/g, ' ').replace(/\s+/g, ' ');
171
+ }
172
+ /** The index of the first column matching one of `aliases`, or -1. */ function columnIndex(columns, aliases) {
173
+ const keys = columns.map(headerKey);
174
+ for (const alias of aliases){
175
+ const at = keys.indexOf(alias);
176
+ if (at !== -1) return at;
177
+ }
178
+ return -1;
179
+ }
180
+ /**
181
+ * Whether a parsed first row is a HEADER rather than a person.
182
+ *
183
+ * A header is a row with no address in it. That test rather than an alias
184
+ * match, because the common shape of a merchant's export is a header whose
185
+ * address column is called something we have never seen — and treating that
186
+ * file as headerless would import the word "Email Address" as a line that is
187
+ * not an address, and shift every subsequent column read by one.
188
+ *
189
+ * A one-column file of bare addresses therefore has no header, correctly:
190
+ * every row including the first carries an address.
191
+ */ function looksLikeHeader(cells) {
192
+ return !cells.some((cell)=>normalizeContactEmail(cell));
193
+ }
194
+ /**
195
+ * Reads an uploaded or pasted file into rows.
196
+ *
197
+ * Handles the two shapes a merchant's list actually arrives in: a CSV with a
198
+ * header, and a bare column of addresses with no header at all. Both go
199
+ * through one parser — `parseCsv` — because a newline-separated list of
200
+ * addresses IS a single-column CSV, and a second code path for it would be a
201
+ * second place for the quoting rules to differ.
202
+ *
203
+ * ## Every line comes back, including the bad ones
204
+ *
205
+ * A file that silently discarded its malformed lines would tell an operator
206
+ * that 100 addresses went on the list when 94 did, and the six they never
207
+ * hear about are the six they typed wrong. This is the rule `resolveAddresses`
208
+ * already applies to a paste, restated for a file.
209
+ */ export function parseListImport(text) {
210
+ const table = parseCsv(String(text != null ? text : ''));
211
+ if (!table.length) {
212
+ return {
213
+ columns: [],
214
+ rows: [],
215
+ usable: 0,
216
+ unusable: 0,
217
+ duplicates: 0,
218
+ overCeiling: false
219
+ };
220
+ }
221
+ const headed = table.length > 1 && looksLikeHeader(table[0]);
222
+ const columns = headed ? table[0].map((cell)=>String(cell != null ? cell : '').trim()) : [];
223
+ const body = headed ? table.slice(1) : table;
224
+ const emailAt = headed ? columnIndex(columns, EMAIL_COLUMNS) : 0;
225
+ const nameAt = headed ? columnIndex(columns, NAME_COLUMNS) : -1;
226
+ const sourceAt = headed ? columnIndex(columns, OPT_IN_SOURCE_COLUMNS) : -1;
227
+ const dateAt = headed ? columnIndex(columns, OPT_IN_DATE_COLUMNS) : -1;
228
+ const seen = new Set();
229
+ const rows = [];
230
+ let usable = 0;
231
+ let unusable = 0;
232
+ let duplicates = 0;
233
+ let overCeiling = false;
234
+ for (const cells of body){
235
+ var _cells_emailAt, _cells_find, _cells_nameAt, _cells_sourceAt, _cells_dateAt;
236
+ /*
237
+ * The named column when the header named one, and otherwise the first
238
+ * cell in the row that IS an address.
239
+ *
240
+ * The fallback is what makes an unrecognized header survivable: an
241
+ * export whose address column is called `Primary contact e-mail (work)`
242
+ * matches no alias, and refusing the whole file over a column name would
243
+ * be refusing the customer's migration over our vocabulary.
244
+ */ const raw = emailAt >= 0 && emailAt < cells.length ? String((_cells_emailAt = cells[emailAt]) != null ? _cells_emailAt : '') : (_cells_find = cells.find((cell)=>normalizeContactEmail(cell))) != null ? _cells_find : '';
245
+ const email = normalizeContactEmail(raw);
246
+ const input = String(raw != null ? raw : '').trim() || cells.join(', ').trim();
247
+ if (!email) {
248
+ unusable += 1;
249
+ rows.push({
250
+ input,
251
+ email: null,
252
+ name: '',
253
+ declaredSource: '',
254
+ declaredAt: ''
255
+ });
256
+ continue;
257
+ }
258
+ if (seen.has(email)) {
259
+ duplicates += 1;
260
+ continue;
261
+ }
262
+ if (seen.size >= LIST_IMPORT_MAX_ADDRESSES) {
263
+ overCeiling = true;
264
+ break;
265
+ }
266
+ seen.add(email);
267
+ usable += 1;
268
+ rows.push({
269
+ input,
270
+ email,
271
+ name: nameAt >= 0 ? String((_cells_nameAt = cells[nameAt]) != null ? _cells_nameAt : '').trim() : '',
272
+ declaredSource: sourceAt >= 0 ? String((_cells_sourceAt = cells[sourceAt]) != null ? _cells_sourceAt : '').trim() : '',
273
+ declaredAt: dateAt >= 0 ? String((_cells_dateAt = cells[dateAt]) != null ? _cells_dateAt : '').trim() : ''
274
+ });
275
+ }
276
+ return {
277
+ columns,
278
+ rows,
279
+ usable,
280
+ unusable,
281
+ duplicates,
282
+ overCeiling
283
+ };
284
+ }
285
+ /**
286
+ * The mechanical checks, over a parsed file.
287
+ *
288
+ * Cheap by construction: two substring passes and one set membership per
289
+ * address. It is deliberately not a deliverability service — Omnisend's own
290
+ * caveat on the one that exists is that "list cleaning confirms
291
+ * deliverability only and does not establish recipient consent", and consent
292
+ * is the only question this import actually turns on.
293
+ */ export function screenListImport(parsed) {
294
+ const roleAccounts = [];
295
+ for (const row of parsed.rows){
296
+ if (!row.email) continue;
297
+ const local = row.email.slice(0, row.email.indexOf('@'));
298
+ if (ROLE_ACCOUNT_LOCAL_PARTS.includes(local)) roleAccounts.push(row.email);
299
+ }
300
+ const purchaseTellColumns = parsed.columns.filter((column)=>{
301
+ const key = headerKey(column);
302
+ return PURCHASE_TELL_COLUMNS.some((tell)=>key.includes(tell));
303
+ });
304
+ return {
305
+ roleAccounts,
306
+ purchaseTellColumns,
307
+ declaresBasis: parsed.rows.some((row)=>!!row.declaredSource || !!row.declaredAt)
308
+ };
309
+ }
310
+ /**
311
+ * The sentence recorded as the REASON behind an imported person's basis.
312
+ *
313
+ * One line, built from what the file actually declared, so a compliance
314
+ * question about one address gets an answer about that address rather than
315
+ * "somebody ticked a box on an import once". Empty declarations produce the
316
+ * plain sentence rather than a sentence with holes in it.
317
+ */ export function importedBasisReason(row) {
318
+ const parts = [];
319
+ if (row.declaredSource) parts.push(`declared source: ${row.declaredSource}`);
320
+ if (row.declaredAt) parts.push(`declared opt-in: ${row.declaredAt}`);
321
+ return parts.length ? `Imported from a file, attested by the operator (${parts.join('; ')}).` : 'Imported from a file, attested by the operator.';
322
+ }
323
+
324
+ //# sourceMappingURL=list-import.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../libs/plugins/email/src/lib/list-import.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 * READING A MERCHANT'S CONTACT FILE, and saying what is in it.\n *\n * `docs/specs/email-competitive-gaps.md` G5 is the product gap — a customer\n * arriving with a list has no way to bring it — and P4 is its condition: an\n * importer is simultaneously the biggest onboarding blocker and the biggest\n * abuse vector, so it ships WITH its controls or not at all. This module is\n * the pure half of those controls. It parses, it de-duplicates, and it\n * SCREENS. It decides nothing about consent and it enrolls nobody: the\n * consent question belongs to `enrollment-basis`, which the one-address\n * add path already asks, and an import that answered it a second way would be\n * exactly the defect class the register has a P1 entry for.\n *\n * ## The screening reports, it never refuses\n *\n * M3AAWG's Vetting BCP supplies two cheap mechanical checks and both are\n * signals rather than verdicts. A role account (`sales@`, `info@`) is, in\n * M3AAWG's words, indicative of poor acquisition practice — it is not proof\n * of one, and plenty of legitimate B2B lists carry a handful. A column named\n * `jigsaw` or `append` is a purchase tell, and again a merchant may simply\n * have named a column badly.\n *\n * So neither one drops an address. Both are put in front of the operator\n * BEFORE they attest, because the attestation is the thing with teeth: an\n * operator who states they have permission for a file whose headers say it\n * was appended has made a claim their own console showed them the evidence\n * against. That is what makes the record worth keeping.\n *\n * ## A declared basis per address, and why it is still an assertion\n *\n * P4 asks for \"a declared basis per address, not one checkbox over the file\".\n * A file may carry an opt-in source and an opt-in date per row, and when it\n * does they are read here and carried onto the import as evidence. They do\n * NOT become the person's own opt-in. Nothing arriving in a spreadsheet is a\n * checkbox somebody ticked; it is the merchant telling us about one, which is\n * an operator assertion however many columns it arrives in. The basis stays\n * `operator-attested` and the declared source rides along as the reason.\n */\n\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport { parseCsv } from '@aglyn/aglyn/app-utils/csv'\n\n/**\n * The most addresses one uploaded file may name.\n *\n * A bound on the WORK an import represents, not a capacity limit: it refuses\n * a FILE, before anything is written, and it can never drop a person already\n * on a list or trim one to make room. A merchant with more than this splits\n * the file, which is a nuisance; a merchant whose audience got silently\n * truncated has an audience they cannot reason about.\n *\n * 50,000 is Klaviyo's shape rather than a number of our own — its only\n * published hard import limit is a 50 MB CSV, which is the same statement in\n * bytes. Above this the parse itself is the cost, and it happens in one\n * request.\n */\nexport const LIST_IMPORT_MAX_ADDRESSES = 50_000\n\n/**\n * Local parts that make an address a ROLE account.\n *\n * A mailbox several people read, or none. M3AAWG's Vetting BCP: their\n * appearance on a customer list \"may be indicative of poor acquisition\n * practices\" — a list built by scraping a website collects these, a list\n * built from signups does not.\n *\n * Reported, never dropped. A merchant importing their own supplier contacts\n * legitimately has `orders@`, and an importer that quietly removed addresses\n * would be telling the operator a different number went on the list than did.\n */\nexport const ROLE_ACCOUNT_LOCAL_PARTS: readonly string[] = [\n 'abuse',\n 'admin',\n 'billing',\n 'contact',\n 'enquiries',\n 'help',\n 'hello',\n 'hr',\n 'info',\n 'inquiries',\n 'mail',\n 'marketing',\n 'noreply',\n 'no-reply',\n 'office',\n 'orders',\n 'postmaster',\n 'sales',\n 'security',\n 'staff',\n 'support',\n 'team',\n 'webmaster',\n]\n\n/**\n * Column names that say where the file came from, when the answer is \"not\n * from people who asked\".\n *\n * M3AAWG names `jigsaw` and `append` specifically. The rest are the same tell\n * in the vocabulary the data brokers actually use, and they are matched as\n * substrings of a normalized header so `Appended Email` and `append_date`\n * both hit.\n *\n * Every vendor surveyed prohibits purchased lists outright, Apple bans\n * purchased, rented and appended lists, and M3AAWG calls appending \"a direct\n * violation of core M3AAWG values\". This is not a policy we invented and the\n * screening exists so that a merchant cannot attest their way past it without\n * having been shown it.\n */\nexport const PURCHASE_TELL_COLUMNS: readonly string[] = [\n 'jigsaw',\n 'append',\n 'purchased',\n 'rented',\n 'databroker',\n 'data broker',\n 'leadgen',\n 'lead gen',\n 'scraped',\n]\n\n/** Header aliases that name the address column. */\nconst EMAIL_COLUMNS = [\n 'email',\n 'emailaddress',\n 'email address',\n 'e-mail',\n 'e-mail address',\n 'mail',\n 'contact email',\n 'primary email',\n]\n\n/** Header aliases that name a display name. */\nconst NAME_COLUMNS = [\n 'name',\n 'full name',\n 'fullname',\n 'display name',\n 'contact name',\n 'first name',\n 'firstname',\n 'given name',\n]\n\n/** Header aliases carrying the merchant's declared opt-in source. */\nconst OPT_IN_SOURCE_COLUMNS = [\n 'opt-in source',\n 'optin source',\n 'opt in source',\n 'consent source',\n 'signup source',\n 'subscription source',\n 'source',\n]\n\n/** Header aliases carrying the merchant's declared opt-in date. */\nconst OPT_IN_DATE_COLUMNS = [\n 'opt-in date',\n 'optin date',\n 'opt in date',\n 'consent date',\n 'signup date',\n 'subscribed at',\n 'date subscribed',\n 'confirmed at',\n]\n\n/** What the merchant's file says about one person. */\nexport interface ListImportRow {\n /** The source line, verbatim, so a bad one can be pointed at on screen. */\n input: string\n /** The normalized address, or `null` when the line does not carry one. */\n email: string | null\n /** A display name from the file, or `''`. */\n name: string\n /**\n * Where the file says this person opted in, or `''`.\n *\n * Evidence for the operator's assertion and never a basis of its own — see\n * the module note.\n */\n declaredSource: string\n /** When the file says they opted in, or `''`, kept as written. */\n declaredAt: string\n}\n\n/** What one file turned out to be. */\nexport interface ParsedListImport {\n /** The header row's column names, or `[]` for a bare list of addresses. */\n columns: string[]\n /**\n * One row per usable, first-seen address, plus one per unusable line.\n *\n * A repeat of an address already seen is collapsed and counted in\n * {@link duplicates} rather than carried: the membership is keyed by the\n * normalized address, so two lines would be one row and reporting them as\n * two would tell the operator they are attesting for more people than they\n * are. That is exactly the rule `resolveAddresses` applies to a paste.\n */\n rows: ListImportRow[]\n /** Rows carrying a usable address. */\n usable: number\n /** Lines that are not addresses. Reported, never dropped. */\n unusable: number\n /** Repeat appearances of an address already counted. */\n duplicates: number\n /** True when the file names more than {@link LIST_IMPORT_MAX_ADDRESSES}. */\n overCeiling: boolean\n}\n\n/** What the mechanical screening found. Signals, not verdicts. */\nexport interface ListImportScreening {\n /** Addresses at a shared or unattended mailbox. */\n roleAccounts: string[]\n /** Column names in the file that read as purchase or append tells. */\n purchaseTellColumns: string[]\n /** True when the file declares an opt-in source or date per row. */\n declaresBasis: boolean\n}\n\n/** Normalizes a header cell for alias matching. */\nfunction headerKey(value: string): string {\n return String(value ?? '')\n .trim()\n .toLowerCase()\n .replace(/[_]+/g, ' ')\n .replace(/\\s+/g, ' ')\n}\n\n/** The index of the first column matching one of `aliases`, or -1. */\nfunction columnIndex(columns: string[], aliases: readonly string[]): number {\n const keys = columns.map(headerKey)\n for (const alias of aliases) {\n const at = keys.indexOf(alias)\n if (at !== -1) return at\n }\n return -1\n}\n\n/**\n * Whether a parsed first row is a HEADER rather than a person.\n *\n * A header is a row with no address in it. That test rather than an alias\n * match, because the common shape of a merchant's export is a header whose\n * address column is called something we have never seen — and treating that\n * file as headerless would import the word \"Email Address\" as a line that is\n * not an address, and shift every subsequent column read by one.\n *\n * A one-column file of bare addresses therefore has no header, correctly:\n * every row including the first carries an address.\n */\nfunction looksLikeHeader(cells: readonly string[]): boolean {\n return !cells.some((cell) => normalizeContactEmail(cell))\n}\n\n/**\n * Reads an uploaded or pasted file into rows.\n *\n * Handles the two shapes a merchant's list actually arrives in: a CSV with a\n * header, and a bare column of addresses with no header at all. Both go\n * through one parser — `parseCsv` — because a newline-separated list of\n * addresses IS a single-column CSV, and a second code path for it would be a\n * second place for the quoting rules to differ.\n *\n * ## Every line comes back, including the bad ones\n *\n * A file that silently discarded its malformed lines would tell an operator\n * that 100 addresses went on the list when 94 did, and the six they never\n * hear about are the six they typed wrong. This is the rule `resolveAddresses`\n * already applies to a paste, restated for a file.\n */\nexport function parseListImport(text: string): ParsedListImport {\n const table = parseCsv(String(text ?? ''))\n if (!table.length) {\n return {\n columns: [],\n rows: [],\n usable: 0,\n unusable: 0,\n duplicates: 0,\n overCeiling: false,\n }\n }\n const headed = table.length > 1 && looksLikeHeader(table[0])\n const columns = headed ? table[0].map((cell) => String(cell ?? '').trim()) : []\n const body = headed ? table.slice(1) : table\n\n const emailAt = headed ? columnIndex(columns, EMAIL_COLUMNS) : 0\n const nameAt = headed ? columnIndex(columns, NAME_COLUMNS) : -1\n const sourceAt = headed ? columnIndex(columns, OPT_IN_SOURCE_COLUMNS) : -1\n const dateAt = headed ? columnIndex(columns, OPT_IN_DATE_COLUMNS) : -1\n\n const seen = new Set<string>()\n const rows: ListImportRow[] = []\n let usable = 0\n let unusable = 0\n let duplicates = 0\n let overCeiling = false\n\n for (const cells of body) {\n /*\n * The named column when the header named one, and otherwise the first\n * cell in the row that IS an address.\n *\n * The fallback is what makes an unrecognized header survivable: an\n * export whose address column is called `Primary contact e-mail (work)`\n * matches no alias, and refusing the whole file over a column name would\n * be refusing the customer's migration over our vocabulary.\n */\n const raw =\n emailAt >= 0 && emailAt < cells.length\n ? String(cells[emailAt] ?? '')\n : (cells.find((cell) => normalizeContactEmail(cell)) ?? '')\n const email = normalizeContactEmail(raw)\n const input = String(raw ?? '').trim() || cells.join(', ').trim()\n if (!email) {\n unusable += 1\n rows.push({\n input,\n email: null,\n name: '',\n declaredSource: '',\n declaredAt: '',\n })\n continue\n }\n if (seen.has(email)) {\n duplicates += 1\n continue\n }\n if (seen.size >= LIST_IMPORT_MAX_ADDRESSES) {\n overCeiling = true\n break\n }\n seen.add(email)\n usable += 1\n rows.push({\n input,\n email,\n name: nameAt >= 0 ? String(cells[nameAt] ?? '').trim() : '',\n declaredSource: sourceAt >= 0 ? String(cells[sourceAt] ?? '').trim() : '',\n declaredAt: dateAt >= 0 ? String(cells[dateAt] ?? '').trim() : '',\n })\n }\n\n return { columns, rows, usable, unusable, duplicates, overCeiling }\n}\n\n/**\n * The mechanical checks, over a parsed file.\n *\n * Cheap by construction: two substring passes and one set membership per\n * address. It is deliberately not a deliverability service — Omnisend's own\n * caveat on the one that exists is that \"list cleaning confirms\n * deliverability only and does not establish recipient consent\", and consent\n * is the only question this import actually turns on.\n */\nexport function screenListImport(\n parsed: Pick<ParsedListImport, 'columns' | 'rows'>,\n): ListImportScreening {\n const roleAccounts: string[] = []\n for (const row of parsed.rows) {\n if (!row.email) continue\n const local = row.email.slice(0, row.email.indexOf('@'))\n if (ROLE_ACCOUNT_LOCAL_PARTS.includes(local)) roleAccounts.push(row.email)\n }\n const purchaseTellColumns = parsed.columns.filter((column) => {\n const key = headerKey(column)\n return PURCHASE_TELL_COLUMNS.some((tell) => key.includes(tell))\n })\n return {\n roleAccounts,\n purchaseTellColumns,\n declaresBasis: parsed.rows.some(\n (row) => !!row.declaredSource || !!row.declaredAt,\n ),\n }\n}\n\n/**\n * The sentence recorded as the REASON behind an imported person's basis.\n *\n * One line, built from what the file actually declared, so a compliance\n * question about one address gets an answer about that address rather than\n * \"somebody ticked a box on an import once\". Empty declarations produce the\n * plain sentence rather than a sentence with holes in it.\n */\nexport function importedBasisReason(row: {\n declaredSource: string\n declaredAt: string\n}): string {\n const parts: string[] = []\n if (row.declaredSource) parts.push(`declared source: ${row.declaredSource}`)\n if (row.declaredAt) parts.push(`declared opt-in: ${row.declaredAt}`)\n return parts.length\n ? `Imported from a file, attested by the operator (${parts.join('; ')}).`\n : 'Imported from a file, attested by the operator.'\n}\n"],"names":["normalizeContactEmail","parseCsv","LIST_IMPORT_MAX_ADDRESSES","ROLE_ACCOUNT_LOCAL_PARTS","PURCHASE_TELL_COLUMNS","EMAIL_COLUMNS","NAME_COLUMNS","OPT_IN_SOURCE_COLUMNS","OPT_IN_DATE_COLUMNS","headerKey","value","String","trim","toLowerCase","replace","columnIndex","columns","aliases","keys","map","alias","at","indexOf","looksLikeHeader","cells","some","cell","parseListImport","text","table","length","rows","usable","unusable","duplicates","overCeiling","headed","body","slice","emailAt","nameAt","sourceAt","dateAt","seen","Set","raw","find","email","input","join","push","name","declaredSource","declaredAt","has","size","add","screenListImport","parsed","roleAccounts","row","local","includes","purchaseTellColumns","filter","column","key","tell","declaresBasis","importedBasisReason","parts"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCC,GAED,SAASA,qBAAqB,QAAQ,kCAAiC;AACvE,SAASC,QAAQ,QAAQ,6BAA4B;AAErD;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,4BAA4B,MAAM;AAE/C;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,2BAA8C;IACzD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED;;;;;;;;;;;;;;CAcC,GACD,OAAO,MAAMC,wBAA2C;IACtD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED,iDAAiD,GACjD,MAAMC,gBAAgB;IACpB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,6CAA6C,GAC7C,MAAMC,eAAe;IACnB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,mEAAmE,GACnE,MAAMC,wBAAwB;IAC5B;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,iEAAiE,GACjE,MAAMC,sBAAsB;IAC1B;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAuDD,iDAAiD,GACjD,SAASC,UAAUC,KAAa;IAC9B,OAAOC,OAAOD,gBAAAA,QAAS,IACpBE,IAAI,GACJC,WAAW,GACXC,OAAO,CAAC,SAAS,KACjBA,OAAO,CAAC,QAAQ;AACrB;AAEA,oEAAoE,GACpE,SAASC,YAAYC,OAAiB,EAAEC,OAA0B;IAChE,MAAMC,OAAOF,QAAQG,GAAG,CAACV;IACzB,KAAK,MAAMW,SAASH,QAAS;QAC3B,MAAMI,KAAKH,KAAKI,OAAO,CAACF;QACxB,IAAIC,OAAO,CAAC,GAAG,OAAOA;IACxB;IACA,OAAO,CAAC;AACV;A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;IAC3E;IACA,MAAMgB,sBAAsBL,OAAO1C,OAAO,CAACgD,MAAM,CAAC,CAACC;QACjD,MAAMC,MAAMzD,UAAUwD;QACtB,OAAO7D,sBAAsBqB,IAAI,CAAC,CAAC0C,OAASD,IAAIJ,QAAQ,CAACK;IAC3D;IACA,OAAO;QACLR;QACAI;QACAK,eAAeV,OAAO3B,IAAI,CAACN,IAAI,CAC7B,CAACmC,MAAQ,CAAC,CAACA,IAAIR,cAAc,IAAI,CAAC,CAACQ,IAAIP,UAAU;IAErD;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,SAASgB,oBAAoBT,GAGnC;IACC,MAAMU,QAAkB,EAAE;IAC1B,IAAIV,IAAIR,cAAc,EAAEkB,MAAMpB,IAAI,CAAC,CAAC,iBAAiB,EAAEU,IAAIR,cAAc,EAAE;IAC3E,IAAIQ,IAAIP,UAAU,EAAEiB,MAAMpB,IAAI,CAAC,CAAC,iBAAiB,EAAEU,IAAIP,UAAU,EAAE;IACnE,OAAOiB,MAAMxC,MAAM,GACf,CAAC,gDAAgD,EAAEwC,MAAMrB,IAAI,CAAC,MAAM,EAAE,CAAC,GACvE;AACN"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * Called from the console registrar. The owner is named rather than read off
19
+ * the loader's marker, so the routes register the same way under a spec that
20
+ * calls the registrar directly.
21
+ */
22
+ export declare function registerEmailRecordRoutes(): void;