@wirecat/cli-core 1.0.0 → 1.2.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 (111) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/THIRD_PARTY_NOTICES +43 -0
  3. package/dist/background/daily-archive-timer.d.ts +1 -1
  4. package/dist/cli/account-remove.d.ts +3 -0
  5. package/dist/cli/account-remove.js +1 -1
  6. package/dist/cli/documents/index.d.ts +2 -1
  7. package/dist/cli/documents/index.js +4 -1
  8. package/dist/cli/documents/words.d.ts +1 -1
  9. package/dist/cli/domain-lists-command.d.ts +16 -0
  10. package/dist/cli/domain-lists-command.js +88 -0
  11. package/dist/cli/index.d.ts +4 -3
  12. package/dist/cli/index.js +4 -3
  13. package/dist/cli/messenger/conversation-answers.d.ts +2 -0
  14. package/dist/cli/messenger/message-answers.d.ts +2 -0
  15. package/dist/cli/messenger/message-items.js +2 -0
  16. package/dist/cli/messenger/message-writes.d.ts +4 -0
  17. package/dist/cli/messenger/search-answers.js +2 -0
  18. package/dist/cli/model-catalogue-command.d.ts +6 -0
  19. package/dist/cli/model-catalogue-command.js +1 -1
  20. package/dist/cli/oauth-session.d.ts +38 -4
  21. package/dist/cli/oauth-session.js +72 -25
  22. package/dist/cli/shared-command-exports.d.ts +4 -0
  23. package/dist/cli/shared-command-exports.js +6 -0
  24. package/dist/cli/token-session.d.ts +9 -3
  25. package/dist/cli/token-session.js +34 -3
  26. package/dist/domain/domain-lists.d.ts +86 -0
  27. package/dist/domain/domain-lists.js +110 -0
  28. package/dist/domain/free-mail-domains.generated.d.ts +1 -0
  29. package/dist/domain/free-mail-domains.generated.js +4 -0
  30. package/dist/domain/models.d.ts +5 -0
  31. package/dist/domain/organization-sectors.d.ts +9 -3
  32. package/dist/domain/organization-sectors.generated.d.ts +1 -0
  33. package/dist/domain/organization-sectors.generated.js +1 -0
  34. package/dist/domain/organization-sectors.js +16 -3
  35. package/dist/domain/person-kinds.d.ts +6 -1
  36. package/dist/domain/person-kinds.js +5 -0
  37. package/dist/entities/contact-context.d.ts +4 -0
  38. package/dist/entities/conversation-results.d.ts +4 -0
  39. package/dist/entities/domain-list.d.ts +27 -0
  40. package/dist/entities/domain-list.js +28 -0
  41. package/dist/entities/evidence.d.ts +16 -0
  42. package/dist/entities/index.d.ts +56 -2
  43. package/dist/entities/index.js +3 -1
  44. package/dist/entities/knowledge-lists.d.ts +1 -1
  45. package/dist/entities/listener.d.ts +8 -0
  46. package/dist/entities/message-change.d.ts +2 -0
  47. package/dist/entities/message-context.d.ts +6 -0
  48. package/dist/entities/message-write.d.ts +8 -0
  49. package/dist/entities/message.d.ts +4 -0
  50. package/dist/entities/message.js +4 -0
  51. package/dist/entities/store-records.d.ts +2 -0
  52. package/dist/errors/reasons.js +20 -2
  53. package/dist/mail/cli/index.js +1 -1
  54. package/dist/mail/headers.d.ts +2 -0
  55. package/dist/mail/headers.js +2 -1
  56. package/dist/mail/mail-types.d.ts +48 -0
  57. package/dist/mail/mail-types.js +218 -0
  58. package/dist/mail/read.js +1 -0
  59. package/dist/mail/sort-rules.d.ts +58 -0
  60. package/dist/mail/sort-rules.js +79 -0
  61. package/dist/oauth/index.d.ts +1 -1
  62. package/dist/oauth/storage.d.ts +10 -2
  63. package/dist/oauth/storage.js +23 -9
  64. package/dist/search/lucene/registry.js +24 -0
  65. package/dist/services/domain-lists-download.d.ts +26 -0
  66. package/dist/services/domain-lists-download.js +155 -0
  67. package/dist/services/messages-search.js +1 -1
  68. package/dist/services/metadata.d.ts +1 -1
  69. package/dist/store/areas.d.ts +3 -1
  70. package/dist/store/areas.js +2 -0
  71. package/dist/store/index.d.ts +2 -2
  72. package/dist/store/index.js +1 -1
  73. package/dist/store/people.d.ts +18 -9
  74. package/dist/store/people.js +8 -7
  75. package/dist/store/public.d.ts +1 -1
  76. package/dist/store/public.js +1 -1
  77. package/dist/store/queries.js +9 -2
  78. package/dist/store/sqlite/accounts.js +3 -1
  79. package/dist/store/sqlite/domain-organizations.d.ts +7 -4
  80. package/dist/store/sqlite/domain-organizations.js +94 -36
  81. package/dist/store/sqlite/email-types.d.ts +87 -0
  82. package/dist/store/sqlite/email-types.js +296 -0
  83. package/dist/store/sqlite/emails.d.ts +14 -2
  84. package/dist/store/sqlite/emails.js +32 -12
  85. package/dist/store/sqlite/identities.d.ts +4 -1
  86. package/dist/store/sqlite/identities.js +11 -2
  87. package/dist/store/sqlite/identity-rekey.js +2 -0
  88. package/dist/store/sqlite/lucene-fields.d.ts +6 -0
  89. package/dist/store/sqlite/lucene-fields.js +10 -0
  90. package/dist/store/sqlite/lucene.js +6 -0
  91. package/dist/store/sqlite/mail-sorting.d.ts +122 -0
  92. package/dist/store/sqlite/mail-sorting.js +482 -0
  93. package/dist/store/sqlite/manifest.js +6 -0
  94. package/dist/store/sqlite/merged-persons.d.ts +3 -2
  95. package/dist/store/sqlite/merged-persons.js +5 -3
  96. package/dist/store/sqlite/migrations.generated.js +76 -0
  97. package/dist/store/sqlite/people-list.d.ts +1 -6
  98. package/dist/store/sqlite/people-list.js +97 -42
  99. package/dist/store/sqlite/person-links.js +13 -3
  100. package/dist/store/sqlite/person-match-scan.js +5 -2
  101. package/dist/store/sqlite/schema/mail-sorting.d.ts +384 -0
  102. package/dist/store/sqlite/schema/mail-sorting.js +31 -0
  103. package/dist/store/sqlite/schema/sender-bots.d.ts +56 -0
  104. package/dist/store/sqlite/schema/sender-bots.js +9 -1
  105. package/dist/store/sqlite/schema.d.ts +66 -1
  106. package/dist/store/sqlite/schema.js +9 -1
  107. package/dist/store/sqlite/sender-bots.d.ts +89 -15
  108. package/dist/store/sqlite/sender-bots.js +417 -136
  109. package/dist/store/sqlite/sender-signals.d.ts +11 -4
  110. package/dist/store/sqlite/sender-signals.js +14 -10
  111. package/package.json +2 -2
