@wirecat/cli-core 0.639.0 → 0.640.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 (38) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/domain/crm.d.ts +3 -0
  3. package/dist/domain/name-variants.d.ts +2 -0
  4. package/dist/domain/name-variants.js +107 -0
  5. package/dist/domain/person-kinds.d.ts +6 -3
  6. package/dist/domain/person-kinds.js +5 -2
  7. package/dist/entities/contact-activity.d.ts +3 -0
  8. package/dist/entities/contact-activity.js +3 -0
  9. package/dist/entities/contact-context.d.ts +6 -0
  10. package/dist/entities/index.d.ts +6 -0
  11. package/dist/errors/reasons.js +2 -1
  12. package/dist/resolve.d.ts +8 -0
  13. package/dist/resolve.js +48 -6
  14. package/dist/search/lucene/registry.js +17 -15
  15. package/dist/services/message-resolution.d.ts +12 -0
  16. package/dist/services/message-resolution.js +42 -1
  17. package/dist/services/messages-search.js +29 -15
  18. package/dist/services/metadata.d.ts +1 -1
  19. package/dist/store/index.d.ts +1 -1
  20. package/dist/store/people.d.ts +10 -3
  21. package/dist/store/people.js +2 -1
  22. package/dist/store/sqlite/accounts.js +2 -0
  23. package/dist/store/sqlite/crm.js +5 -0
  24. package/dist/store/sqlite/hit-places.js +19 -6
  25. package/dist/store/sqlite/identities.js +21 -1
  26. package/dist/store/sqlite/lucene-fields.d.ts +2 -1
  27. package/dist/store/sqlite/lucene-fields.js +76 -16
  28. package/dist/store/sqlite/lucene.js +8 -8
  29. package/dist/store/sqlite/note-search.js +9 -0
  30. package/dist/store/sqlite/people-list.js +14 -8
  31. package/dist/store/sqlite/person-doubts.d.ts +13 -3
  32. package/dist/store/sqlite/person-doubts.js +92 -48
  33. package/dist/store/sqlite/person-links.js +15 -2
  34. package/dist/store/sqlite/test-people.d.ts +24 -0
  35. package/dist/store/sqlite/test-people.js +92 -0
  36. package/dist/store/types.d.ts +6 -0
  37. package/docs/search/recipes.json +3 -0
  38. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,39 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.640.0 — 11.11.2026
9
+
10
+ ### Added
11
+
12
+ - **Part of a name in `from:`, `to:`, `cc:`, `bcc:` and `chat:`.** An unquoted value with `*` or `?` is a pattern over names, aliases and @usernames (titles for chats; addresses too in mail): `from:Ярослав*` finds «Ярослав» and «Ярослав Орлов», `from:*Орлов*` anyone with it inside, `chat:*отчет*` every chat with it in the title. The search reads them all. Case, ё/е and letter forms do not matter. A pattern that fits nobody is `not_found` with the nearest names; more than 50 fits is `query.too-large`. An id and an exact name work as before.
13
+ - **An ambiguous name lists more choices.** When several people are named exactly as typed, the error's candidates also list the people whose name only contains it, so «Ярослав» offers «Ярослав Орлов» too.
14
+ - **Wildcards in `mailbox:`, `label:` and `tag:`, and a word's start in `subject:`, `content:` and `transcript:`** (`mailbox:Proj*`, `tag:work-*`, `subject:отчет*`, `content:накладн*`).
15
+ - **A bare word's start looks where a bare word does.** `invoi*` without a field now also finds the word in voice transcripts, file text and file names, as `invoice` does, and says where (`matched_in`).
16
+ - **Test data is hidden from people lists.** A person whose every identity has a seed id or an address at a reserved
17
+ domain (`example.com`, `.test`, `.invalid` and the like) is of the new kind `test`, which every kind and `all` leave
18
+ out; `people.list({ kind: "test" })` lists them. `people.markTestData` hides a person the owner calls test data, and
19
+ `people.keep` on a hidden person brings them back as a real contact. Both are kept in the store, so every computer
20
+ sees them. See [ARCHITECTURE.md, "Who is shown"](docs/dev/ARCHITECTURE.md).
21
+ - **Every phone and address of a CRM contact.** `CrmPerson.phones` and `emails`, and `PersonFacts.phones` and
22
+ `emails`, keep all of them on the identity; a linked identity gives them as `phones` and `emails`, its `phone` and
23
+ `email` among them.
24
+
25
+ ### Changed — may break callers
26
+
27
+ - **`PersonKind` has a sixth kind, `test`.** A caller that keeps a record of every kind adds it; `people.list` and
28
+ `people.counts` give it, and `kind: "all"` leaves it out.
29
+
30
+ - **A doubt about test data asks only when unsure.** A seed name alone is a `test-data` doubt with the move
31
+ `{ op: "test-data", person }` (`people links resolve <who> test`), and `keep` now answers it as a real contact
32
+ instead of refusing it with `person.test-data`, which is no longer raised. A test identity on a person who holds a real one is a doubt with an
33
+ unlink. Sure test data is no longer a doubt.
34
+ - **A short form of a name, or a name that repeats the mailbox, is no second name.** Ярик and Ярослав, Bob and Robert,
35
+ and a Drive or mail identity named after its own address no longer make a `shared-address` or `mixed-names` doubt.
36
+
37
+ ### Fixed
38
+
39
+ - **`*word*` in the text names the way out.** A pattern that starts with `*` reads every indexed word; over the expansion budget its error now suggests `word*`, which also finds the word's forms.
40
+
8
41
  ## 0.639.0 — 11.11.2026
