@wirecat/cli-core 1.0.0-rc.0 → 1.1.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.
Files changed (96) hide show
  1. package/CHANGELOG.md +186 -0
  2. package/THIRD_PARTY_NOTICES +47 -0
  3. package/dist/cli/account-rename.js +1 -1
  4. package/dist/cli/bot/api-input.d.ts +5 -0
  5. package/dist/cli/bot/api-input.js +6 -1
  6. package/dist/cli/bot/api.js +7 -1
  7. package/dist/cli/domain-lists-command.d.ts +16 -0
  8. package/dist/cli/domain-lists-command.js +88 -0
  9. package/dist/cli/index.d.ts +4 -3
  10. package/dist/cli/index.js +3 -2
  11. package/dist/cli/model-catalogue-command.d.ts +6 -0
  12. package/dist/cli/model-catalogue-command.js +1 -1
  13. package/dist/cli/oauth-session.d.ts +38 -4
  14. package/dist/cli/oauth-session.js +66 -22
  15. package/dist/cli/service-api.js +3 -1
  16. package/dist/cli/shared-command-exports.d.ts +2 -0
  17. package/dist/cli/shared-command-exports.js +3 -0
  18. package/dist/cli/token-session.d.ts +9 -0
  19. package/dist/cli/token-session.js +29 -2
  20. package/dist/crm/manifest/map.d.ts +5 -2
  21. package/dist/crm/manifest/map.js +14 -2
  22. package/dist/domain/domain-lists.d.ts +86 -0
  23. package/dist/domain/domain-lists.js +110 -0
  24. package/dist/domain/free-mail-domains.generated.d.ts +1 -0
  25. package/dist/domain/free-mail-domains.generated.js +4 -0
  26. package/dist/domain/organization-sectors.d.ts +16 -0
  27. package/dist/domain/organization-sectors.generated.d.ts +12 -0
  28. package/dist/domain/organization-sectors.generated.js +15 -0
  29. package/dist/domain/organization-sectors.js +22 -0
  30. package/dist/domain/person-kinds.d.ts +5 -0
  31. package/dist/domain/person-kinds.js +5 -0
  32. package/dist/entities/domain-list.d.ts +27 -0
  33. package/dist/entities/domain-list.js +28 -0
  34. package/dist/entities/index.d.ts +20 -1
  35. package/dist/entities/index.js +3 -1
  36. package/dist/entities/knowledge-lists.d.ts +1 -0
  37. package/dist/entities/knowledge-lists.js +2 -0
  38. package/dist/errors/reasons.js +14 -3
  39. package/dist/mail/mail-types.d.ts +48 -0
  40. package/dist/mail/mail-types.js +218 -0
  41. package/dist/mail/score.d.ts +2 -0
  42. package/dist/mail/score.js +9 -2
  43. package/dist/oauth/index.d.ts +1 -1
  44. package/dist/oauth/storage.d.ts +10 -2
  45. package/dist/oauth/storage.js +23 -9
  46. package/dist/services/domain-lists-download.d.ts +26 -0
  47. package/dist/services/domain-lists-download.js +155 -0
  48. package/dist/services/search-all-rank.d.ts +44 -0
  49. package/dist/services/search-all-rank.js +112 -0
  50. package/dist/services/search-all-tracker.d.ts +58 -0
  51. package/dist/services/search-all-tracker.js +155 -0
  52. package/dist/services/search-all.d.ts +1 -8
  53. package/dist/services/search-all.js +18 -199
  54. package/dist/services/tracker-meaning.js +1 -1
  55. package/dist/store/areas.d.ts +1 -0
  56. package/dist/store/index.d.ts +2 -1
  57. package/dist/store/index.js +1 -1
  58. package/dist/store/people.d.ts +30 -0
  59. package/dist/store/people.js +16 -1
  60. package/dist/store/sqlite/accounts.js +3 -1
  61. package/dist/store/sqlite/domain-organizations.d.ts +36 -0
  62. package/dist/store/sqlite/domain-organizations.js +288 -0
  63. package/dist/store/sqlite/email-types.d.ts +79 -0
  64. package/dist/store/sqlite/email-types.js +261 -0
  65. package/dist/store/sqlite/emails.d.ts +11 -2
  66. package/dist/store/sqlite/emails.js +18 -7
  67. package/dist/store/sqlite/identities.d.ts +4 -1
  68. package/dist/store/sqlite/identities.js +11 -2
  69. package/dist/store/sqlite/identity-rekey.js +2 -0
  70. package/dist/store/sqlite/knowledge.d.ts +2 -9
  71. package/dist/store/sqlite/manifest.js +6 -0
  72. package/dist/store/sqlite/merged-persons.d.ts +3 -2
  73. package/dist/store/sqlite/merged-persons.js +5 -3
  74. package/dist/store/sqlite/migrations.generated.js +77 -0
  75. package/dist/store/sqlite/organizations.d.ts +12 -1
  76. package/dist/store/sqlite/organizations.js +9 -1
  77. package/dist/store/sqlite/people-list.js +69 -11
  78. package/dist/store/sqlite/person-links.js +13 -3
  79. package/dist/store/sqlite/person-match-scan.js +14 -1
  80. package/dist/store/sqlite/schema/sender-bots.d.ts +344 -0
  81. package/dist/store/sqlite/schema/sender-bots.js +30 -0
  82. package/dist/store/sqlite/schema.d.ts +49 -0
  83. package/dist/store/sqlite/schema.js +7 -0
  84. package/dist/store/sqlite/sender-bots.d.ts +108 -0
  85. package/dist/store/sqlite/sender-bots.js +431 -0
  86. package/dist/store/sqlite/sender-signals.d.ts +13 -3
  87. package/dist/store/sqlite/sender-signals.js +17 -13
  88. package/dist/store/sqlite/tracker.d.ts +11 -9
  89. package/dist/store/sqlite/tracker.js +27 -12
  90. package/dist/store/sqlite/work-tasks.js +2 -0
  91. package/dist/tracker/cli/index.d.ts +1 -1
  92. package/dist/tracker/cli/index.js +83 -24
  93. package/dist/tracker/sync.js +43 -20
  94. package/dist/tracker/writes.d.ts +28 -0
  95. package/dist/tracker/writes.js +141 -19
  96. package/package.json +3 -3