@@ -1,16 +1,125 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { releaseDomainHolds } from "./domain-organizations.js";
2
+ import { displayName } from "../../domain/display-names.js";
3
+ import { SENDER_BOT_PREFIX } from "../../domain/person-kinds.js";
4
+ import { fold } from "../normalize.js";
5
+ import { groupByDomain, releaseDomainHolds } from "./domain-organizations.js";
3
6
  import { currentPerson } from "./merged-persons.js";
4
- import { isOwner, mergePerson, move, recordOf, renameAfterLeaving, required, unlinkIdentity } from "./person-links.js";
5
- import { write } from "./transaction.js";
6
- export const SENDER_BOT_PREFIX = "sender-bot:";
7
- export const senderBotsOf = (database) => new Map(database
8
- .prepare("SELECT id, person_id, author, name FROM sender_bots")
9
- .all()
10
- .map((row) => [
11
- Number(row.person_id),
12
- { id: Number(row.id), author: row.author, name: row.name == null ? null : String(row.name) },
13
- ]));
7
+ import { isOwner, mergePerson, move, recordOf, renameAfterLeaving } from "./person-links.js";
8
+ import { SMALL_GROUP_MEMBERS } from "./person-ties.js";
9
+ import { LIST_ID, senderSignalsOf, sentMailOf } from "./sender-signals.js";
10
+ import { read, write } from "./transaction.js";
11
+ const MIN_QUERY = 3;
12
+ const HOLDS = "EXISTS (SELECT 1 FROM sender_bot_identities h WHERE h.bot_id = b.id)";
13
+ const SHOWN = "coalesce(b.name, (SELECT coalesce(i.name, i.username, i.external_id) FROM sender_bot_identities s " +
14
+ "JOIN identities i ON i.id = s.identity_id WHERE s.bot_id = b.id ORDER BY i.name IS NULL, i.id LIMIT 1))";
15
+ const refOf = (side) => side.person !== undefined
16
+ ? `person:${side.person}`
17
+ : side.bot !== undefined
18
+ ? `${SENDER_BOT_PREFIX}${side.bot}`
19
+ : null;
20
+ const holderOf = (database, identity) => {
21
+ const linked = database.prepare("SELECT person_id FROM identity_links WHERE identity_id = ?").get(identity);
22
+ if (linked !== undefined)
23
+ return { person: Number(linked.person_id) };
24
+ const held = database.prepare("SELECT bot_id FROM sender_bot_identities WHERE identity_id = ?").get(identity);
25
+ return held === undefined ? {} : { bot: Number(held.bot_id) };
26
+ };
27
+ const identitiesOf = (database, person) => database
28
+ .prepare("SELECT identity_id FROM identity_links WHERE person_id = ? ORDER BY identity_id")
29
+ .all(person)
30
+ .map((row) => Number(row.identity_id));
31
+ const botIdentitiesOf = (database, bot) => database
32
+ .prepare("SELECT identity_id FROM sender_bot_identities WHERE bot_id = ? ORDER BY identity_id")
33
+ .all(bot)
34
+ .map((row) => Number(row.identity_id));
35
+ const logMove = (database, identity, from, to, { author, reason, at }) => database
36
+ .prepare("INSERT INTO sender_bot_moves (identity_id, from_person_id, from_bot_id, to_person_id, to_bot_id, author, " +
37
+ "reason, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
38
+ .run(identity, from.person ?? null, from.bot ?? null, to.person ?? null, to.bot ?? null, author, reason, at);
39
+ /** `person_id` only keeps builds before version 75 from reading the bot as a person: a negative one names none. */
40
+ const createBot = (database, { author, reason, at }, name = null) => Number(database
41
+ .prepare("INSERT INTO sender_bots (person_id, name, author, reason, created_at, updated_at) " +
42
+ "VALUES ((SELECT min(0, coalesce(min(person_id), 0)) - 1 FROM sender_bots), ?, ?, ?, ?, ?) RETURNING id")
43
+ .get(name, author, reason, at, at)?.id);
44
+ /** A person every identity left for a bot is stored as a merge's emptied person is: no list shows them. */
45
+ const retireEmptied = (database, people) => {
46
+ const retire = database.prepare("UPDATE persons SET kind = 'merged' WHERE id = ? AND NOT EXISTS (SELECT 1 FROM identity_links WHERE person_id = ?)");
47
+ for (const person of people)
48
+ retire.run(person, person);
49
+ };
50
+ /**
51
+ * Moves identities to a bot, off a person or another bot, each move logged. Answers the people each left, and which
52
+ * identities. The caller holds the write lock.
53
+ */
54
+ const intoBot = (database, identities, bot, log) => {
55
+ const left = new Map();
56
+ for (const identity of identities) {
57
+ const from = holderOf(database, identity);
58
+ if (from.bot === bot)
59
+ continue;
60
+ if (from.person !== undefined) {
61
+ database.prepare("DELETE FROM identity_links WHERE identity_id = ?").run(identity);
62
+ left.set(from.person, [...(left.get(from.person) ?? []), identity]);
63
+ }
64
+ if (from.bot !== undefined)
65
+ database.prepare("UPDATE sender_bot_identities SET bot_id = ? WHERE identity_id = ?").run(bot, identity);
66
+ else
67
+ database
68
+ .prepare("INSERT INTO sender_bot_identities (identity_id, bot_id, created_at) VALUES (?, ?, ?)")
69
+ .run(identity, bot, log.at);
70
+ logMove(database, identity, from, { bot }, log);
71
+ }
72
+ retireEmptied(database, left.keys());
73
+ return left;
74
+ };
75
+ /** The person an identity last left for a bot, as that person is now; `undefined` when it came from none. */
76
+ const originOf = (database, identity) => {
77
+ const row = database
78
+ .prepare("SELECT m.from_person_id FROM sender_bot_moves m JOIN persons p ON p.id = m.from_person_id " +
79
+ "WHERE m.identity_id = ? AND m.to_bot_id IS NOT NULL ORDER BY m.id DESC LIMIT 1")
80
+ .get(identity);
81
+ return row === undefined ? undefined : currentPerson(database, Number(row.from_person_id));
82
+ };
83
+ const newPerson = (database, identity, at) => Number(database
84
+ .prepare("INSERT INTO persons (name, created_at, updated_at) VALUES ((SELECT name FROM identities WHERE id = ?), ?, ?) " +
85
+ "RETURNING id")
86
+ .get(identity, at, at)?.id);
87
+ /**
88
+ * Gives a bot's identities to a person: `to`, else the person each came from, else a person row of its own. The bot
89
+ * goes with its last identity. Answers the person each went to. The caller holds the write lock.
90
+ */
91
+ const outOfBot = (database, identities, to, log) => {
92
+ const by = log.author === "owner" ? "owner" : "rules";
93
+ const went = new Map();
94
+ for (const identity of identities) {
95
+ const from = holderOf(database, identity);
96
+ if (from.bot === undefined)
97
+ continue;
98
+ database.prepare("DELETE FROM sender_bot_identities WHERE identity_id = ?").run(identity);
99
+ const target = to ?? originOf(database, identity) ?? newPerson(database, identity, log.at);
100
+ database
101
+ .prepare("INSERT INTO identity_links (identity_id, person_id, method, confidence, created_at, author, updated_at) " +
102
+ "VALUES (?, ?, 'bot', 1, ?, ?, ?)")
103
+ .run(identity, target, log.at, by, log.at);
104
+ database
105
+ .prepare("INSERT INTO identity_link_events (identity_id, from_person_id, to_person_id, method, created_at, author) " +
106
+ "VALUES (?, NULL, ?, 'bot', ?, ?)")
107
+ .run(identity, target, log.at, by);
108
+ logMove(database, identity, from, { person: target }, log);
109
+ went.set(identity, target);
110
+ }
111
+ return went;
112
+ };
113
+ /**
114
+ * The source re-keyed `from` onto `to`, both stored: a bot holding `from` takes `to` from its person, since one
115
+ * account is one program. The person it leaves is hidden as `intoBot` hides one. The caller holds the write lock.
116
+ */
117
+ export const rekeyIntoBot = (database, from, to, at) => {
118
+ const bot = holderOf(database, from).bot;
119
+ if (bot === undefined || holderOf(database, to).bot !== undefined)
120
+ return;
121
+ intoBot(database, [to], bot, { author: "rules", reason: "the source re-keyed the identity", at });
122
+ };
14
123
  /** People holding an identity the owner last moved to a person, or kept as one: no rule makes them a bot. */
15
124
  export const ownerPeopleOf = (database) => new Set(database
16
125
  .prepare("SELECT DISTINCT l.person_id AS person FROM sender_bot_moves m JOIN identity_links l ON l.identity_id = m.identity_id " +
@@ -18,172 +127,344 @@ export const ownerPeopleOf = (database) => new Set(database
18
127
  "AND m.id = (SELECT max(id) FROM sender_bot_moves WHERE identity_id = m.identity_id)")
19
128
  .all()
20
129
  .map((row) => Number(row.person)));
130
+ /** A person every identity left for a bot is no one's assignee: the bot has no tasks. */
21
131
  export const refuseBotAssignee = (database, person) => {
22
- if (database.prepare("SELECT 1 FROM sender_bots WHERE person_id = ?").get(person) !== undefined)
23
- throw new CliError("validation_error", `person:${person} is a sender bot, which is no one's assignee`, {
24
- reason: "sender-bot.assignee",
25
- });
132
+ const bot = database
133
+ .prepare("SELECT m.to_bot_id FROM sender_bot_moves m WHERE m.from_person_id = ? AND m.to_bot_id IS NOT NULL " +
134
+ "AND NOT EXISTS (SELECT 1 FROM identity_links WHERE person_id = ?) ORDER BY m.id DESC LIMIT 1")
135
+ .get(person, person);
136
+ if (bot !== undefined)
137
+ throw new CliError("validation_error", `person:${person} moved to ${SENDER_BOT_PREFIX}${bot.to_bot_id}, which is no one's assignee`, { reason: "sender-bot.assignee" });
26
138
  };
27
- const identitiesOf = (database, person) => database
28
- .prepare("SELECT identity_id FROM identity_links WHERE person_id = ? ORDER BY identity_id")
29
- .all(person)
30
- .map((row) => Number(row.identity_id));
31
- const logMoves = (database, identities, from, to, { author, reason, at }) => {
32
- const row = database.prepare("INSERT INTO sender_bot_moves (identity_id, from_person_id, from_bot_id, to_person_id, to_bot_id, author, reason, " +
33
- "created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
34
- for (const identity of identities)
35
- row.run(identity, from.person ?? null, from.bot ?? null, to.person ?? null, to.bot ?? null, author, reason, at);
36
- };
37
- const createBot = (database, person, { author, reason, at, name = null }) => Number(database
38
- .prepare("INSERT INTO sender_bots (person_id, name, author, reason, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) " +
39
- "RETURNING id")
40
- .get(person, name, author, reason, at, at)?.id);
41
- /** A rule's move of a whole person to a bot, or of a rule's bot back to a person; the caller holds the write lock. */
42
- export const ruleMove = (database, person, to, reason, at) => {
43
- const identities = identitiesOf(database, person);
44
- const options = { author: "rules", reason, at };
45
- if (to === "bot") {
46
- const bot = createBot(database, person, options);
47
- logMoves(database, identities, { person }, { bot }, options);
48
- return;
139
+ /** A rule's move of a whole person to a new bot; answers the bot. The caller holds the write lock. */
140
+ export const ruleToBot = (database, person, reason, at) => {
141
+ const log = { author: "rules", reason, at };
142
+ const bot = createBot(database, log);
143
+ intoBot(database, identitiesOf(database, person), bot, log);
144
+ return bot;
145
+ };
146
+ /** The reason of a bot that only sent a newsletter: a mail written to the owner alone gives it back to a person. */
147
+ export const NEWSLETTER_ONLY = "newsletter-only";
148
+ /** Mail from the identity `s` that no list sent, to the owner and at most a small group. */
149
+ const ONE_TO_ONE = "EXISTS (SELECT 1 FROM emails e WHERE e.from_identity_id = s.identity_id AND e.outgoing IS NOT 1 " +
150
+ `AND e.deleted_at IS NULL AND ${LIST_ID} IS NULL AND json_extract(e.headers, '$."list-unsubscribe"') IS NOT 1 ` +
151
+ "AND json_extract(e.headers, '$.\"list-unsubscribe-post\"') IS NOT 1 " +
152
+ "AND json_extract(e.headers, '$.\"feedback-id\"') IS NOT 1 " +
153
+ "AND json_extract(e.headers, '$.precedence') IS NOT 'bulk' AND json_extract(e.headers, '$.precedence') IS NOT 'junk' " +
154
+ "AND NOT EXISTS (SELECT 1 FROM email_mailboxes m " +
155
+ "JOIN mailboxes x ON x.id = m.mailbox_id WHERE m.email_id = e.id AND x.kind = 'bulk') " +
156
+ "AND (SELECT count(*) FROM email_recipients r WHERE r.email_id = e.id AND r.role IN ('to', 'cc')) " +
157
+ `BETWEEN 1 AND ${SMALL_GROUP_MEMBERS})`;
158
+ /**
159
+ * A rule's bot the owner wrote to, or a newsletter's that wrote to the owner alone, by mail or in a private chat both wrote in, goes back to the people its identities
160
+ * came from; a messenger's own bot flag holds anyway. The caller holds the write lock.
161
+ */
162
+ export const ruleBotsBack = (database, at) => {
163
+ const back = database
164
+ .prepare("SELECT b.id, b.reason FROM sender_bots b WHERE b.author = 'rules' AND NOT EXISTS (SELECT 1 FROM " +
165
+ "sender_bot_identities s JOIN identities i ON i.id = s.identity_id WHERE s.bot_id = b.id AND i.bot = 1) " +
166
+ "AND EXISTS (SELECT 1 FROM sender_bot_identities s WHERE s.bot_id = b.id AND (" +
167
+ "EXISTS (SELECT 1 FROM email_recipients r JOIN emails e ON e.id = r.email_id WHERE r.identity_id = s.identity_id " +
168
+ "AND e.outgoing = 1 AND e.deleted_at IS NULL AND e.draft IS NOT 1) OR " +
169
+ "EXISTS (SELECT 1 FROM messages m JOIN chats c ON c.id = m.chat_id WHERE m.sender_identity_id = s.identity_id " +
170
+ "AND m.outgoing IS NOT 1 AND c.kind = 'dialog' AND EXISTS (SELECT 1 FROM messages o WHERE o.chat_id = c.id " +
171
+ `AND o.outgoing = 1)) OR (b.reason = '${NEWSLETTER_ONLY}' AND ${ONE_TO_ONE})))`)
172
+ .all();
173
+ for (const row of back) {
174
+ const reason = row.reason === NEWSLETTER_ONLY ? "a 1-to-1 mail or the owner wrote to it" : "the owner wrote to it";
175
+ outOfBot(database, botIdentitiesOf(database, Number(row.id)), undefined, { author: "rules", reason, at });
49
176
  }
50
- const held = database.prepare("SELECT id FROM sender_bots WHERE person_id = ? AND author = 'rules'").get(person);
51
- if (held === undefined)
52
- return;
53
- database.prepare("DELETE FROM sender_bots WHERE id = ?").run(Number(held.id));
54
- logMoves(database, identities, { bot: Number(held.id) }, { person }, options);
55
177
  };
56
- const botRow = (database, ref) => {
178
+ const MAIL_CHECKED = "people.newsletter_bots_mail_checked";
179
+ /**
180
+ * Mail a newsletter's bot sent since the last check: no trigger makes a kind stale for it, so a 1-to-1 mail would wait
181
+ * for someone else's change to give the bot back. Answers the newest email id to check up to, or `undefined`.
182
+ */
183
+ export const newsletterBotsMail = (database) => {
184
+ const newest = Number(database.prepare("SELECT coalesce(max(id), 0) AS n FROM emails").get()?.n);
185
+ const checked = Number(database.prepare("SELECT value FROM store_settings WHERE key = ?").get(MAIL_CHECKED)?.value ?? 0);
186
+ return newest > checked ? newest : undefined;
187
+ };
188
+ /** Gives back the newsletter bots a 1-to-1 mail came from, and keeps how far the mail was checked. */
189
+ export const settleNewsletterBots = (database, newest, at) => {
190
+ const checked = Number(database.prepare("SELECT value FROM store_settings WHERE key = ?").get(MAIL_CHECKED)?.value ?? 0);
191
+ const sent = database
192
+ .prepare("SELECT 1 FROM sender_bots b CROSS JOIN sender_bot_identities s ON s.bot_id = b.id CROSS JOIN emails e " +
193
+ `ON e.from_identity_id = s.identity_id WHERE b.author = 'rules' AND b.reason = '${NEWSLETTER_ONLY}' ` +
194
+ "AND e.id > ? AND e.id <= ? LIMIT 1")
195
+ .get(checked, newest);
196
+ if (sent !== undefined)
197
+ ruleBotsBack(database, at);
198
+ database
199
+ .prepare("INSERT INTO store_settings (key, value, at) VALUES (?, ?, ?) " +
200
+ "ON CONFLICT (key) DO UPDATE SET value = excluded.value, at = excluded.at")
201
+ .run(MAIL_CHECKED, String(newest), at);
202
+ };
203
+ /** Whether a build before version 75 sorted a bot onto a person row since the last kept list. */
204
+ export const hasLegacyBots = (database) => database.prepare("SELECT 1 FROM sender_bots WHERE person_id > 0 LIMIT 1").get() !== undefined;
205
+ /**
206
+ * A bot a build before version 75 sorted after the upgrade holds its person row's identities there: they move to the
207
+ * bot, as the upgrade moved the others. The caller holds the write lock.
208
+ */
209
+ export const settleLegacyBots = (database, at) => {
210
+ const legacy = database.prepare("SELECT id, person_id, author, reason FROM sender_bots WHERE person_id > 0").all();
211
+ for (const row of legacy) {
212
+ const bot = Number(row.id);
213
+ const identities = identitiesOf(database, Number(row.person_id));
214
+ database
215
+ .prepare("UPDATE sender_bots SET person_id = (SELECT min(0, coalesce(min(person_id), 0)) - 1 FROM sender_bots) WHERE id = ?")
216
+ .run(bot);
217
+ const log = { author: row.author, reason: "sorted by a build before store version 75", at };
218
+ intoBot(database, identities, bot, log);
219
+ if (identities.length === 0)
220
+ database.prepare("DELETE FROM sender_bots WHERE id = ?").run(bot);
221
+ }
222
+ };
223
+ const botIdOf = (database, ref) => {
57
224
  const id = ref.startsWith(SENDER_BOT_PREFIX) ? ref.slice(SENDER_BOT_PREFIX.length) : "";
58
225
  const row = /^[1-9]\d*$/.test(id)
59
- ? database.prepare("SELECT id, person_id FROM sender_bots WHERE id = ?").get(Number(id))
226
+ ? database.prepare("SELECT id FROM sender_bots WHERE id = ?").get(Number(id))
60
227
  : undefined;
61
228
  if (row === undefined)
62
229
  throw new CliError("not_found", `no ${ref} in the store`, { reason: "sender-bot.not-found", reference: ref });
63
- return { id: Number(row.id), person: Number(row.person_id) };
230
+ return Number(row.id);
64
231
  };
65
- const botOfPerson = (database, person) => {
66
- const row = database.prepare("SELECT id FROM sender_bots WHERE person_id = ?").get(person);
67
- return row === undefined ? undefined : Number(row.id);
68
- };
69
- const personRow = (database, ref) => {
232
+ const personIdOf = (database, ref) => {
70
233
  const uid = ref.startsWith("person:") ? ref.slice("person:".length) : "";
71
234
  const found = /^[1-9]\d*$/.test(uid) ? database.prepare("SELECT id FROM persons WHERE id = ?").get(uid) : undefined;
72
235
  if (found === undefined)
73
236
  throw new CliError("not_found", `no ${ref} in the store`, { reference: ref });
74
237
  return currentPerson(database, Number(found.id));
75
238
  };
76
- /** What a move names: a whole person or bot, or one identity and the person it sits on. */
77
- const subjectOf = (context, subject) => {
78
- const { database } = context;
79
- if (typeof subject !== "string") {
80
- const found = required(context, subject);
81
- const alone = identitiesOf(database, found.personPk).length === 1;
82
- return alone ? { person: found.personPk } : { person: found.personPk, identity: found.pk, ref: subject };
239
+ const identityIdOf = (database, { provider, id }) => {
240
+ const row = database.prepare("SELECT id FROM identities WHERE provider = ? AND external_id = ?").get(provider, id);
241
+ if (row === undefined)
242
+ throw new CliError("not_found", `no ${provider} identity ${id} in the store`);
243
+ return Number(row.id);
244
+ };
245
+ /** What a move names: a person's identities, a bot's, or one identity. */
246
+ const subjectOf = (database, subject) => {
247
+ if (typeof subject !== "string")
248
+ return { identities: [identityIdOf(database, subject)] };
249
+ if (subject.startsWith(SENDER_BOT_PREFIX)) {
250
+ const bot = botIdOf(database, subject);
251
+ return { bot, identities: botIdentitiesOf(database, bot) };
83
252
  }
84
- if (subject.startsWith(SENDER_BOT_PREFIX))
85
- return { person: botRow(database, subject).person };
86
- return { person: personRow(database, subject) };
87
- };
88
- const senderBotOf = (database, id) => {
89
- const row = database.prepare("SELECT person_id, name, author, reason FROM sender_bots WHERE id = ?").get(id);
90
- return {
91
- bot: `${SENDER_BOT_PREFIX}${id}`,
92
- person: `person:${Number(row?.person_id)}`,
93
- name: row?.name == null ? null : String(row.name),
94
- author: row?.author,
95
- reason: row?.reason == null ? null : String(row.reason),
96
- };
253
+ const person = personIdOf(database, subject);
254
+ const identities = identitiesOf(database, person);
255
+ const took = identities.length === 0 ? botThatTook(database, person) : undefined;
256
+ return took === undefined ? { person, identities } : { bot: took, identities: botIdentitiesOf(database, took) };
97
257
  };
258
+ /** The bot that took every identity of a person, so their `person:` ref still names it. */
259
+ const botThatTook = (database, person) => {
260
+ const row = database
261
+ .prepare("SELECT s.bot_id FROM sender_bot_moves m JOIN sender_bot_identities s ON s.identity_id = m.identity_id " +
262
+ "WHERE m.from_person_id = ? AND m.to_bot_id IS NOT NULL ORDER BY m.id DESC LIMIT 1")
263
+ .get(person);
264
+ return row === undefined ? undefined : Number(row.bot_id);
265
+ };
266
+ const botsOf = (database, ids) => {
267
+ if (ids.length === 0)
268
+ return [];
269
+ const json = JSON.stringify(ids);
270
+ const rows = new Map(database
271
+ .prepare("SELECT id, name, organization_id, author, reason FROM sender_bots WHERE id IN (SELECT value FROM json_each(?))")
272
+ .all(json)
273
+ .map((row) => [Number(row.id), row]));
274
+ const identities = new Map();
275
+ for (const row of database
276
+ .prepare("SELECT s.bot_id, i.provider, i.external_id, i.name, i.username, i.phone FROM sender_bot_identities s " +
277
+ "JOIN identities i ON i.id = s.identity_id WHERE s.bot_id IN (SELECT value FROM json_each(?)) ORDER BY i.id")
278
+ .all(json)) {
279
+ const held = identities.get(Number(row.bot_id)) ?? [];
280
+ held.push({
281
+ provider: String(row.provider),
282
+ id: String(row.external_id),
283
+ name: row.name == null ? null : String(row.name),
284
+ username: row.username == null ? null : String(row.username),
285
+ phone: row.phone == null ? null : String(row.phone),
286
+ });
287
+ identities.set(Number(row.bot_id), held);
288
+ }
289
+ const counts = new Map();
290
+ for (const row of database
291
+ .prepare("SELECT s.bot_id AS bot, count(*) AS n, max(m.sent_at) AS at FROM sender_bot_identities s " +
292
+ "JOIN messages m ON m.sender_identity_id = s.identity_id WHERE s.bot_id IN (SELECT value FROM json_each(?)) " +
293
+ "AND m.deleted_at IS NULL AND m.outgoing IS NOT 1 GROUP BY 1 UNION ALL " +
294
+ "SELECT s.bot_id, count(*), max(coalesce(e.sent_at, e.received_at)) FROM sender_bot_identities s " +
295
+ "JOIN emails e ON e.from_identity_id = s.identity_id WHERE s.bot_id IN (SELECT value FROM json_each(?)) " +
296
+ "AND e.deleted_at IS NULL AND e.outgoing IS NOT 1 GROUP BY 1")
297
+ .all(json, json)) {
298
+ const was = counts.get(Number(row.bot)) ?? { n: 0, at: null };
299
+ const at = row.at == null ? was.at : Math.max(Number(row.at), was.at ?? 0);
300
+ counts.set(Number(row.bot), { n: was.n + Number(row.n), at });
301
+ }
302
+ const sent = sentMailOf(database, ids, "bot");
303
+ return ids.flatMap((id) => {
304
+ const row = rows.get(id);
305
+ if (row === undefined)
306
+ return [];
307
+ const held = identities.get(id) ?? [];
308
+ const first = held.find((one) => one.name !== null) ?? held[0];
309
+ const emails = held.flatMap((one) => (one.provider === "email" ? [one.id] : []));
310
+ const name = row.name == null ? null : String(row.name);
311
+ const counted = counts.get(id);
312
+ return [
313
+ {
314
+ bot: `${SENDER_BOT_PREFIX}${id}`,
315
+ name,
316
+ displayName: displayName(name, {
317
+ name: first?.name ?? null,
318
+ username: first?.username ?? null,
319
+ phone: first?.phone ?? null,
320
+ email: emails[0] ?? null,
321
+ }),
322
+ organization: row.organization_id == null ? null : `organization:${Number(row.organization_id)}`,
323
+ author: row.author,
324
+ reason: row.reason == null ? null : String(row.reason),
325
+ identities: held.map(({ phone: _, ...one }) => one),
326
+ messagesFrom: counted?.n ?? 0,
327
+ lastContact: counted?.at == null ? null : new Date(counted.at).toISOString(),
328
+ ...senderSignalsOf(sent.get(id) ?? [], { addresses: emails, ownerWrote: false, chatted: false }),
329
+ },
330
+ ];
331
+ });
332
+ };
333
+ const movesOf = (database, bot) => database
334
+ .prepare("SELECT m.*, i.provider, i.external_id FROM sender_bot_moves m JOIN identities i ON i.id = m.identity_id " +
335
+ "WHERE m.from_bot_id = ? OR m.to_bot_id = ? ORDER BY m.id")
336
+ .all(bot, bot)
337
+ .map((row) => ({
338
+ identity: { provider: String(row.provider), id: String(row.external_id) },
339
+ from: refOf({
340
+ ...(row.from_person_id == null ? {} : { person: Number(row.from_person_id) }),
341
+ ...(row.from_bot_id == null ? {} : { bot: Number(row.from_bot_id) }),
342
+ }),
343
+ to: refOf({
344
+ ...(row.to_person_id == null ? {} : { person: Number(row.to_person_id) }),
345
+ ...(row.to_bot_id == null ? {} : { bot: Number(row.to_bot_id) }),
346
+ }),
347
+ author: row.author,
348
+ reason: row.reason == null ? null : String(row.reason),
349
+ at: new Date(Number(row.created_at)).toISOString(),
350
+ }));
351
+ const detailsOf = (database, bot) => {
352
+ const [found] = botsOf(database, [bot]);
353
+ if (found === undefined)
354
+ throw new CliError("not_found", `no ${SENDER_BOT_PREFIX}${bot} in the store`, { reason: "sender-bot.not-found" });
355
+ return { ...found, moves: movesOf(database, bot) };
356
+ };
357
+ /** The sender bots, by name; a bot a build before version 75 sorted shows once a list has settled it. */
358
+ export const listBots = (database, options) => {
359
+ const { limit, offset = 0 } = options;
360
+ const where = [HOLDS];
361
+ const params = [];
362
+ if (options.query !== undefined) {
363
+ const text = options.query.trim();
364
+ if (text.length < MIN_QUERY)
365
+ throw new CliError("validation_error", `a bots search takes at least ${MIN_QUERY} characters, got "${options.query}"`, { reason: "query.short-text" });
366
+ const like = (form) => `%${form.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
367
+ where.push("(b.name LIKE ? ESCAPE '\\' OR EXISTS (SELECT 1 FROM sender_bot_identities s JOIN identities i ON " +
368
+ "i.id = s.identity_id WHERE s.bot_id = b.id AND (i.name_folded LIKE ? ESCAPE '\\' " +
369
+ "OR i.external_id LIKE ? ESCAPE '\\' OR i.username LIKE ? ESCAPE '\\')))");
370
+ params.push(like(text), like(fold(text)), like(text), like(text));
371
+ }
372
+ if (options.organization !== undefined) {
373
+ const id = options.organization.startsWith("organization:")
374
+ ? options.organization.slice("organization:".length)
375
+ : "";
376
+ if (!/^[1-9]\d*$/.test(id))
377
+ throw new CliError("validation_error", `an organization is organization:<id>, got "${options.organization}"`);
378
+ where.push("b.organization_id = ?");
379
+ params.push(Number(id));
380
+ }
381
+ return read(database, () => {
382
+ const filter = where.join(" AND ");
383
+ const total = Number(database.prepare(`SELECT count(*) AS n FROM sender_bots b WHERE ${filter}`).get(...params)?.n);
384
+ const ids = database
385
+ .prepare(`SELECT b.id FROM sender_bots b WHERE ${filter} ORDER BY ${SHOWN} COLLATE NOCASE, b.id LIMIT ? OFFSET ?`)
386
+ .all(...params, limit, offset)
387
+ .map((row) => Number(row.id));
388
+ return { items: botsOf(database, ids), hasMore: total > offset + limit, total };
389
+ });
390
+ };
391
+ /** One sender bot with its identities and every move to or from it. */
392
+ export const showBot = (database, ref) => read(database, () => detailsOf(database, botIdOf(database, ref)));
98
393
  /**
99
- * The owner's word that a person, or one of their identities, is a program, for its whole history: its messages stay
100
- * where they are, and no rule moves it back. `bot` joins it to a bot already stored; one identity of a person with
101
- * others gets a person row of its own first.
394
+ * The owner's word that a person, a bot or one identity is a program, for its whole history: its messages stay where
395
+ * they are, and no rule gives it back. `bot` joins it to a stored bot; else a bot that already holds it keeps it, or a
396
+ * new one takes it. A person every identity left is hidden, and a move back gives their uid back.
102
397
  */
103
398
  export const moveToBot = (context, subject, options = {}) => {
104
399
  const { database } = context;
105
400
  return write(database, () => {
106
401
  const at = context.now();
402
+ settleLegacyBots(database, at);
107
403
  const log = { author: "owner", reason: options.reason ?? null, at };
108
- const chosen = subjectOf(context, subject);
109
- if (isOwner(context, chosen.person))
404
+ const chosen = subjectOf(database, subject);
405
+ const people = new Set(chosen.identities.flatMap((one) => holderOf(database, one).person ?? []));
406
+ if ([...people].some((person) => isOwner(context, person)))
110
407
  throw new CliError("validation_error", "the owner's own person is never a bot", { reason: "sender-bot.owner" });
111
- const target = options.bot === undefined ? undefined : botRow(database, options.bot);
112
- const from = { person: chosen.person, bot: botOfPerson(database, chosen.person) };
113
- const claim = (bot) => database
408
+ if (chosen.identities.length === 0)
409
+ throw new CliError("validation_error", `${String(subject)} holds no identity to move`, {
410
+ reason: "sender-bot.empty",
411
+ });
412
+ const held = new Set(chosen.identities.flatMap((one) => holderOf(database, one).bot ?? []));
413
+ const target = options.bot !== undefined
414
+ ? botIdOf(database, options.bot)
415
+ : (chosen.bot ?? (held.size === 1 && people.size === 0 ? [...held][0] : undefined));
416
+ const bot = target ?? createBot(database, log, options.name ?? null);
417
+ database
114
418
  .prepare("UPDATE sender_bots SET author = 'owner', name = coalesce(?, name), updated_at = ? WHERE id = ?")
115
419
  .run(options.name ?? null, at, bot);
116
- if (target !== undefined && target.person !== chosen.person) {
117
- const moving = chosen.identity === undefined ? identitiesOf(database, chosen.person) : [chosen.identity];
118
- if (chosen.identity === undefined) {
119
- mergePerson(context, chosen.person, target.person, { method: "bot", by: "owner" });
120
- if (from.bot !== undefined)
121
- database.prepare("DELETE FROM sender_bots WHERE id = ?").run(from.bot);
122
- }
123
- else {
124
- move(context, chosen.identity, chosen.person, target.person, { method: "bot", by: "owner" });
125
- renameAfterLeaving(context, chosen.person, [chosen.identity]);
126
- }
127
- claim(target.id);
128
- logMoves(database, moving, from, { bot: target.id }, log);
129
- return senderBotOf(database, target.id);
130
- }
131
- if (chosen.identity !== undefined && chosen.ref !== undefined) {
132
- const alone = Number(unlinkIdentity(context, chosen.ref, { method: "unlink", by: "owner" }).uid);
133
- const bot = createBot(database, alone, { ...log, name: options.name ?? null });
134
- logMoves(database, [chosen.identity], from, { bot }, log);
135
- return senderBotOf(database, bot);
136
- }
137
- const held = from.bot ?? createBot(database, chosen.person, { ...log, name: options.name ?? null });
138
- if (from.bot !== undefined)
139
- claim(held);
140
- logMoves(database, identitiesOf(database, chosen.person), from, { bot: held }, log);
141
- return senderBotOf(database, held);
420
+ const left = intoBot(database, chosen.identities, bot, log);
421
+ for (const [person, gone] of left)
422
+ if (identitiesOf(database, person).length > 0)
423
+ renameAfterLeaving(context, person, gone);
424
+ groupByDomain(database, [{ id: bot, displayName: options.name ?? null, holds: true, bot: true }], at);
425
+ return detailsOf(database, bot);
142
426
  });
143
427
  };
144
428
  /**
145
429
  * The owner's word that a bot, a person or one identity is a person, for its whole history; no rule makes it a bot
146
- * again. `person` joins it to that person; one identity of a bot with others gets a person row of its own.
430
+ * again. `person` takes it; else each identity goes back to the person it came from, or a person of its own. Said of a
431
+ * person, it keeps them one. Answers the person the first identity is on.
147
432
  */
148
433
  export const moveToPerson = (context, subject, options = {}) => {
149
434
  const { database } = context;
150
435
  return write(database, () => {
151
436
  const at = context.now();
437
+ settleLegacyBots(database, at);
152
438
  const log = { author: "owner", reason: options.reason ?? null, at };
153
- const chosen = subjectOf(context, subject);
154
- const bot = botOfPerson(database, chosen.person);
155
- const from = { person: chosen.person, bot };
156
- const target = options.person === undefined ? undefined : personRow(database, options.person);
157
- if (target !== undefined && botOfPerson(database, target) !== undefined)
158
- throw new CliError("validation_error", `${options.person} is a bot; name a person`, {
159
- reason: "sender-bot.not-a-person",
160
- reference: options.person,
439
+ const chosen = subjectOf(database, subject);
440
+ const target = options.person === undefined ? undefined : personIdOf(database, options.person);
441
+ if (chosen.identities.length === 0)
442
+ throw new CliError("validation_error", `${String(subject)} holds no identity to move`, {
443
+ reason: "sender-bot.empty",
161
444
  });
162
- if (target !== undefined && target !== chosen.person) {
163
- const moving = chosen.identity === undefined ? identitiesOf(database, chosen.person) : [chosen.identity];
164
- if (chosen.identity === undefined)
165
- mergePerson(context, chosen.person, target, { method: "manual", by: "owner" });
166
- else {
167
- move(context, chosen.identity, chosen.person, target, { method: "manual", by: "owner" });
168
- renameAfterLeaving(context, chosen.person, [chosen.identity]);
169
- }
170
- if (bot !== undefined && identitiesOf(database, chosen.person).length === 0)
171
- database.prepare("DELETE FROM sender_bots WHERE id = ?").run(bot);
172
- releaseDomainHolds(database, moving);
173
- logMoves(database, moving, from, { person: target }, log);
445
+ if (chosen.person !== undefined && target !== undefined && target !== chosen.person) {
446
+ for (const identity of chosen.identities)
447
+ logMove(database, identity, { person: chosen.person }, { person: target }, log);
448
+ mergePerson(context, chosen.person, target, { method: "manual", by: "owner" });
174
449
  return recordOf(context, target);
175
450
  }
176
- if (chosen.identity !== undefined && chosen.ref !== undefined && bot !== undefined) {
177
- const alone = Number(unlinkIdentity(context, chosen.ref, { method: "unlink", by: "owner" }).uid);
178
- releaseDomainHolds(database, [chosen.identity]);
179
- logMoves(database, [chosen.identity], from, { person: alone }, log);
180
- return recordOf(context, alone);
451
+ const went = outOfBot(database, chosen.identities, target, log);
452
+ for (const identity of chosen.identities) {
453
+ if (went.has(identity))
454
+ continue;
455
+ const person = holderOf(database, identity).person;
456
+ if (person === undefined)
457
+ continue;
458
+ const to = target ?? person;
459
+ if (to !== person) {
460
+ move(context, identity, person, to, { method: "manual", by: "owner" });
461
+ renameAfterLeaving(context, person, [identity]);
462
+ }
463
+ logMove(database, identity, { person }, { person: to }, log);
464
+ went.set(identity, to);
181
465
  }
182
- if (bot !== undefined)
183
- database.prepare("DELETE FROM sender_bots WHERE id = ?").run(bot);
184
- const moving = chosen.identity === undefined ? identitiesOf(database, chosen.person) : [chosen.identity];
185
- releaseDomainHolds(database, moving);
186
- logMoves(database, moving, from, { person: chosen.person }, log);
187
- return recordOf(context, chosen.person);
466
+ releaseDomainHolds(database, chosen.identities);
467
+ const first = went.get(chosen.identities[0]);
468
+ return recordOf(context, first ?? target ?? chosen.person);
188
469
  });
189
470
  };