9
42
 
10
43
  ### Changed — may break callers
@@ -79,6 +79,9 @@ export interface CrmPerson {
79
79
  name: string | null;
80
80
  email?: string | null;
81
81
  phone?: string | null;
82
+ /** Every phone and address the contact holds, `phone` and `email` first; left out, the stored ones stay. */
83
+ phones?: string[];
84
+ emails?: string[];
82
85
  /** The job title as the CRM writes it: kept beside the relationship, never a role. */
83
86
  position?: string | null;
84
87
  /**
@@ -19,3 +19,5 @@ export declare const variantKey: (name: string | null | undefined) => string | n
19
19
  * spelling and the older one with `y` (`Iuliia`, `Yuliia`), Latin read as Russian. Each spelling once.
20
20
  */
21
21
  export declare const spellings: (text: string) => string[];
22
+ /** A word's skeleton with the skeletons of the full names it may stand for: `iarik` gives `iarik` and `iaroslav`. */
23
+ export declare const fullNames: (skeleton: string) => string[];
@@ -145,3 +145,110 @@ export const spellings = (text) => {
145
145
  }
146
146
  return [...new Set([folded, LATIN.test(folded) ? toCyrillic(folded) : folded])];
147
147
  };
148
+ /** Each full first name and its everyday short forms, Russian and English. */
149
+ const SHORT_FORMS = {
150
+ Александр: "Саша Саня Шура Алекс",
151
+ Александра: "Саша Саня Шура",
152
+ Алексей: "Алеша Леша",
153
+ Анастасия: "Настя",
154
+ Анатолий: "Толя",
155
+ Андрей: "Андрюша",
156
+ Анна: "Аня",
157
+ Антон: "Антоша",
158
+ Артем: "Тема",
159
+ Борис: "Боря",
160
+ Валентин: "Валя",
161
+ Валентина: "Валя",
162
+ Валерий: "Валера",
163
+ Валерия: "Лера",
164
+ Василий: "Вася",
165
+ Виктор: "Витя",
166
+ Виктория: "Вика",
167
+ Виталий: "Виталик",
168
+ Владимир: "Вова Володя",
169
+ Владислав: "Влад Слава",
170
+ Вячеслав: "Слава",
171
+ Галина: "Галя",
172
+ Геннадий: "Гена",
173
+ Георгий: "Жора Гоша",
174
+ Григорий: "Гриша",
175
+ Дарья: "Даша",
176
+ Дмитрий: "Дима Митя",
177
+ Евгений: "Женя",
178
+ Евгения: "Женя",
179
+ Екатерина: "Катя",
180
+ Елена: "Лена",
181
+ Елизавета: "Лиза",
182
+ Иван: "Ваня",
183
+ Илья: "Илюша",
184
+ Ирина: "Ира",
185
+ Константин: "Костя",
186
+ Ксения: "Ксюша",
187
+ Леонид: "Леня",
188
+ Любовь: "Люба",
189
+ Людмила: "Люда",
190
+ Максим: "Макс",
191
+ Маргарита: "Рита",
192
+ Мария: "Маша",
193
+ Михаил: "Миша",
194
+ Надежда: "Надя",
195
+ Наталья: "Наташа",
196
+ Николай: "Коля",
197
+ Ольга: "Оля",
198
+ Павел: "Паша",
199
+ Петр: "Петя",
200
+ Полина: "Поля",
201
+ Роман: "Рома",
202
+ Светлана: "Света",
203
+ Семен: "Сема",
204
+ Сергей: "Сережа",
205
+ Софья: "Соня",
206
+ Станислав: "Стас",
207
+ Степан: "Степа",
208
+ Татьяна: "Таня",
209
+ Федор: "Федя",
210
+ Эдуард: "Эдик",
211
+ Юлия: "Юля",
212
+ Юрий: "Юра",
213
+ Яков: "Яша",
214
+ Ярослав: "Ярик Слава",
215
+ Alexander: "Alex Sasha",
216
+ Andrew: "Andy Drew",
217
+ Anthony: "Tony",
218
+ Benjamin: "Ben",
219
+ Catherine: "Cathy Kate Katie",
220
+ Charles: "Charlie Chuck",
221
+ Christopher: "Chris",
222
+ Daniel: "Dan Danny",
223
+ David: "Dave",
224
+ Edward: "Ed Eddie Ted",
225
+ Elizabeth: "Liz Lizzy Beth Betty",
226
+ James: "Jim Jimmy Jamie",
227
+ Jennifer: "Jen Jenny",
228
+ John: "Johnny Jack",
229
+ Joseph: "Joe Joey",
230
+ Katherine: "Kate Katie Kathy",
231
+ Margaret: "Maggie Meg Peggy",
232
+ Matthew: "Matt",
233
+ Michael: "Mike Mick",
234
+ Nicholas: "Nick",
235
+ Patrick: "Pat",
236
+ Peter: "Pete",
237
+ Rebecca: "Becky",
238
+ Richard: "Rick Rich Dick",
239
+ Robert: "Bob Bobby Rob Robbie",
240
+ Samuel: "Sam",
241
+ Stephen: "Steve",
242
+ Steven: "Steve",
243
+ Thomas: "Tom Tommy",
244
+ Timothy: "Tim",
245
+ William: "Bill Billy Will Liam",
246
+ };
247
+ const FULL_NAMES = new Map();
248
+ for (const [full, short] of Object.entries(SHORT_FORMS))
249
+ for (const form of [full, ...short.split(" ")]) {
250
+ const key = wordSkeleton(form);
251
+ FULL_NAMES.set(key, [...new Set([...(FULL_NAMES.get(key) ?? []), wordSkeleton(full)])]);
252
+ }
253
+ /** A word's skeleton with the skeletons of the full names it may stand for: `iarik` gives `iarik` and `iaroslav`. */
254
+ export const fullNames = (skeleton) => [skeleton, ...(FULL_NAMES.get(skeleton) ?? [])];
@@ -1,8 +1,11 @@
1
- /** What a person in the store is, for a list that shows the useful ones and keeps the noise apart. */
2
- export declare const PERSON_KINDS: readonly ["person", "organization", "automated", "stranger", "unsorted"];
1
+ /**
2
+ * What a person in the store is, for a list that shows the useful ones and keeps the noise apart. `test` is what a
3
+ * test run left, which `all` leaves out too.
4
+ */
5
+ export declare const PERSON_KINDS: readonly ["person", "organization", "automated", "stranger", "unsorted", "test"];
3
6
  export type PersonKind = (typeof PERSON_KINDS)[number];