@@ -0,0 +1,22 @@
1
+ import { FREE_MAIL_DOMAINS } from "./free-mail-domains.generated.js";
2
+ import { SECTOR_DOMAINS } from "./organization-sectors.generated.js";
3
+ /** Sectors only the domain-list pack gives (`domain-lists update`): UT1 has them, Wikidata's table does not. */
4
+ export const PACK_SECTORS = ["gaming_gambling", "adult"];
5
+ /** Most specific first: an organization holding domains of two sectors takes the first. */
6
+ export const SECTORS = [
7
+ ...Object.keys(SECTOR_DOMAINS),
8
+ ...PACK_SECTORS,
9
+ ];
10
+ export const isSector = (value) => SECTORS.includes(value);
11
+ let sectors;
12
+ /** The sector of a registrable domain from the built-in table, lower case as `registrableOf` gives it. */
13
+ export const sectorOfDomain = (domain) => {
14
+ sectors ??= new Map(Object.entries(SECTOR_DOMAINS).flatMap(([sector, domains]) => domains.split(" ").map((one) => [one, sector])));
15
+ return sectors.get(domain);
16
+ };
17
+ let freeMail;
18
+ /** A mailbox provider anyone can sign up to (microlink's MIT list, built in): its domain names no organization. */
19
+ export const isFreeMailDomain = (domain) => {
20
+ freeMail ??= new Set(FREE_MAIL_DOMAINS.split(" "));
21
+ return freeMail.has(domain);
22
+ };
@@ -8,6 +8,11 @@ export declare const PERSON_KINDS: readonly ["person", "organization", "automate
8
8
  export type PersonKind = (typeof PERSON_KINDS)[number];
9
9
  /** What decided a kind, besides the ties that make someone a `person`. @experimental */
10
10
  export type KindSignal = "test-data" | "bot" | "no-reply" | "notification-address" | "auto-submitted" | "null-return-path" | "bulk-mail" | "bulk-never-replied" | "automated-name" | "organization" | "role-address" | "company-name" | "no-tie" | "no-name";
11
+ /**
12
+ * A sender bot's reference, `sender-bot:<id>`: a program that writes to the owner, an entity apart from people.
13
+ * `bot:` names the agents of the `bots` table. @experimental
14
+ */
15
+ export declare const SENDER_BOT_PREFIX = "sender-bot:";
11
16
  /** A sender that is a program: «Notifications», «Рассылка», «no-reply». */
12
17
  export declare const isAutomatedName: (name: string | null) => boolean;
13
18
  /** A legal form or a word only a business calls itself: «ООО Ромашка», «CZECH AIRLINES», «OpenWeather Team». */
@@ -4,6 +4,11 @@
4
4
  * @experimental
5
5
  */
6
6
  export const PERSON_KINDS = ["person", "organization", "automated", "stranger", "unsorted", "test"];
7
+ /**
8
+ * A sender bot's reference, `sender-bot:<id>`: a program that writes to the owner, an entity apart from people.
9
+ * `bot:` names the agents of the `bots` table. @experimental
10
+ */
11
+ export const SENDER_BOT_PREFIX = "sender-bot:";
7
12
  const AUTOMATED_WORDS = new Set([
8
13
  "noreply",
9
14
  "notification",
@@ -0,0 +1,27 @@
1
+ import * as v from "valibot";
2
+ /** One source of the domain-list pack as this computer holds it (`domain-lists list`, `domain-lists update`). */
3
+ export declare const domainList: v.StrictObjectSchema<{
4
+ readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
5
+ readonly title: v.StringSchema<undefined>;
6
+ /**
7
+ * `sector` gives an organization its sector; `freemail` keeps a mailbox provider from making one; `bad` only marks a
8
+ * host known for spam, phishing or malware.
9
+ */
10
+ readonly signal: v.PicklistSchema<["sector", "freemail", "bad"], undefined>;
11
+ /** `non-commercial`: WireCat may use it, a paid service built around it may not. */
12
+ readonly class: v.PicklistSchema<["commercial-ok", "non-commercial"], undefined>;
13
+ readonly licence: v.StringSchema<undefined>;
14
+ readonly licence_url: v.StringSchema<undefined>;
15
+ readonly attribution: v.StringSchema<undefined>;
16
+ readonly homepage: v.StringSchema<undefined>;
17
+ /** Fetched from its source on this computer, since it may not be redistributed. */
18
+ readonly upstream: v.BooleanSchema<undefined>;
19
+ readonly lines: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
20
+ /** Lines per sector or category, as published. */
21
+ readonly tags: v.RecordSchema<v.StringSchema<undefined>, v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>, undefined>;
22
+ /** The pack's build date. */
23
+ readonly version: v.StringSchema<undefined>;
24
+ readonly installed_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
25
+ readonly sha256: v.StringSchema<undefined>;
26
+ readonly path: v.StringSchema<undefined>;
27
+ }, undefined>;
@@ -0,0 +1,28 @@
1
+ import * as v from "valibot";
2
+ import { count, id, text, time } from "./fields.js";
3
+ /** One source of the domain-list pack as this computer holds it (`domain-lists list`, `domain-lists update`). */
4
+ export const domainList = v.strictObject({
5
+ id,
6
+ title: text,
7
+ /**
8
+ * `sector` gives an organization its sector; `freemail` keeps a mailbox provider from making one; `bad` only marks a
9
+ * host known for spam, phishing or malware.
10
+ */
11
+ signal: v.picklist(["sector", "freemail", "bad"]),
12
+ /** `non-commercial`: WireCat may use it, a paid service built around it may not. */
13
+ class: v.picklist(["commercial-ok", "non-commercial"]),
14
+ licence: text,
15
+ licence_url: text,
16
+ attribution: text,
17
+ homepage: text,
18
+ /** Fetched from its source on this computer, since it may not be redistributed. */
19
+ upstream: v.boolean(),
20
+ lines: count,
21
+ /** Lines per sector or category, as published. */
22
+ tags: v.record(v.string(), count),
23
+ /** The pack's build date. */
24
+ version: text,
25
+ installed_at: time,
26
+ sha256: text,
27
+ path: text,
28
+ });
@@ -30,6 +30,7 @@ import { conversationBatch, conversationBatchStatus, conversationBuildResult, co
30
30
  import { counterRefresh, counters } from "./counters.js";
31
31
  import { document } from "./document.js";
32
32
  import { documentLink } from "./document-link.js";
33
+ import { domainList } from "./domain-list.js";
33
34
  import { evidence } from "./evidence.js";
34
35
  import { fact } from "./fact.js";
35
36
  import { reference } from "./fields.js";
@@ -92,7 +93,7 @@ import { topic } from "./topic.js";
92
93
  * subset of its fields, never a renamed one. Commands move onto these one by one; until then, a schema
93
94
  * is the target, not a description of today's output.
94
95
  */
95
- export { account, accountChange, accountPrivacy, accountPrivacyChange, accountProfile, accountSession, adminReport, agenda, analysisConsent, analysisConsentRevocation, attachment, attachmentBytes, attachmentExtraction, attachmentTextChange, automaticTags, botAdmin, botMenuEntry, botProfile, botSeenChat, botTemplate, botWebhook, cachedChatMetadata, callRecord, chart, chat, chatAdminChange, chatArchive, chatCoverage, chatEvent, chatFolderChange, chatFolderOrder, chatFolderRemoval, chatGroupChange, chatInspection, chatInvite, chatInviteChange, chatMembersChange, chatMembersFetch, chatMetadata, chatMetadataRefresh, chatModeration, chatMuting, chatPin, chatRead, chatRemoval, chatRequestChange, chatRules, chatSender, chatSending, chatStats, chatTracking, chatUnread, contact, contactActivity, contactAlias, contactCheck, contactContext, contactImport, contactLookup, contactNote, contactNoteRemoval, contactPreparation, contactStateChange, contactSync, contactUpdate, conversation, conversationBatch, conversationBatchStatus, conversationBuildResult, conversationChange, conversationDetails, conversationEmbedding, conversationEmbeddingStatus, conversationHit, conversationPreparation, conversationReadiness, counterRefresh, counters, document, documentLink, endedAccountSessions, evidence, evidencePacket, fact, folder, hit, identity, imageEmbedding, inviteLink, job, joinRequest, linkedPerson, mailCounts, mediaArchive, mediaArchiveCheck, mediaArchiveMove, mediaArchiveTimer, meeting, meetingProjectCandidates, meetingSeriesInventory, member, memory, mention, mentionDecision, mentionDetails, mentionDomain, mentionRebuild, message, messageContext, messageCounts, messageDeletion, messageDownload, messageEvent, messageLink, messageLinks, messagePin, messageStar, messageSync, messageTranscript, messageWrite, model, modelKey, note, officialStats, organization, person, place, poll, pollChange, pollVote, project, ranking, reaction, reactionChange, recipient, recipientAdded, recipientChange, recipientOff, recipientRemoved, recordedRun, reference, relationship, reminder, removedModelKey, responseTimes, retention, runDetails, runHit, runLocation, savedSearch, scheduledCancellation, scheduledJob, scheduledSend, scheduleHarness, searchHistoryClear, sendAttempt, serveSummary, stickerInventory, storeBackup, storeChatStatus, storeCheck, storeClear, storeCopyRemoval, storeDecrypt, storedModelKey, storeExport, storeGapPlan, storeGapRepair, storeImport, storeInfo, storeJobCancel, storeJobClear, storeJobDetails, storeJobRetry, storeMigration, storeReindex, storeRepair, storeReset, storeRestore, storeTable, tagChange, tagging, task, taskAnalysis, taskAnalysisMark, taskCard, taskCategories, taskClosed, taskCreated, taskLinks, taskMerge, taskPair, taskScan, taskSimilar, taskStats, taskUnmerge, template, topic, topicIcon, trackedChat, trackedChatHistory, waitingChats, watchedMessage, watchItem, };
96
+ export { account, accountChange, accountPrivacy, accountPrivacyChange, accountProfile, accountSession, adminReport, agenda, analysisConsent, analysisConsentRevocation, attachment, attachmentBytes, attachmentExtraction, attachmentTextChange, automaticTags, botAdmin, botMenuEntry, botProfile, botSeenChat, botTemplate, botWebhook, cachedChatMetadata, callRecord, chart, chat, chatAdminChange, chatArchive, chatCoverage, chatEvent, chatFolderChange, chatFolderOrder, chatFolderRemoval, chatGroupChange, chatInspection, chatInvite, chatInviteChange, chatMembersChange, chatMembersFetch, chatMetadata, chatMetadataRefresh, chatModeration, chatMuting, chatPin, chatRead, chatRemoval, chatRequestChange, chatRules, chatSender, chatSending, chatStats, chatTracking, chatUnread, contact, contactActivity, contactAlias, contactCheck, contactContext, contactImport, contactLookup, contactNote, contactNoteRemoval, contactPreparation, contactStateChange, contactSync, contactUpdate, conversation, conversationBatch, conversationBatchStatus, conversationBuildResult, conversationChange, conversationDetails, conversationEmbedding, conversationEmbeddingStatus, conversationHit, conversationPreparation, conversationReadiness, counterRefresh, counters, document, documentLink, domainList, endedAccountSessions, evidence, evidencePacket, fact, folder, hit, identity, imageEmbedding, inviteLink, job, joinRequest, linkedPerson, mailCounts, mediaArchive, mediaArchiveCheck, mediaArchiveMove, mediaArchiveTimer, meeting, meetingProjectCandidates, meetingSeriesInventory, member, memory, mention, mentionDecision, mentionDetails, mentionDomain, mentionRebuild, message, messageContext, messageCounts, messageDeletion, messageDownload, messageEvent, messageLink, messageLinks, messagePin, messageStar, messageSync, messageTranscript, messageWrite, model, modelKey, note, officialStats, organization, person, place, poll, pollChange, pollVote, project, ranking, reaction, reactionChange, recipient, recipientAdded, recipientChange, recipientOff, recipientRemoved, recordedRun, reference, relationship, reminder, removedModelKey, responseTimes, retention, runDetails, runHit, runLocation, savedSearch, scheduledCancellation, scheduledJob, scheduledSend, scheduleHarness, searchHistoryClear, sendAttempt, serveSummary, stickerInventory, storeBackup, storeChatStatus, storeCheck, storeClear, storeCopyRemoval, storeDecrypt, storedModelKey, storeExport, storeGapPlan, storeGapRepair, storeImport, storeInfo, storeJobCancel, storeJobClear, storeJobDetails, storeJobRetry, storeMigration, storeReindex, storeRepair, storeReset, storeRestore, storeTable, tagChange, tagging, task, taskAnalysis, taskAnalysisMark, taskCard, taskCategories, taskClosed, taskCreated, taskLinks, taskMerge, taskPair, taskScan, taskSimilar, taskStats, taskUnmerge, template, topic, topicIcon, trackedChat, trackedChatHistory, waitingChats, watchedMessage, watchItem, };
96
97
  export declare const ENTITIES: {
97
98
  readonly meeting_change: v.StrictObjectSchema<{
98
99
  readonly action: v.PicklistSchema<["create", "update", "cancel"], undefined>;
@@ -4130,6 +4131,7 @@ export declare const ENTITIES: {
4130
4131
  readonly kind: v.PicklistSchema<["company", "team", "family", "community"], undefined>;
4131
4132
  readonly name: v.StringSchema<undefined>;
4132
4133
  readonly scope: v.PicklistSchema<["personal", "work"], undefined>;
4134
+ readonly sector: v.NullableSchema<v.PicklistSchema<import("../domain/organization-sectors.js").Sector[], undefined>, undefined>;
4133
4135
  readonly created_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
4134
4136
  }, undefined>;
4135
4137
  readonly project: v.StrictObjectSchema<{
@@ -10417,6 +10419,23 @@ export declare const ENTITIES: {
10417
10419
  readonly to_embed: v.NullableSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>, undefined>;
10418
10420
  readonly estimate_seconds: v.NullableSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>, undefined>;
10419
10421
  }, undefined>;
10422
+ readonly domain_list: v.StrictObjectSchema<{
10423
+ readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
10424
+ readonly title: v.StringSchema<undefined>;
10425
+ readonly signal: v.PicklistSchema<["sector", "freemail", "bad"], undefined>;
10426
+ readonly class: v.PicklistSchema<["commercial-ok", "non-commercial"], undefined>;
10427
+ readonly licence: v.StringSchema<undefined>;
10428
+ readonly licence_url: v.StringSchema<undefined>;
10429
+ readonly attribution: v.StringSchema<undefined>;
10430
+ readonly homepage: v.StringSchema<undefined>;
10431
+ readonly upstream: v.BooleanSchema<undefined>;
10432
+ readonly lines: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
10433
+ readonly tags: v.RecordSchema<v.StringSchema<undefined>, v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>, undefined>;
10434
+ readonly version: v.StringSchema<undefined>;
10435
+ readonly installed_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
10436
+ readonly sha256: v.StringSchema<undefined>;
10437
+ readonly path: v.StringSchema<undefined>;
10438
+ }, undefined>;
10420
10439
  readonly model_key: v.StrictObjectSchema<{
10421
10440
  readonly provider: v.StringSchema<undefined>;
10422
10441
  readonly stored: v.OptionalSchema<v.PicklistSchema<["environment", "keyring", "file"], undefined>, undefined>;
@@ -34,6 +34,7 @@ import { counterRefresh, counters } from "./counters.js";
34
34
  import { deal, lead, pipeline, stage } from "./deal.js";
35
35
  import { document } from "./document.js";
36
36
  import { documentLink } from "./document-link.js";
37
+ import { domainList } from "./domain-list.js";
37
38
  import { evidence } from "./evidence.js";
38
39
  import { fact } from "./fact.js";
39
40
  import { reference, untrusted } from "./fields.js";
@@ -101,7 +102,7 @@ import { topic } from "./topic.js";
101
102
  * subset of its fields, never a renamed one. Commands move onto these one by one; until then, a schema
102
103
  * is the target, not a description of today's output.
103
104
  */
104
- export { account, accountChange, accountPrivacy, accountPrivacyChange, accountProfile, accountSession, adminReport, agenda, analysisConsent, analysisConsentRevocation, attachment, attachmentBytes, attachmentExtraction, attachmentTextChange, automaticTags, botAdmin, botMenuEntry, botProfile, botSeenChat, botTemplate, botWebhook, cachedChatMetadata, callRecord, chart, chat, chatAdminChange, chatArchive, chatCoverage, chatEvent, chatFolderChange, chatFolderOrder, chatFolderRemoval, chatGroupChange, chatInspection, chatInvite, chatInviteChange, chatMembersChange, chatMembersFetch, chatMetadata, chatMetadataRefresh, chatModeration, chatMuting, chatPin, chatRead, chatRemoval, chatRequestChange, chatRules, chatSender, chatSending, chatStats, chatTracking, chatUnread, contact, contactActivity, contactAlias, contactCheck, contactContext, contactImport, contactLookup, contactNote, contactNoteRemoval, contactPreparation, contactStateChange, contactSync, contactUpdate, conversation, conversationBatch, conversationBatchStatus, conversationBuildResult, conversationChange, conversationDetails, conversationEmbedding, conversationEmbeddingStatus, conversationHit, conversationPreparation, conversationReadiness, counterRefresh, counters, document, documentLink, endedAccountSessions, evidence, evidencePacket, fact, folder, hit, identity, imageEmbedding, inviteLink, job, joinRequest, linkedPerson, mailCounts, mediaArchive, mediaArchiveCheck, mediaArchiveMove, mediaArchiveTimer, meeting, meetingProjectCandidates, meetingSeriesInventory, member, memory, mention, mentionDecision, mentionDetails, mentionDomain, mentionRebuild, message, messageContext, messageCounts, messageDeletion, messageDownload, messageEvent, messageLink, messageLinks, messagePin, messageStar, messageSync, messageTranscript, messageWrite, model, modelKey, note, officialStats, organization, person, place, poll, pollChange, pollVote, project, ranking, reaction, reactionChange, recipient, recipientAdded, recipientChange, recipientOff, recipientRemoved, recordedRun, reference, relationship, reminder, removedModelKey, responseTimes, retention, runDetails, runHit, runLocation, savedSearch, scheduledCancellation, scheduledJob, scheduledSend, scheduleHarness, searchHistoryClear, sendAttempt, serveSummary, stickerInventory, storeBackup, storeChatStatus, storeCheck, storeClear, storeCopyRemoval, storeDecrypt, storedModelKey, storeExport, storeGapPlan, storeGapRepair, storeImport, storeInfo, storeJobCancel, storeJobClear, storeJobDetails, storeJobRetry, storeMigration, storeReindex, storeRepair, storeReset, storeRestore, storeTable, tagChange, tagging, task, taskAnalysis, taskAnalysisMark, taskCard, taskCategories, taskClosed, taskCreated, taskLinks, taskMerge, taskPair, taskScan, taskSimilar, taskStats, taskUnmerge, template, topic, topicIcon, trackedChat, trackedChatHistory, waitingChats, watchedMessage, watchItem, };
105
+ export { account, accountChange, accountPrivacy, accountPrivacyChange, accountProfile, accountSession, adminReport, agenda, analysisConsent, analysisConsentRevocation, attachment, attachmentBytes, attachmentExtraction, attachmentTextChange, automaticTags, botAdmin, botMenuEntry, botProfile, botSeenChat, botTemplate, botWebhook, cachedChatMetadata, callRecord, chart, chat, chatAdminChange, chatArchive, chatCoverage, chatEvent, chatFolderChange, chatFolderOrder, chatFolderRemoval, chatGroupChange, chatInspection, chatInvite, chatInviteChange, chatMembersChange, chatMembersFetch, chatMetadata, chatMetadataRefresh, chatModeration, chatMuting, chatPin, chatRead, chatRemoval, chatRequestChange, chatRules, chatSender, chatSending, chatStats, chatTracking, chatUnread, contact, contactActivity, contactAlias, contactCheck, contactContext, contactImport, contactLookup, contactNote, contactNoteRemoval, contactPreparation, contactStateChange, contactSync, contactUpdate, conversation, conversationBatch, conversationBatchStatus, conversationBuildResult, conversationChange, conversationDetails, conversationEmbedding, conversationEmbeddingStatus, conversationHit, conversationPreparation, conversationReadiness, counterRefresh, counters, document, documentLink, domainList, endedAccountSessions, evidence, evidencePacket, fact, folder, hit, identity, imageEmbedding, inviteLink, job, joinRequest, linkedPerson, mailCounts, mediaArchive, mediaArchiveCheck, mediaArchiveMove, mediaArchiveTimer, meeting, meetingProjectCandidates, meetingSeriesInventory, member, memory, mention, mentionDecision, mentionDetails, mentionDomain, mentionRebuild, message, messageContext, messageCounts, messageDeletion, messageDownload, messageEvent, messageLink, messageLinks, messagePin, messageStar, messageSync, messageTranscript, messageWrite, model, modelKey, note, officialStats, organization, person, place, poll, pollChange, pollVote, project, ranking, reaction, reactionChange, recipient, recipientAdded, recipientChange, recipientOff, recipientRemoved, recordedRun, reference, relationship, reminder, removedModelKey, responseTimes, retention, runDetails, runHit, runLocation, savedSearch, scheduledCancellation, scheduledJob, scheduledSend, scheduleHarness, searchHistoryClear, sendAttempt, serveSummary, stickerInventory, storeBackup, storeChatStatus, storeCheck, storeClear, storeCopyRemoval, storeDecrypt, storedModelKey, storeExport, storeGapPlan, storeGapRepair, storeImport, storeInfo, storeJobCancel, storeJobClear, storeJobDetails, storeJobRetry, storeMigration, storeReindex, storeRepair, storeReset, storeRestore, storeTable, tagChange, tagging, task, taskAnalysis, taskAnalysisMark, taskCard, taskCategories, taskClosed, taskCreated, taskLinks, taskMerge, taskPair, taskScan, taskSimilar, taskStats, taskUnmerge, template, topic, topicIcon, trackedChat, trackedChatHistory, waitingChats, watchedMessage, watchItem, };
105
106
  export const ENTITIES = {
106
107
  sync_progress: syncProgress,
107
108
  deal,
@@ -357,6 +358,7 @@ export const ENTITIES = {
357
358
  chat_rules: chatRules,
358
359
  chat_moderation: chatModeration,
359
360
  "model.chosen": chosenModel,
361
+ domain_list: domainList,
360
362
  model_key: modelKey,
361
363
  chat_sending: chatSending,
362
364
  "model_key.stored": storedModelKey,
@@ -6,6 +6,7 @@ export declare const organization: v.StrictObjectSchema<{
6
6
  readonly kind: v.PicklistSchema<["company", "team", "family", "community"], undefined>;
7
7
  readonly name: v.StringSchema<undefined>;
8
8
  readonly scope: v.PicklistSchema<["personal", "work"], undefined>;
9
+ readonly sector: v.NullableSchema<v.PicklistSchema<import("../domain/organization-sectors.js").Sector[], undefined>, undefined>;
9
10
  readonly created_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
10
11
  }, undefined>;
11
12
  /** @experimental */
@@ -1,4 +1,5 @@
1
1
  import * as v from "valibot";
2
+ import { SECTORS } from "../domain/organization-sectors.js";
2
3
  import { id, reference, text, time } from "./fields.js";
3
4
  /** @experimental */
4
5
  export const organization = v.strictObject({
@@ -7,6 +8,7 @@ export const organization = v.strictObject({
7
8
  kind: v.picklist(["company", "team", "family", "community"]),
8
9
  name: text,
9
10
  scope: v.picklist(["personal", "work"]),
11
+ sector: v.nullable(v.picklist(SECTORS)),
10
12
  created_at: time,
11
13
  });
12
14
  /** @experimental */
@@ -72,7 +72,6 @@ const SIGN_IN = [
72
72
  ["account-rename.unconfirmed", "confirmation_required", "renaming a profile asks first; add --yes"],
73
73
  ["account-rename.moved-run", "permission_error", "a run with moved folders never renames a profile"],
74
74
  ["account-rename.unpaired", "configuration_error", "the tool named different paths for the old and new name"],
75
- ["account-rename.config", "configuration_error", "the config file cannot be read"],
76
75
  ];
77
76
  /** Reasons every CLI over a provider's API raises alike: gcal and drive today. */
78
77
  const PROVIDER_API = [
@@ -142,6 +141,7 @@ const OTHERS = [
142
141
  ["enrichment.owner-only", "permission_error", "only the owner turns enrichment on, not an agent"],
143
142
  ["search-harder.owner-only", "permission_error", "only the owner allows search all --harder, not an agent"],
144
143
  ["model.offline", "permission_error", "downloading a model needs the network; --offline was requested"],
144
+ ["domain-lists.offline", "permission_error", "updating the domain lists needs the network; --offline was requested"],
145
145
  ["model.key-rejected", "invalid_response", "the model provider refused the API key (401 or 403)"],
146
146
  ["model.unreachable", "invalid_response", "the model provider could not be reached over the network"],
147
147
  [
@@ -316,6 +316,7 @@ const OTHERS = [
316
316
  validation("push.too-many-files", "the folder holds more files than one push takes"),
317
317
  validation("push.unreadable", "the folder to push could not be read"),
318
318
  validation("spreadsheet.unreadable", "the workbook could not be read"),
319
+ ["config.unreadable", "configuration_error", "the config file cannot be read"],
319
320
  [
320
321
  "config.unrepairable",
321
322
  "configuration_error",
@@ -543,7 +544,7 @@ const OTHERS = [
543
544
  validation("tracker.unlisted-held", "a tracker's id list would mark too much deleted, or the sign-in read only part; nothing was"),
544
545
  validation("tracker.write-unsupported", "the tracker does not take this write, or does not recognise a repeated one"),
545
546
  validation("tracker.field", "a field of an issue or a comment the tracker's write does not take as given"),
546
- validation("tracker.reference", "a team, state, label, project or user no single row of the copy has by that name"),
547
+ validation("tracker.reference", "a team, state, label, project, user or sprint no single row of the copy has by that name"),
547
548
  validation("tracker.team-required", "a new issue needs its team: name one, or sync a copy that holds one"),
548
549
  ["tracker.no-record", "invalid_response", "the tracker answered a write with no record and no error; sync and look"],
549
550
  [
@@ -604,6 +605,11 @@ const OTHERS = [
604
605
  validation("order.ref", "the reference names no order, or a shop's number names more than one"),
605
606
  validation("order.status", "a rejected or deleted order's status does not change"),
606
607
  ["model.not-downloaded", "not_found", "the model is not downloaded on this machine"],
608
+ [
609
+ "tracker.no-vectors",
610
+ "not_found",
611
+ "no issue, project or comment is embedded with the model yet; sync --embed builds them",
612
+ ],
607
613
  ["person.no-owner", "not_found", "no person is marked as the owner in the store"],
608
614
  ["person.unknown", "not_found", "the store has no person by that reference; people list gives person:<uid>"],
609
615
  ["person.no-doubt", "not_found", "nothing about that person is in doubt; people links check lists who is"],
@@ -619,7 +625,7 @@ const OTHERS = [
619
625
  [
620
626
  "identity.owner-only",
621
627
  "permission_error",
622
- "only the owner undoes a merge, splits a person, confirms or undoes a link, or links an identity to themselves",
628
+ "only the owner undoes or confirms a merge, a split or a link, links an identity to themselves, or moves a sender",
623
629
  ],
624
630
  [
625
631
  "identity.stale",
@@ -657,6 +663,11 @@ const OTHERS = [
657
663
  validation("identity.common-name", "more than six people have the name, so it proposes no one"),
658
664
  validation("identity.not-a-person", "a bot, a program or an organization is never proposed as a person by name"),
659
665
  validation("identity.owner", "one side is the owner's person, and only the owner joins anyone to themselves"),
666
+ ["sender-bot.not-found", "not_found", "no sender bot has that id; the bots list names them"],
667
+ validation("sender-bot.owner", "the owner's own person is never a bot"),
668
+ validation("sender-bot.not-a-person", "the identity named is a sender bot's, not a person's; name a person"),
669
+ validation("sender-bot.empty", "the person or bot named holds no identity to move"),
670
+ validation("sender-bot.assignee", "a sender bot is no one's assignee; move it to a person first"),
660
671
  validation("identity.shared-email", "more than six people share the address, so it proposes no one"),
661
672
  validation("identity-link.dedicated-review", "an identity link is staged and decided through the people review"),
662
673
  validation("identity-split.dedicated-review", "a split of a person is staged and decided through the people review"),
@@ -0,0 +1,48 @@
1
+ import type { Sector } from "../domain/organization-sectors.js";
2
+ import { type Reach } from "../store/sqlite/sender-signals.js";
3
+ /**
4
+ * What one email is, apart from who sent it: a shop's receipt is an `order` and its sale a `promotion`. The first
5
+ * that matches wins, in this order, with one exception: an automated sender's List-Unsubscribe mail with no campaign
6
+ * marker is an `account_notice` before the list types are tried (Zero's rule that keeps receipts out of promotions).
7
+ * `system_alert` comes before `account_notice`: an alert carries Auto-Submitted too, and would never be reached.
8
+ * @experimental
9
+ */
10
+ export declare const MAIL_TYPES: readonly ["auto_reply", "security", "calendar", "travel", "event_ticket", "order", "shipping", "bill", "social_notification", "discussion_list", "newsletter", "promotion", "system_alert", "account_notice", "personal", "other"];
11
+ /** @experimental */
12
+ export type MailType = (typeof MAIL_TYPES)[number];
13
+ /** What the store keeps of one email that its type is worked out from. @experimental */
14
+ export interface MailTypeInput {
15
+ from: string | null;
16
+ subject: string | null;
17
+ /** As `mailHeadersOf` keeps them: what marks a program or a list counts only under the From domain's DKIM. */
18
+ headers: Record<string, unknown>;
19
+ /** To and Cc together; `null` when the store holds no recipients (mail recorded as an envelope). */
20
+ recipients: number | null;
21
+ /** The media types of its parts the store keeps as attachments, lower case. */
22
+ parts: readonly string[];
23
+ /** schema.org types its HTML declares (`Order`, `FlightReservation`). */
24
+ schemaTypes: readonly string[];
25
+ /** Distinct addresses that send to its List-Id. */
26
+ listSenders: number;
27
+ /** The owner sent mail to this address, or this is the owner's own mail. */
28
+ ownerWrote: boolean;
29
+ /** The sender is a sender bot. */
30
+ bot: boolean;
31
+ /** The sector of the organization the sender's address belongs to. */
32
+ sector: Sector | null;
33
+ }
34
+ /** @experimental */
35
+ export interface MailTypeOf {
36
+ type: MailType;
37
+ reach: Reach;
38
+ /** What decided the type; `null` for `other`. */
39
+ signal: string | null;
40
+ }
41
+ /**
42
+ * One email's type, reach and the signal behind the type, from what the store keeps of it alone: no lookup, no model.
43
+ * Mail from someone the owner writes to is typed by what the mail itself carries (a calendar or report part, schema.org
44
+ * markup, list headers), never by an address word or a subject alone: `info@` is often a person. @experimental
45
+ */
46
+ export declare const mailTypeOf: (input: MailTypeInput) => MailTypeOf;
47
+ /** The schema.org types an email's HTML declares, in JSON-LD or microdata, as Gmail's markup reads them. @experimental */
48
+ export declare const schemaTypesOf: (html: string | null) => string[];
@@ -0,0 +1,218 @@
1
+ /*
2
+ * The order of the checks and the AUTOMATED_SENDER and MARKETING_SENDER patterns are ported from Zero's header
3
+ * classifier, apps/server/src/lib/imap/categorize.ts at commit 4b642dfd9890a1fdcb1b98a177fe74ca3142c445:
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2025 Zero Email
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
10
+ * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
11
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
12
+ * permit persons to whom the Software is furnished to do so, subject to the following conditions:
13
+ *
14
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
15
+ * Software.
16
+ *
17
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
18
+ * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19
+ * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
20
+ * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+ */
22
+ import { isNoReplyAddress } from "../domain/addresses.js";
23
+ import { DISCUSSION_SENDERS, reachOfOne } from "../store/sqlite/sender-signals.js";
24
+ /**
25
+ * What one email is, apart from who sent it: a shop's receipt is an `order` and its sale a `promotion`. The first
26
+ * that matches wins, in this order, with one exception: an automated sender's List-Unsubscribe mail with no campaign
27
+ * marker is an `account_notice` before the list types are tried (Zero's rule that keeps receipts out of promotions).
28
+ * `system_alert` comes before `account_notice`: an alert carries Auto-Submitted too, and would never be reached.
29
+ * @experimental
30
+ */
31
+ export const MAIL_TYPES = [
32
+ "auto_reply",
33
+ "security",
34
+ "calendar",
35
+ "travel",
36
+ "event_ticket",
37
+ "order",
38
+ "shipping",
39
+ "bill",
40
+ "social_notification",
41
+ "discussion_list",
42
+ "newsletter",
43
+ "promotion",
44
+ "system_alert",
45
+ "account_notice",
46
+ "personal",
47
+ "other",
48
+ ];
49
+ /** Automated senders: notifications, receipts, alerts (Zero). */
50
+ const AUTOMATED_SENDER = /^(no-?reply|do-?not-?reply|donotreply|notifications?|notify|alerts?|mailer-daemon|postmaster|bounces?|automated|system|accounts?|security|billing|receipts?|orders?|shipping|support|service|updates?)([+._-].*)?@/i;
51
+ /** Marketing senders (Zero). */
52
+ const MARKETING_SENDER = /^(news(letters?)?|marketing|promo(tions?)?|offers?|deals?|sales|hello|hi|team|info|digest)([+._-].*)?@/i;
53
+ const local = (words) => new RegExp(`^(${words})([+._-].*)?@`, "i");
54
+ const MAILER_DAEMON = local("mailer-daemon|postmaster");
55
+ const SECURITY_SENDER = local("security|account-?security|verify|verification|auth|2fa|otp|login|signin|password");
56
+ const ORDER_SENDER = local("orders?|receipts?|order-?confirm(ation)?|purchases?");
57
+ const SHIPPING_SENDER = local("shipping|shipments?|tracking|deliver(y|ies)|dispatch");
58
+ const BILL_SENDER = local("billing|invoices?|payments?|statements?");
59
+ const ALERT_SENDER = local("alerts?|alertmanager|monitoring|monitor|cron|root|ci|builds?|jenkins|nagios|zabbix|sentry");
60
+ const NEWS_SENDER = local("news(letters?)?|digest|editors?|weekly");
61
+ const AUTO_REPLY_SUBJECT = /^(auto(matic)?[ -]?(reply|response)|out of (the )?office|abwesenheit|réponse automatique|respuesta automática|автоответ|автоматический ответ|undeliverable|undelivered mail|delivery status notification|mail delivery (failed|subsystem)|returned mail|failure notice|не доставлено)/iu;
62
+ const SECURITY_SUBJECT = /\b(verification code|security code|one[- ]time (pass)?code|sign[- ]?in (attempt|alert|code)|new (sign[- ]?in|login|device)|log[- ]?in (attempt|alert|code)|password (reset|change)|reset your password|two[- ]factor|2-step|confirm your (email|account)|verify your (email|account|identity))\b|код (подтверждения|для входа|безопасности)|вход в (аккаунт|учётную|учетную)|сброс пароля|código de (verificación|seguridad|acceso)|restablecer (tu |la )?contraseña|inicio de sesión/iu;
63
+ const TRAVEL_SUBJECT = /\b(boarding pass|e-?ticket|itinerary|flight (confirmation|booking|reservation)|booking confirm(ation|ed)|check[- ]in (now|is open|online))\b|посадочный талон|маршрутная квитанция|tarjeta de embarque|confirmación de (reserva|vuelo)/iu;
64
+ const EVENT_SUBJECT = /\b(your tickets?|ticket confirmation|tickets? for)\b|билеты? на|tus entradas|entradas para/iu;
65
+ const ORDER_SUBJECT = /\b(order (confirmation|confirmed|received|#|no\.?|number)|your order|thank(s| you) for your (order|purchase)|purchase confirmation|your receipt|receipt for|payment receipt)\b|ваш заказ|заказ (№|#|оформлен|принят)|tu pedido|confirmación de (pedido|compra)/iu;
66
+ const SHIPPING_SUBJECT = /\b(has (been )?shipped|out for delivery|has been delivered|on (its|the) way|tracking (number|info)|track your (order|package|parcel)|shipment|dispatched)\b|отправлен|доставлен|посылк|tu (pedido|paquete) (ha sido enviado|está en camino)|en camino/iu;
67
+ const BILL_SUBJECT = /\b(invoice|statement (is )?(ready|available)|your (monthly |account )?statement|payment (due|reminder|received|confirmation|failed)|bill (is )?(ready|due)|your bill)\b|сч[её]т (на оплату|№|#)|выписка|квитанция|factura|extracto|recibo de pago/iu;
68
+ const ALERT_SUBJECT = /^\[(firing|resolved|alert)|\b(build (failed|passed|fixed|broken)|pipeline (failed|succeeded)|cron <|is down|downtime)\b/iu;
69
+ const PROMOTION_SUBJECT = /\d+\s?%|\b(sale|discount|deals?|offers?|coupon|promo(code)?|free shipping|black friday|cyber monday|limited time|last chance)\b|скидк|распродаж|промокод|descuento|oferta|rebajas|cupón/iu;
70
+ const NEWS_SUBJECT = /\b(newsletter|digest|weekly|monthly|issue\s?#?\d+|edition)\b|рассылка|дайджест|boletín/iu;
71
+ const REPORT_PARTS = new Set(["message/delivery-status", "message/disposition-notification"]);
72
+ const CALENDAR_PARTS = new Set(["text/calendar", "application/ics"]);
73
+ const TRAVEL_SCHEMA = /^(Flight|Train|Bus|Lodging|RentalCar|Taxi|Boat)Reservation$/;
74
+ const schemaOf = (types, wanted) => types.find((one) => (typeof wanted === "string" ? one === wanted : wanted.test(one)));
75
+ /**
76
+ * One email's type, reach and the signal behind the type, from what the store keeps of it alone: no lookup, no model.
77
+ * Mail from someone the owner writes to is typed by what the mail itself carries (a calendar or report part, schema.org
78
+ * markup, list headers), never by an address word or a subject alone: `info@` is often a person. @experimental
79
+ */
80
+ export const mailTypeOf = (input) => {
81
+ const { headers } = input;
82
+ const from = input.from ?? "";
83
+ const subject = input.subject ?? "";
84
+ const oneClick = headers["list-unsubscribe-post"] === true;
85
+ const feedbackId = headers["feedback-id"] === true;
86
+ const listUnsubscribe = headers["list-unsubscribe"] === true;
87
+ const listId = typeof headers["list-id"] === "string";
88
+ const precedence = typeof headers.precedence === "string" ? headers.precedence : "";
89
+ const bulkPrecedence = precedence === "bulk" || precedence === "junk";
90
+ const autoSubmitted = headers["auto-submitted"] !== undefined;
91
+ // With a List-Id, its senders decide: one sender, even under `+tag` addresses, writes a newsletter.
92
+ const discussion = listId
93
+ ? input.listSenders >= DISCUSSION_SENDERS
94
+ : precedence === "list" && !feedbackId && !MARKETING_SENDER.test(from);
95
+ const mass = listUnsubscribe || bulkPrecedence || listId || oneClick;
96
+ const transactional = !mass && !feedbackId;
97
+ const noReply = from !== "" && isNoReplyAddress(from);
98
+ const person = input.ownerWrote && !input.bot;
99
+ // A forged `security@` would lend a phishing mail the look of a real alert.
100
+ const trusted = headers.dmarc !== "fail" && headers.dkim !== "fail";
101
+ const weak = !person && !oneClick && !listId;
102
+ const reach = reachOfOne({
103
+ autoSubmitted,
104
+ nullReturnPath: headers["null-return-path"] === true,
105
+ oneClick,
106
+ feedbackId,
107
+ bulk: mass || precedence === "list",
108
+ discussionList: discussion,
109
+ recipients: input.recipients,
110
+ }).reach;
111
+ const typed = (type, signal) => ({ type, reach, signal });
112
+ const schema = (wanted) => schemaOf(input.schemaTypes, wanted);
113
+ const report = input.parts.find((part) => REPORT_PARTS.has(part));
114
+ if (report !== undefined)
115
+ return typed("auto_reply", report);
116
+ if (MAILER_DAEMON.test(from))
117
+ return typed("auto_reply", "mailer-daemon");
118
+ if (!mass && AUTO_REPLY_SUBJECT.test(subject))
119
+ return typed("auto_reply", "auto-reply-subject");
120
+ if (weak && trusted && SECURITY_SENDER.test(from))
121
+ return typed("security", "security-address");
122
+ if (weak && trusted && SECURITY_SUBJECT.test(subject))
123
+ return typed("security", "security-subject");
124
+ const calendar = input.parts.find((part) => CALENDAR_PARTS.has(part));
125
+ if (calendar !== undefined)
126
+ return typed("calendar", calendar);
127
+ const travel = schema(TRAVEL_SCHEMA);
128
+ if (travel !== undefined)
129
+ return typed("travel", `schema:${travel}`);
130
+ if (weak && TRAVEL_SUBJECT.test(subject))
131
+ return typed("travel", "travel-subject");
132
+ if (weak && transactional && input.sector === "airline")
133
+ return typed("travel", "sector:airline");
134
+ if (schema("EventReservation") !== undefined)
135
+ return typed("event_ticket", "schema:EventReservation");
136
+ if (weak && EVENT_SUBJECT.test(subject))
137
+ return typed("event_ticket", "ticket-subject");
138
+ if (schema("Order") !== undefined)
139
+ return typed("order", "schema:Order");
140
+ if (weak && ORDER_SENDER.test(from))
141
+ return typed("order", "order-address");
142
+ // "Your order has shipped" names the order but reports the parcel.
143
+ if (weak && ORDER_SUBJECT.test(subject) && !SHIPPING_SUBJECT.test(subject))
144
+ return typed("order", "order-subject");
145
+ if (schema("ParcelDelivery") !== undefined)
146
+ return typed("shipping", "schema:ParcelDelivery");
147
+ if (weak && SHIPPING_SENDER.test(from))
148
+ return typed("shipping", "shipping-address");
149
+ if (weak && SHIPPING_SUBJECT.test(subject))
150
+ return typed("shipping", "shipping-subject");
151
+ if (weak && transactional && input.sector === "delivery")
152
+ return typed("shipping", "sector:delivery");
153
+ if (schema("Invoice") !== undefined)
154
+ return typed("bill", "schema:Invoice");
155
+ if (weak && BILL_SENDER.test(from))
156
+ return typed("bill", "bill-address");
157
+ if (weak && BILL_SUBJECT.test(subject))
158
+ return typed("bill", "bill-subject");
159
+ if (!person && input.sector === "social")
160
+ return typed("social_notification", "sector:social");
161
+ if (discussion)
162
+ return typed("discussion_list", listId ? "discussion-list" : "precedence-list");
163
+ // Transactional mail sometimes carries List-Unsubscribe: an automated sender with no campaign marker sends notices.
164
+ const automated = AUTOMATED_SENDER.test(from) && !MARKETING_SENDER.test(from);
165
+ if (listUnsubscribe && !oneClick && !feedbackId && !bulkPrecedence && automated)
166
+ return typed("account_notice", "automated-address");
167
+ if (mass || feedbackId) {
168
+ if (PROMOTION_SUBJECT.test(subject))
169
+ return typed("promotion", "promotion-subject");
170
+ if (MARKETING_SENDER.test(from) && !NEWS_SENDER.test(from))
171
+ return typed("promotion", "marketing-address");
172
+ if (listId)
173
+ return typed("newsletter", "list-id");
174
+ if (NEWS_SENDER.test(from))
175
+ return typed("newsletter", "newsletter-address");
176
+ if (NEWS_SUBJECT.test(subject))
177
+ return typed("newsletter", "newsletter-subject");
178
+ if (input.sector === "news")
179
+ return typed("newsletter", "sector:news");
180
+ if (!input.bot && !noReply)
181
+ return typed("newsletter", "person-sender");
182
+ return typed("promotion", oneClick ? "one-click-unsubscribe" : feedbackId ? "feedback-id" : "bulk-mail");
183
+ }
184
+ if (!person && (ALERT_SENDER.test(from) || ALERT_SUBJECT.test(subject)))
185
+ return typed("system_alert", ALERT_SENDER.test(from) ? "alert-address" : "alert-subject");
186
+ if (!person && autoSubmitted)
187
+ return typed("account_notice", "auto-submitted");
188
+ if (!person && noReply)
189
+ return typed("account_notice", "no-reply");
190
+ if (!person && AUTOMATED_SENDER.test(from))
191
+ return typed("account_notice", "automated-address");
192
+ if (person)
193
+ return typed("personal", "owner-wrote");
194
+ if (!input.bot && headers["null-return-path"] !== true)
195
+ return typed("personal", "person");
196
+ return typed("other", null);
197
+ };
198
+ const JSON_LD_OPEN = /<script[^>]*type\s*=\s*["']?application\/ld\+json[^>]*>/gi;
199
+ const ITEM_TYPE = /\bitemtype\s*=\s*["']?https?:\/\/schema\.org\/([A-Za-z]+)/gi;
200
+ const LD_TYPE = /"@type"\s*:\s*"(?:https?:\/\/schema\.org\/)?([A-Za-z]+)"/g;
201
+ /** The schema.org types an email's HTML declares, in JSON-LD or microdata, as Gmail's markup reads them. @experimental */
202
+ export const schemaTypesOf = (html) => {
203
+ if (html === null || html === "")
204
+ return [];
205
+ const found = new Set();
206
+ for (const open of html.matchAll(JSON_LD_OPEN)) {
207
+ const start = open.index + open[0].length;
208
+ const end = html.indexOf("</script>", start);
209
+ // An unclosed block ends the scan: every later opener would search to the end again.
210
+ if (end === -1)
211
+ break;
212
+ for (const [, type] of html.slice(start, end).matchAll(LD_TYPE))
213
+ found.add(type);
214
+ }
215
+ for (const [, type] of html.matchAll(ITEM_TYPE))
216
+ found.add(type);
217
+ return [...found];
218
+ };
@@ -42,6 +42,8 @@ export declare const registrableOf: (address: string) => string;
42
42
  * looked up; a brand display name sent from one of them is the classic scam.
43
43
  */
44
44
  export declare const FREE_MAIL: Set<string>;
45
+ /** A throwaway mail domain (CC0 list); `domain` is lower case, as `registrableOf` gives it. */
46
+ export declare const isDisposableDomain: (domain: string) => boolean;
45
47
  /**
46
48
  * The brand a display name claims while the address belongs to someone else, if any. "Google via LinkedIn" from
47
49
  * LinkedIn's own domain is LinkedIn passing a page on; "PayPal via Desk" from anywhere else is still judged whole.
@@ -1,4 +1,4 @@
1
- import { isDisposableEmailDomain } from "disposable-email-domains-js";
1
+ import { disposableEmailBlocklistSet } from "disposable-email-domains-js";
2
2
  import { getDomain } from "tldts";
3
3
  /**
4
4
  * How much each sign of spam, a scam or a robot adds to a sender's score. Gmail filters spam before it reaches
@@ -66,6 +66,13 @@ export const FREE_MAIL = new Set([
66
66
  "rambler.ru",
67
67
  "zoho.com",
68
68
  ]);
69
+ let disposable;
70
+ // `isDisposableEmailDomain` builds its set of about 9,000 domains on every call.
71
+ /** A throwaway mail domain (CC0 list); `domain` is lower case, as `registrableOf` gives it. */
72
+ export const isDisposableDomain = (domain) => {
73
+ disposable ??= disposableEmailBlocklistSet();
74
+ return disposable.has(domain);
75
+ };
69
76
  /** A brand and the first labels of the domains it really sends from. */
70
77
  const BRANDS = {
71
78
  paypal: ["paypal"],
@@ -160,7 +167,7 @@ export const scoreGroup = (items, context) => {
160
167
  const stamped = items.filter((item) => item.headers?.auth !== undefined);
161
168
  if (stamped.length && most(stamped, (item) => item.headers?.auth?.dkim !== "pass"))
162
169
  signals.push("dkim_not_passed");
163
- if (domain !== undefined && isDisposableEmailDomain(domain))
170
+ if (domain !== undefined && isDisposableDomain(domain))
164
171
  signals.push("disposable_domain");
165
172
  if (context.bulk >= 0.8 && !context.replied)
166
173
  signals.push("bulk_never_replied");
@@ -3,4 +3,4 @@ export { type ClientFileOptions, readClientFile } from "./client-file.js";
3
3
  export { type SignInOptions, type TokenKeeper, type TokenKeeperOptions, type TokensOptions, tokenKeeper, } from "./keeper.js";
4
4
  export { type AppSource, type ExchangeContext, googleProvider, type OAuthClient, type OAuthProvider, type RequestContext, type TokenSet, } from "./provider.js";
5
5
  export { requestTokens, revokeToken, TOKEN_LOG_ALLOW, TOKEN_LOG_EVENT } from "./requests.js";
6
- export { accountTokenCodec, type CredentialStorageOptions, credentialStorage, driveSessionCodec, type EncodeInput, googleTokenCodec, oauthAccount, type StoredTokens, standardCodec, type TokenCodec, type TokenStorage, zoomTokenCodec, } from "./storage.js";
6
+ export { accountTokenCodec, type CredentialStorageOptions, credentialStorage, driveSessionCodec, type EncodeInput, googleTokenCodec, type LegacyAccount, oauthAccount, type StoredTokens, standardCodec, type TokenCodec, type TokenStorage, zoomTokenCodec, } from "./storage.js";