4
7
  /** What decided a kind, besides the ties that make someone a `person`. */
5
- export type KindSignal = "bot" | "no-reply" | "bulk-mail" | "bulk-never-replied" | "automated-name" | "organization" | "role-address" | "company-name" | "no-tie" | "no-name";
8
+ export type KindSignal = "test-data" | "bot" | "no-reply" | "bulk-mail" | "bulk-never-replied" | "automated-name" | "organization" | "role-address" | "company-name" | "no-tie" | "no-name";
6
9
  /** A sender that is a program: «Notifications», «Рассылка», «no-reply». */
7
10
  export declare const isAutomatedName: (name: string | null) => boolean;
8
11
  /** A legal form or a word only a business calls itself: «ООО Ромашка», «CZECH AIRLINES», «OpenWeather Team». */
@@ -1,5 +1,8 @@
1
- /** What a person in the store is, for a list that shows the useful ones and keeps the noise apart. */
2
- export const PERSON_KINDS = ["person", "organization", "automated", "stranger", "unsorted"];
1
+ /**
2
+ * What a person in the store is, for a list that shows the useful ones and keeps the noise apart. `test` is what a
3
+ * test run left, which `all` leaves out too.
4
+ */
5
+ export const PERSON_KINDS = ["person", "organization", "automated", "stranger", "unsorted", "test"];
3
6
  const AUTOMATED_WORDS = new Set([
4
7
  "noreply",
5
8
  "notification",
@@ -11,6 +11,9 @@ export declare const linkedPerson: v.StrictObjectSchema<{
11
11
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
12
12
  readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
13
13
  readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
14
+ /** Every phone and address the source gave, `phone` and `email` among them. */
15
+ readonly phones: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
16
+ readonly emails: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
14
17
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
15
18
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
16
19
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -8,6 +8,9 @@ const linkedIdentity = v.strictObject({
8
8
  username: v.nullable(text),
9
9
  phone: v.optional(v.nullable(text)),
10
10
  email: v.optional(v.nullable(text)),
11
+ /** Every phone and address the source gave, `phone` and `email` among them. */
12
+ phones: v.optional(v.array(text)),
13
+ emails: v.optional(v.array(text)),
11
14
  is_bot: v.nullable(v.boolean()),
12
15
  accounts: v.array(id),
13
16
  seen_in: v.array(v.strictObject({ account: id, scope: v.picklist(["personal", "work"]) })),
@@ -33,6 +33,8 @@ declare const context: v.StrictObjectSchema<{
33
33
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
34
34
  readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
35
35
  readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
36
+ readonly phones: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
37
+ readonly emails: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
36
38
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
37
39
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
38
40
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -826,6 +828,8 @@ export declare const contactContext: v.UnionSchema<[v.StrictObjectSchema<{
826
828
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
827
829
  readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
828
830
  readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
831
+ readonly phones: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
832
+ readonly emails: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
829
833
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
830
834
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
831
835
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -1630,6 +1634,8 @@ export declare const contactPreparation: v.StrictObjectSchema<{
1630
1634
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
1631
1635
  readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
1632
1636
  readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
1637
+ readonly phones: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
1638
+ readonly emails: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
1633
1639
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
1634
1640
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
1635
1641
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -2718,6 +2718,8 @@ export declare const ENTITIES: {
2718
2718
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
2719
2719
  readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
2720
2720
  readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
2721
+ readonly phones: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
2722
+ readonly emails: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
2721
2723
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
2722
2724
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
2723
2725
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -3507,6 +3509,8 @@ export declare const ENTITIES: {
3507
3509
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
3508
3510
  readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
3509
3511
  readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
3512
+ readonly phones: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
3513
+ readonly emails: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
3510
3514
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
3511
3515
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
3512
3516
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -3810,6 +3814,8 @@ export declare const ENTITIES: {
3810
3814
  readonly username: v.NullableSchema<v.StringSchema<undefined>, undefined>;
3811
3815
  readonly phone: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
3812
3816
  readonly email: v.OptionalSchema<v.NullableSchema<v.StringSchema<undefined>, undefined>, undefined>;
3817
+ readonly phones: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
3818
+ readonly emails: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
3813
3819
  readonly is_bot: v.NullableSchema<v.BooleanSchema<undefined>, undefined>;
3814
3820
  readonly accounts: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>, undefined>;
3815
3821
  readonly seen_in: v.ArraySchema<v.StrictObjectSchema<{
@@ -378,7 +378,8 @@ const OTHERS = [
378
378
  ["person.no-owner", "not_found", "no person is marked as the owner in the store"],
379
379
  ["person.unknown", "not_found", "the store has no person by that reference; people list gives person:<uid>"],
380
380
  ["person.no-doubt", "not_found", "nothing about that person is in doubt; people links check lists who is"],
381
- validation("person.test-data", "the person is in doubt only as test data, which is not kept; remove the test data"),
381
+ validation("person.owner", "the owner's own person is not test data"),
382
+ validation("person.no-identity", "a person with no identity is not test data; there is nothing to hide"),
382
383
  validation("person.from-required", "say whom the identity leaves: --from person:<uid>, or person:me for the owner"),
383
384
  [
384
385
  "identity.separated",
package/dist/resolve.d.ts CHANGED
@@ -27,3 +27,11 @@ export declare const pickChat: (reference: string, chats: Chat[]) => Chat;
27
27
  * `lower()` folds ASCII only, and most of these names are Cyrillic.
28
28
  */
29
29
  export declare const pickPerson: (reference: string, people: PeopleLookup) => Contact;
30
+ /** Everyone a name pattern such as `Ярослав*` or `*Орлов*` fits by their alias, name or @username. */
31
+ export declare const peopleMatching: (pattern: string, people: Contact[], { byAddress }?: {
32
+ byAddress?: boolean | undefined;
33
+ }) => Contact[];
34
+ /** Every chat a name pattern fits by its title or @username. */
35
+ export declare const chatsMatching: (pattern: string, chats: Chat[]) => Chat[];
36
+ /** The items whose names are closest to what a pattern spells, for a refusal to offer: a typo finds nobody. */
37
+ export declare const nearest: <T>(pattern: string, items: T[], names: (item: T) => string[], most?: number) => T[];
package/dist/resolve.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { CliError, singleLine } from "@wirecat/cli-base";
2
2
  import { contactReferenceOf } from "./domain/ref-arguments.js";
3
+ import { compileAutomaton, wildcardPattern } from "./search/lucene/automaton.js";
4
+ import { trigrams } from "./search/trigrams.js";
3
5
  /** Shaped like a Telegram or MAX id. Another messenger's ids may be any string, so a miss here is not "not an id". */
4
6
  export const isId = (reference) => /^-?\d+$/.test(reference.trim());
5
7
  /**
@@ -47,15 +49,55 @@ export const pickPerson = (reference, people) => {
47
49
  throw new CliError("not_found", `no person ${trimmed} in what this account has seen`);
48
50
  const wanted = foldName(trimmed.replace(/^@/, ""));
49
51
  const everyone = people.all().toSorted((a, b) => (a.name ?? "").localeCompare(b.name ?? ""));
50
- const fields = (person) => [person.alias, person.name, person.username].filter(isPresent).map(foldName);
51
- const exact = everyone.filter((person) => fields(person).includes(wanted));
52
- const matches = exact.length > 0 ? exact : everyone.filter((person) => fields(person).some((one) => one.includes(wanted)));
53
- if (matches.length === 1 && matches[0])
54
- return matches[0];
55
- if (matches.length === 0)
52
+ const exact = everyone.filter((person) => namesOf(person).includes(wanted));
53
+ const containing = everyone.filter((person) => namesOf(person).some((one) => one.includes(wanted)));
54
+ if (exact.length === 1 && exact[0])
55
+ return exact[0];
56
+ if (containing.length === 1 && containing[0])
57
+ return containing[0];
58
+ if (containing.length === 0)
56
59
  throw new CliError("not_found", `nobody matches "${reference}"`);
60
+ // Several people are named exactly this: the ones it is only part of the name of are as likely meant.
61
+ const matches = exact.length > 0 ? [...exact, ...containing.filter((person) => !exact.includes(person))] : containing;
57
62
  throw ambiguous(reference, "people", matches.map(({ id, name, username }) => ({ id, name, username })), ({ name, username }) => singleLine([name, username && `@${username}`].filter(isPresent).join(" ")));
58
63
  };
64
+ const namesOf = (person, byAddress = false) => [person.alias, person.name, person.username, byAddress ? person.id : undefined].filter(isPresent).map(foldName);
65
+ const chatNamesOf = (chat) => [chat.title, chat.providerMetadata?.username]
66
+ .filter((one) => typeof one === "string" && one !== "")
67
+ .map(foldName);
68
+ /** A name pattern with Lucene's `*` and `?`, matched against a whole name folded as `foldName` folds it. */
69
+ const namePattern = (pattern) => {
70
+ const automaton = compileAutomaton(wildcardPattern(foldName(pattern.trim().replace(/^@/, ""))));
71
+ return (names) => names.some((one) => automaton.test(one));
72
+ };
73
+ /** Everyone a name pattern such as `Ярослав*` or `*Орлов*` fits by their alias, name or @username. */
74
+ export const peopleMatching = (pattern, people, { byAddress = false } = {}) => {
75
+ const fits = namePattern(pattern);
76
+ return people.filter((person) => fits(namesOf(person, byAddress)));
77
+ };
78
+ /** Every chat a name pattern fits by its title or @username. */
79
+ export const chatsMatching = (pattern, chats) => {
80
+ const fits = namePattern(pattern);
81
+ return chats.filter((chat) => fits(chatNamesOf(chat)));
82
+ };
83
+ /** The items whose names are closest to what a pattern spells, for a refusal to offer: a typo finds nobody. */
84
+ export const nearest = (pattern, items, names, most = 5) => {
85
+ const pieces = (text) => foldName(text).split(/\s+/u).flatMap(trigrams);
86
+ const wanted = new Set(pieces(pattern.replace(/\\(.)/gu, "$1").replace(/[*?@]/gu, " ").trim()));
87
+ if (wanted.size === 0)
88
+ return [];
89
+ return items
90
+ .map((item) => ({
91
+ item,
92
+ score: names(item)
93
+ .flatMap(pieces)
94
+ .filter((piece) => wanted.has(piece)).length,
95
+ }))
96
+ .filter(({ score }) => score > 1)
97
+ .toSorted((a, b) => b.score - a.score)
98
+ .slice(0, most)
99
+ .map(({ item }) => item);
100
+ };
59
101
  const ambiguous = (reference, what, candidates, label) => {
60
102
  const width = Math.max(...candidates.map(({ id }) => id.length));
61
103
  const lines = candidates.map((candidate) => ` ${candidate.id.padEnd(width)} ${label(candidate)}`).join("\n");
@@ -31,7 +31,7 @@ const validateSize = (node) => {
31
31
  parseBytes(bound, node.span);
32
32
  };
33
33
  const validateTag = (node) => {
34
- if (tagOf(node.value) === undefined)
34
+ if (node.operator === "wildcard" ? !/^[a-z0-9*?-]{1,32}$/iu.test(node.value) : tagOf(node.value) === undefined)
35
35
  searchError("query.invalid-tag", node.span, "a tag is 1-32 letters a-z, digits and hyphens");
36
36
  };
37
37
  const validateMentioned = (node) => {
@@ -43,6 +43,8 @@ const validateTopic = (node) => {
43
43
  searchError("query.invalid-topic", node.span, "use a thread id in one chat");
44
44
  };
45
45
  const terms = ["term", "phrase"];
46
+ const names = [...terms, "wildcard"];
47
+ const NAMES = "account-scoped: an id or contact: reference as is; with * or ? a pattern over alias, name, @username (up to 50); else a name";
46
48
  export const QUERY_FIELDS = [
47
49
  {
48
50
  name: "text",
@@ -76,12 +78,12 @@ export const QUERY_FIELDS = [
76
78
  },
77
79
  {
78
80
  name: "from",
79
- example: 'from:"Alice Synthetic"',
81
+ example: "from:Alice*",
80
82
  index: "identities / sender index",
81
83
  aliases: [],
82
84
  type: "kw",
83
- operators: terms,
84
- normalization: "account-scoped resolution",
85
+ operators: names,
86
+ normalization: NAMES,
85
87
  support: "A1",
86
88
  },
87
89
  ...["to", "cc", "bcc"].map((name) => ({
@@ -90,8 +92,8 @@ export const QUERY_FIELDS = [
90
92
  index: "email_recipients",
91
93
  aliases: [],
92
94
  type: "kw",
93
- operators: terms,
94
- normalization: "account-scoped resolution; mail only",
95
+ operators: names,
96
+ normalization: `${NAMES}; mail only`,
95
97
  support: "A1",
96
98
  })),
97
99
  {
@@ -100,7 +102,7 @@ export const QUERY_FIELDS = [
100
102
  index: "email_words, then the subject",
101
103
  aliases: [],
102
104
  type: "txt",
103
- operators: terms,
105
+ operators: [...terms, "wildcard"],
104
106
  normalization: "every word, folded as text is; mail only",
105
107
  support: "A1",
106
108
  validate: filled,
@@ -111,7 +113,7 @@ export const QUERY_FIELDS = [
111
113
  index: "email_mailboxes",
112
114
  aliases: [],
113
115
  type: "kw",
114
- operators: terms,
116
+ operators: [...terms, "wildcard"],
115
117
  normalization: "a folder or label by its id (ASCII case folded) or name (case folded in any script); mail only",
116
118
  support: "A1",
117
119
  },
@@ -121,7 +123,7 @@ export const QUERY_FIELDS = [
121
123
  index: "email_mailboxes",
122
124
  aliases: [],
123
125
  type: "kw",
124
- operators: terms,
126
+ operators: [...terms, "wildcard"],
125
127
  normalization: "the same as mailbox:; mail only",
126
128
  support: "A1",
127
129
  },
@@ -149,12 +151,12 @@ export const QUERY_FIELDS = [
149
151
  },
150
152
  {
151
153
  name: "chat",
152
- example: 'chat:"Work fixture"',
154
+ example: "chat:*fixture*",
153
155
  index: "chats / message time index",
154
156
  aliases: [],
155
157
  type: "kw",
156
- operators: terms,
157
- normalization: "account-scoped resolution",
158
+ operators: names,
159
+ normalization: "account-scoped: an id or chat: reference as is; with * or ? a pattern over title, @username (up to 50); else a title",
158
160
  support: "A1",
159
161
  },
160
162
  {
@@ -319,7 +321,7 @@ export const QUERY_FIELDS = [
319
321
  index: "attachment_words",
320
322
  aliases: [],
321
323
  type: "txt",
322
- operators: terms,
324
+ operators: [...terms, "wildcard"],
323
325
  normalization: "NFKD/marks/NFC/lowercase v1; the text of files attachments extract read or an agent wrote",
324
326
  support: "A2",
325
327
  validate: filled,
@@ -330,7 +332,7 @@ export const QUERY_FIELDS = [
330
332
  index: "attachment_words ∪ transcript_stems; garbled spellings from transcript_words_vocab",
331
333
  aliases: [],
332
334
  type: "txt",
333
- operators: terms,
335
+ operators: [...terms, "wildcard"],
334
336
  normalization: "any form of the word (Snowball), widened to spellings speech recognition garbles; what a voice message said",
335
337
  support: "A2",
336
338
  validate: filled,
@@ -424,7 +426,7 @@ export const QUERY_FIELDS = [
424
426
  index: "tags: the message, its chat or its sender",
425
427
  aliases: [],
426
428
  type: "kw",
427
- operators: terms,
429
+ operators: [...terms, "wildcard"],
428
430
  normalization: "lowercase a-z, 0-9 and -, 1-32 characters",
429
431
  support: "A2",
430
432
  validate: validateTag,
@@ -34,3 +34,15 @@ export declare const senderAmong: (store: MessageStore, accounts: AccountKey[],
34
34
  provider: string;
35
35
  id: string;
36
36
  }>;
37
+ /** The most people or chats one name pattern may stand for in a search. */
38
+ export declare const MOST_NAME_MATCHES = 50;
39
+ /** Every sender a name pattern (`from:Ярослав*`) fits, through the names each messenger's accounts have seen. */
40
+ export declare const sendersMatching: (store: MessageStore, accounts: AccountKey[], field: string, pattern: string) => Promise<{
41
+ provider: Provider;
42
+ id: Id;
43
+ }[]>;
44
+ /** Every stored chat a name pattern (`chat:*отчёт*`) fits, left ones included: a search reads kept history. */
45
+ export declare const chatsMatchingIn: (store: MessageStore, accounts: AccountKey[], pattern: string) => Promise<{
46
+ account: AccountKey;
47
+ chatId: Id;
48
+ }[]>;
@@ -1,9 +1,10 @@
1
1
  import { CliError, singleLine } from "@wirecat/cli-base";
2
2
  import { chatReferenceOf, ensureAccount } from "../domain/ref-arguments.js";
3
3
  import { profilesOn } from "../domain/ref-summaries.js";
4
- import { isId, pickChat, pickPerson } from "../resolve.js";
4
+ import { chatsMatching, isId, nearest, peopleMatching, pickChat, pickPerson } from "../resolve.js";
5
5
  import { codeOf } from "../sends/guarded.js";
6
6
  import { nothingStored } from "./deps.js";
7
+ import { MAIL } from "./search-kind.js";
7
8
  /**
8
9
  * The chat a store read is about. Offline, a chat with nothing kept answers empty, as it always has;
9
10
  * in store mode the store is the only source, so an empty answer would pass for "nothing was said".
@@ -179,3 +180,43 @@ export const senderAmong = async (store, accounts, reference) => {
179
180
  throw error;
180
181
  }
181
182
  };
183
+ /** The most people or chats one name pattern may stand for in a search. */
184
+ export const MOST_NAME_MATCHES = 50;
185
+ /** `candidates` are shaped as an ambiguous name's are: `{id, name, username}` for people, `{id, title}` for chats. */
186
+ const patternRefused = (field, pattern, what, found, near) => {
187
+ if (found === 0)
188
+ throw new CliError("not_found", `${field}:${pattern} — no ${what} fits${near.length ? `; near: ${near.map(({ label }) => label).join(", ")}` : ""}`, { candidates: near.map(({ candidate }) => candidate) });
189
+ throw new CliError("validation_error", `${field}:${pattern} fits ${found} ${what}, more than ${MOST_NAME_MATCHES} — write more of the name`, { reason: "query.too-large", budget: "name matches", limit: MOST_NAME_MATCHES, complete: false });
190
+ };
191
+ /** Every sender a name pattern (`from:Ярослав*`) fits, through the names each messenger's accounts have seen. */
192
+ export const sendersMatching = async (store, accounts, field, pattern) => {
193
+ const providers = [...new Set(accounts.map(({ provider }) => provider))];
194
+ const seen = await Promise.all(providers.map(async (provider) => {
195
+ const ids = accounts.filter((one) => one.provider === provider).map(({ account }) => account);
196
+ // One account's people carry its aliases; several accounts' do not.
197
+ const scope = ids.length === 1 ? { account: ids[0] } : { accounts: ids };
198
+ return { provider, people: (await store.people.people(provider, scope)).all() };
199
+ }));
200
+ const found = seen.flatMap(({ provider, people }) => peopleMatching(pattern, people, { byAddress: provider === MAIL }).map(({ id }) => ({ provider, id })));
201
+ if (found.length === 0 || found.length > MOST_NAME_MATCHES) {
202
+ const people = seen.flatMap(({ people }) => people);
203
+ const near = nearest(pattern, people, ({ name, alias }) => [name, alias].filter(isText));
204
+ patternRefused(field, pattern, "person", found.length, near.map(({ id, name, username }) => ({ id, label: name ?? id, candidate: { id, name, username } })));
205
+ }
206
+ return found;
207
+ };
208
+ /** Every stored chat a name pattern (`chat:*отчёт*`) fits, left ones included: a search reads kept history. */
209
+ export const chatsMatchingIn = async (store, accounts, pattern) => {
210
+ const held = await Promise.all(accounts.map(async (account) => ({
211
+ account,
212
+ chats: (await store.chats.chats(account, { includeLeft: true })).items,
213
+ })));
214
+ const found = held.flatMap(({ account, chats }) => chatsMatching(pattern, chats).map((chat) => ({ account, chatId: chat.id })));
215
+ if (found.length === 0 || found.length > MOST_NAME_MATCHES) {
216
+ const chats = held.flatMap(({ chats }) => chats);
217
+ const near = nearest(pattern, chats, ({ title }) => [title].filter(isText));
218
+ patternRefused("chat", pattern, "chat", found.length, near.map(({ id, title }) => ({ id, label: title ?? id, candidate: { id, title } })));
219
+ }
220
+ return found;
221
+ };
222
+ const isText = (value) => typeof value === "string" && value !== "";