@wirecat/cli-core 0.606.0 → 0.607.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 (209) hide show
  1. package/CHANGELOG.md +186 -1
  2. package/dist/calendar/index.d.ts +1 -0
  3. package/dist/calendar/index.js +1 -0
  4. package/dist/calendar/reads.js +5 -0
  5. package/dist/cli/app-mcp-command.d.ts +6 -2
  6. package/dist/cli/app-mcp-command.js +11 -2
  7. package/dist/cli/csv.d.ts +10 -0
  8. package/dist/cli/csv.js +22 -0
  9. package/dist/cli/early-refusal.d.ts +10 -0
  10. package/dist/cli/early-refusal.js +19 -0
  11. package/dist/cli/index.d.ts +3 -0
  12. package/dist/cli/index.js +3 -0
  13. package/dist/cli/profile-token.d.ts +29 -0
  14. package/dist/cli/profile-token.js +65 -0
  15. package/dist/cli/program.js +4 -2
  16. package/dist/crm/cli/csv.d.ts +23 -0
  17. package/dist/crm/cli/csv.js +135 -0
  18. package/dist/crm/cli/index.d.ts +1 -1
  19. package/dist/crm/cli/index.js +33 -21
  20. package/dist/crm/cli/pipeline-view.d.ts +3 -0
  21. package/dist/crm/cli/pipeline-view.js +36 -0
  22. package/dist/crm/writes.d.ts +6 -4
  23. package/dist/crm/writes.js +17 -13
  24. package/dist/documents.d.ts +2 -0
  25. package/dist/documents.js +2 -0
  26. package/dist/domain/business.d.ts +79 -0
  27. package/dist/domain/business.js +42 -0
  28. package/dist/domain/finance.d.ts +2 -0
  29. package/dist/domain/finance.js +2 -2
  30. package/dist/domain/google-documents.d.ts +2 -0
  31. package/dist/domain/google-documents.js +3 -1
  32. package/dist/domain/money.d.ts +2 -0
  33. package/dist/domain/money.js +11 -3
  34. package/dist/domain/providers.d.ts +36 -1
  35. package/dist/domain/providers.js +69 -7
  36. package/dist/domain/record-fields.d.ts +42 -0
  37. package/dist/domain/record-fields.js +122 -0
  38. package/dist/domain/record-types.d.ts +489 -16
  39. package/dist/domain/record-types.js +374 -7
  40. package/dist/domain/records.d.ts +96 -5
  41. package/dist/domain/records.js +178 -32
  42. package/dist/domain/ref-summaries.js +5 -0
  43. package/dist/domain/references.d.ts +1 -1
  44. package/dist/domain/references.js +5 -0
  45. package/dist/domain/vcard.d.ts +25 -0
  46. package/dist/domain/vcard.js +267 -0
  47. package/dist/entities/deal.d.ts +14 -0
  48. package/dist/entities/deal.js +3 -0
  49. package/dist/entities/index.d.ts +12 -0
  50. package/dist/errors/reasons.js +61 -2
  51. package/dist/fetch/addresses.d.ts +5 -0
  52. package/dist/fetch/addresses.js +76 -0
  53. package/dist/fetch/page.d.ts +64 -0
  54. package/dist/fetch/page.js +256 -0
  55. package/dist/index.d.ts +5 -3
  56. package/dist/index.js +5 -3
  57. package/dist/meetings/calendar-text.d.ts +1 -1
  58. package/dist/meetings/calendar-text.js +4 -0
  59. package/dist/meetings/event-store.d.ts +2 -2
  60. package/dist/search/account-list.d.ts +4 -0
  61. package/dist/search/account-list.js +19 -8
  62. package/dist/search/query.js +2 -2
  63. package/dist/services/events-search.js +2 -2
  64. package/dist/services/index.d.ts +1 -1
  65. package/dist/services/index.js +1 -1
  66. package/dist/services/ingest.d.ts +56 -8
  67. package/dist/services/ingest.js +95 -61
  68. package/dist/services/messages-search.js +3 -2
  69. package/dist/services/metadata.d.ts +1 -1
  70. package/dist/services/notes-search.js +1 -0
  71. package/dist/services/proposals/kinds/contracts.d.ts +4 -0
  72. package/dist/services/proposals/kinds/contracts.js +9 -0
  73. package/dist/services/proposals/kinds/finance.d.ts +4 -0
  74. package/dist/services/proposals/kinds/finance.js +14 -35
  75. package/dist/services/proposals/kinds/orders.js +7 -30
  76. package/dist/services/proposals/kinds/shared.d.ts +27 -1
  77. package/dist/services/proposals/kinds/shared.js +34 -0
  78. package/dist/services/proposals/kinds/source-review.d.ts +4 -0
  79. package/dist/services/proposals/kinds/source-review.js +45 -0
  80. package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
  81. package/dist/services/proposals/kinds/subscriptions.js +24 -0
  82. package/dist/services/proposals/kinds/transactions.d.ts +4 -0
  83. package/dist/services/proposals/kinds/transactions.js +10 -0
  84. package/dist/services/proposals/registry.js +9 -0
  85. package/dist/services/search-all-meetings.js +2 -2
  86. package/dist/services/search-all.js +4 -3
  87. package/dist/services/search-kind.js +3 -3
  88. package/dist/store/decisions.js +5 -1
  89. package/dist/store/index.d.ts +14 -3
  90. package/dist/store/index.js +3 -0
  91. package/dist/store/people.js +1 -1
  92. package/dist/store/source-review.d.ts +64 -0
  93. package/dist/store/source-review.js +7 -0
  94. package/dist/store/sqlite/accounts.d.ts +1 -1
  95. package/dist/store/sqlite/accounts.js +24 -1
  96. package/dist/store/sqlite/added-sources.d.ts +82 -0
  97. package/dist/store/sqlite/added-sources.js +237 -0
  98. package/dist/store/sqlite/business-contracts.d.ts +90 -0
  99. package/dist/store/sqlite/business-contracts.js +182 -0
  100. package/dist/store/sqlite/calendar-events.js +7 -3
  101. package/dist/store/sqlite/calendar-forget.js +3 -0
  102. package/dist/store/sqlite/calendar.d.ts +21 -1
  103. package/dist/store/sqlite/calendar.js +27 -7
  104. package/dist/store/sqlite/chat-rekey.js +7 -0
  105. package/dist/store/sqlite/chats.d.ts +3 -1
  106. package/dist/store/sqlite/chats.js +15 -1
  107. package/dist/store/sqlite/crm-rows.d.ts +44 -0
  108. package/dist/store/sqlite/crm-rows.js +195 -0
  109. package/dist/store/sqlite/crm.d.ts +2 -11
  110. package/dist/store/sqlite/crm.js +11 -166
  111. package/dist/store/sqlite/deals.d.ts +4 -8
  112. package/dist/store/sqlite/deals.js +5 -3
  113. package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
  114. package/dist/store/sqlite/emails.js +2 -0
  115. package/dist/store/sqlite/entity-types.d.ts +14 -9
  116. package/dist/store/sqlite/entity-types.js +4 -10
  117. package/dist/store/sqlite/evidence-signature.d.ts +114 -0
  118. package/dist/store/sqlite/evidence-signature.js +349 -0
  119. package/dist/store/sqlite/evidence-sources.d.ts +2 -1
  120. package/dist/store/sqlite/evidence-sources.js +7 -3
  121. package/dist/store/sqlite/facts.d.ts +7 -2
  122. package/dist/store/sqlite/facts.js +21 -5
  123. package/dist/store/sqlite/finance.d.ts +18 -105
  124. package/dist/store/sqlite/finance.js +100 -219
  125. package/dist/store/sqlite/knowledge.d.ts +8 -2
  126. package/dist/store/sqlite/knowledge.js +65 -71
  127. package/dist/store/sqlite/labelled.d.ts +3 -0
  128. package/dist/store/sqlite/labelled.js +11 -0
  129. package/dist/store/sqlite/link-kinds.d.ts +2 -0
  130. package/dist/store/sqlite/link-kinds.js +2 -0
  131. package/dist/store/sqlite/manifest.js +2 -0
  132. package/dist/store/sqlite/memories.d.ts +23 -9
  133. package/dist/store/sqlite/memories.js +41 -13
  134. package/dist/store/sqlite/messages.js +2 -0
  135. package/dist/store/sqlite/migrations.generated.js +103 -0
  136. package/dist/store/sqlite/money-lines.d.ts +48 -0
  137. package/dist/store/sqlite/money-lines.js +76 -0
  138. package/dist/store/sqlite/money-transactions.d.ts +132 -0
  139. package/dist/store/sqlite/money-transactions.js +295 -0
  140. package/dist/store/sqlite/notes.d.ts +11 -2
  141. package/dist/store/sqlite/notes.js +20 -25
  142. package/dist/store/sqlite/orders.d.ts +36 -6
  143. package/dist/store/sqlite/orders.js +126 -46
  144. package/dist/store/sqlite/payment-facts.js +1 -1
  145. package/dist/store/sqlite/private-people.js +2 -0
  146. package/dist/store/sqlite/products.d.ts +78 -0
  147. package/dist/store/sqlite/products.js +131 -0
  148. package/dist/store/sqlite/project-transfer/records.js +26 -1
  149. package/dist/store/sqlite/project-transfer/snapshot.js +5 -3
  150. package/dist/store/sqlite/proposed-actions.d.ts +1 -1
  151. package/dist/store/sqlite/proposed-actions.js +24 -7
  152. package/dist/store/sqlite/providers.d.ts +0 -4
  153. package/dist/store/sqlite/providers.js +20 -2
  154. package/dist/store/sqlite/record-matching.d.ts +80 -0
  155. package/dist/store/sqlite/record-matching.js +264 -0
  156. package/dist/store/sqlite/record-projection.d.ts +89 -0
  157. package/dist/store/sqlite/record-projection.js +50 -0
  158. package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
  159. package/dist/store/sqlite/record-projectors-direct.js +125 -0
  160. package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
  161. package/dist/store/sqlite/record-projectors-money.js +214 -0
  162. package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
  163. package/dist/store/sqlite/record-projectors-phone.js +212 -0
  164. package/dist/store/sqlite/record-projectors.d.ts +3 -44
  165. package/dist/store/sqlite/record-projectors.js +7 -67
  166. package/dist/store/sqlite/record-relations.d.ts +24 -0
  167. package/dist/store/sqlite/record-relations.js +92 -0
  168. package/dist/store/sqlite/record-remap.d.ts +12 -0
  169. package/dist/store/sqlite/record-remap.js +92 -0
  170. package/dist/store/sqlite/record-run.d.ts +71 -0
  171. package/dist/store/sqlite/record-run.js +179 -0
  172. package/dist/store/sqlite/record-settling.d.ts +9 -0
  173. package/dist/store/sqlite/record-settling.js +74 -0
  174. package/dist/store/sqlite/record-stamps.d.ts +13 -0
  175. package/dist/store/sqlite/record-stamps.js +30 -0
  176. package/dist/store/sqlite/record-writes.d.ts +43 -0
  177. package/dist/store/sqlite/record-writes.js +307 -0
  178. package/dist/store/sqlite/records.d.ts +52 -42
  179. package/dist/store/sqlite/records.js +123 -353
  180. package/dist/store/sqlite/ref-summaries.d.ts +6 -5
  181. package/dist/store/sqlite/ref-summaries.js +60 -8
  182. package/dist/store/sqlite/refunds.d.ts +31 -0
  183. package/dist/store/sqlite/refunds.js +112 -0
  184. package/dist/store/sqlite/reviewed.d.ts +109 -0
  185. package/dist/store/sqlite/reviewed.js +173 -0
  186. package/dist/store/sqlite/schema.d.ts +2840 -83
  187. package/dist/store/sqlite/schema.js +256 -1
  188. package/dist/store/sqlite/source-review-marks.d.ts +54 -0
  189. package/dist/store/sqlite/source-review-marks.js +143 -0
  190. package/dist/store/sqlite/source-review.d.ts +54 -0
  191. package/dist/store/sqlite/source-review.js +221 -0
  192. package/dist/store/sqlite/stage-amounts.d.ts +14 -0
  193. package/dist/store/sqlite/stage-amounts.js +23 -0
  194. package/dist/store/sqlite/subscriptions.d.ts +135 -0
  195. package/dist/store/sqlite/subscriptions.js +294 -0
  196. package/dist/store/sqlite/text-input.d.ts +3 -0
  197. package/dist/store/sqlite/text-input.js +13 -0
  198. package/dist/store/sqlite/things.js +2 -9
  199. package/dist/store/sqlite/transaction.d.ts +15 -0
  200. package/dist/store/sqlite/transaction.js +57 -0
  201. package/dist/store/sqlite/wallets.d.ts +88 -0
  202. package/dist/store/sqlite/wallets.js +143 -0
  203. package/dist/store/store-errors.d.ts +1 -0
  204. package/dist/store/store-errors.js +45 -0
  205. package/dist/store/store.d.ts +16 -1
  206. package/dist/store/store.js +30 -6
  207. package/package.json +5 -2
  208. package/schemas/examples/records-business.jsonl +11 -0
  209. package/schemas/records-envelope.v1.schema.json +1160 -5
@@ -1,26 +1,33 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { holdsCredential, secretNamed } from "../runs/secrets.js";
3
- import { AMOUNT_ROLES, TYPE_PATTERN, TYPE_RULE, WORD_BODY } from "./record-types.js";
3
+ import { PHONE_COUNTRIES } from "./phones.js";
4
+ import { DECIMAL_PATTERN, fieldError, isObject } from "./record-fields.js";
5
+ import { AMOUNT_ROLES, article, isRecordType, nestedOf, RECORD_ENTITY_TYPES, RECORD_TYPES, referencesOf, roleOf, rolesOf, TYPE_PATTERN, TYPE_RULE, WORD_BODY, } from "./record-types.js";
4
6
  export { RECORD_ENTITY_TYPES } from "./record-types.js";
5
7
  export const RECORDS_SCHEMA_VERSION = 1;
6
8
  export const RECORD_OPERATIONS = ["upsert", "delete"];
9
+ /** How an envelope's lines read `product`: `text` keeps an invoice line's product as data, as v1 did. */
10
+ export const LINE_OPTIONS = ["text", "products"];
7
11
  const WORD = `^${WORD_BODY}$`;
8
12
  const MAX_ID = 512;
9
13
  const MAX_FIELDS_BYTES = 65_536;
10
14
  const MAX_RELATIONS = 100;
11
- const DECIMAL = "^[0-9]{1,16}(\\.[0-9]{1,6})?$";
15
+ const DECIMAL = DECIMAL_PATTERN;
16
+ const REF = "^[a-z]+:[^\\s]{1,500}$";
17
+ const fieldsDef = (type) => `fields-${type}`;
12
18
  /** The v1 envelope as JSON Schema (Draft 2020-12); `schemas/records-envelope.v1.schema.json` is this, written out. */
13
19
  export const RECORDS_ENVELOPE_SCHEMA = {
14
20
  $schema: "https://json-schema.org/draft/2020-12/schema",
15
21
  title: "WireCat records envelope, version 1",
16
- description: "Records one source sends to the store. JSONL is the same model: the first line holds schema_version and " +
17
- "source, each further line one record.",
22
+ description: "Records one source sends to the store. JSONL is the same model: the first line holds schema_version, source " +
23
+ "and options, each further line one record.",
18
24
  type: "object",
19
25
  required: ["schema_version", "source", "records"],
20
26
  additionalProperties: false,
21
27
  properties: {
22
28
  schema_version: { const: RECORDS_SCHEMA_VERSION },
23
29
  source: { $ref: "#/$defs/source" },
30
+ options: { $ref: "#/$defs/options" },
24
31
  records: { type: "array", items: { $ref: "#/$defs/record" } },
25
32
  },
26
33
  $defs: {
@@ -34,6 +41,23 @@ export const RECORDS_ENVELOPE_SCHEMA = {
34
41
  batch_id: { type: "string", minLength: 1, maxLength: MAX_ID, description: "This import, for the receipt" },
35
42
  },
36
43
  },
44
+ options: {
45
+ type: "object",
46
+ additionalProperties: false,
47
+ properties: {
48
+ lines: {
49
+ enum: [...LINE_OPTIONS],
50
+ description: "products: an invoice line's product (an external id) names its product; text, the default, keeps it " +
51
+ "as data. Order lines always read it, and product_ref (a product: ref) is read on every line.",
52
+ },
53
+ phone_region: {
54
+ type: "string",
55
+ pattern: "^[A-Za-z]{2}$",
56
+ description: "The country a person's phone without + is read in. Without it such a number is an identifier only when " +
57
+ "exactly one country of the store's phone_countries setting reads it as valid",
58
+ },
59
+ },
60
+ },
37
61
  record: {
38
62
  type: "object",
39
63
  required: ["key", "type", "external_id", "operation"],
@@ -50,15 +74,27 @@ export const RECORDS_ENVELOPE_SCHEMA = {
50
74
  revision: { type: "integer", minimum: 0, maximum: Number.MAX_SAFE_INTEGER },
51
75
  relations: { type: "array", maxItems: MAX_RELATIONS, items: { $ref: "#/$defs/relation" } },
52
76
  },
77
+ allOf: RECORD_ENTITY_TYPES.map((type) => ({
78
+ if: { properties: { type: { const: type } }, required: ["type"] },
79
+ // biome-ignore lint/suspicious/noThenProperty: JSON Schema's own if/then keyword, never awaited.
80
+ then: { properties: { fields: { $ref: `#/$defs/${fieldsDef(type)}` } } },
81
+ })),
53
82
  },
54
83
  relation: {
55
84
  type: "object",
56
- required: ["role", "type", "external_id"],
85
+ required: ["role"],
57
86
  additionalProperties: false,
87
+ oneOf: [{ required: ["type", "external_id"] }, { required: ["ref"] }],
58
88
  properties: {
59
89
  role: { type: "string", pattern: WORD },
60
90
  type: { type: "string", pattern: TYPE_PATTERN },
61
91
  external_id: { type: "string", minLength: 1, maxLength: MAX_ID },
92
+ ref: { type: "string", pattern: REF, description: "A store entity, such as organization:12" },
93
+ as: {
94
+ type: "string",
95
+ pattern: WORD,
96
+ description: "On a relationship role: the part the target plays, such as decision-maker",
97
+ },
62
98
  amount: {
63
99
  type: "string",
64
100
  pattern: DECIMAL,
@@ -66,12 +102,13 @@ export const RECORDS_ENVELOPE_SCHEMA = {
66
102
  },
67
103
  },
68
104
  },
105
+ ...Object.fromEntries(RECORD_ENTITY_TYPES.map((type) => [fieldsDef(type), RECORD_TYPES[type].fields])),
69
106
  },
70
107
  };
71
108
  const wordPattern = new RegExp(WORD);
72
109
  const typePattern = new RegExp(TYPE_PATTERN);
73
110
  const decimalPattern = new RegExp(DECIMAL);
74
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
111
+ const refPattern = new RegExp(REF);
75
112
  const escapePointer = (segment) => String(segment).replaceAll("~", "~0").replaceAll("/", "~1");
76
113
  export const pointerOf = (...segments) => segments.map((s) => `/${escapePointer(s)}`).join("");
77
114
  const idText = (value) => typeof value === "string" && value.trim() !== "" && value.length <= MAX_ID && !value.includes("\0");
@@ -99,6 +136,8 @@ const secretIn = (value, at) => {
99
136
  }
100
137
  return undefined;
101
138
  };
139
+ /** The type a relation points at: its own `type`, or the prefix of its `ref`. */
140
+ export const targetTypeOf = (relation) => relation.ref === undefined ? String(relation.type) : relation.ref.slice(0, relation.ref.indexOf(":"));
102
141
  const relationErrors = (relations, at) => {
103
142
  if (relations === undefined)
104
143
  return [];
@@ -108,15 +147,25 @@ const relationErrors = (relations, at) => {
108
147
  const here = [...at, index];
109
148
  if (!isObject(relation))
110
149
  return [invalid(here, "a relation is an object")];
111
- const extra = extraKeys(relation, ["role", "type", "external_id", "amount"]);
150
+ const extra = extraKeys(relation, ["role", "type", "external_id", "ref", "as", "amount"]);
112
151
  if (extra.length > 0)
113
- return [invalid([...here, extra[0]], "a relation holds role, type, external_id and amount")];
152
+ return [invalid([...here, extra[0]], "a relation holds role, type, external_id, ref, as and amount")];
114
153
  if (typeof relation.role !== "string" || !wordPattern.test(relation.role))
115
154
  return [invalid([...here, "role"], "a role is lowercase letters, digits, - and _")];
116
- if (typeof relation.type !== "string" || !typePattern.test(relation.type))
117
- return [invalid([...here, "type"], TYPE_RULE)];
118
- if (!idText(relation.external_id))
119
- return [invalid([...here, "external_id"], `an external id takes 1–${MAX_ID} characters`)];
155
+ if (relation.ref !== undefined) {
156
+ if (relation.type !== undefined || relation.external_id !== undefined)
157
+ return [invalid([...here, "ref"], "a relation names its target by ref, or by type and external_id")];
158
+ if (typeof relation.ref !== "string" || !refPattern.test(relation.ref))
159
+ return [invalid([...here, "ref"], "a ref is a store reference, such as organization:12")];
160
+ }
161
+ else {
162
+ if (typeof relation.type !== "string" || !typePattern.test(relation.type))
163
+ return [invalid([...here, "type"], TYPE_RULE)];
164
+ if (!idText(relation.external_id))
165
+ return [invalid([...here, "external_id"], `an external id takes 1–${MAX_ID} characters`)];
166
+ }
167
+ if (relation.as !== undefined && (typeof relation.as !== "string" || !wordPattern.test(relation.as)))
168
+ return [invalid([...here, "as"], "as is lowercase letters, digits, - and _")];
120
169
  if (relation.amount !== undefined && (typeof relation.amount !== "string" || !decimalPattern.test(relation.amount)))
121
170
  return [invalid([...here, "amount"], 'an amount is a decimal string, such as "13000.00"')];
122
171
  if (relation.amount !== undefined && !AMOUNT_ROLES.includes(relation.role))
@@ -124,6 +173,37 @@ const relationErrors = (relations, at) => {
124
173
  return [];
125
174
  });
126
175
  };
176
+ /** What the type's registry entry says about its fields and roles: run once the record's shape is right. */
177
+ const typeErrors = (record, at) => {
178
+ if (record.operation !== "upsert" || !isRecordType(record.type))
179
+ return [];
180
+ const { type } = record;
181
+ const wrong = fieldError(RECORD_TYPES[type].fields, record.fields);
182
+ if (wrong)
183
+ return [invalid([...at, "fields", ...wrong.at], wrong.message)];
184
+ const relations = record.relations ?? [];
185
+ for (const [index, relation] of relations.entries()) {
186
+ const here = [...at, "relations", index];
187
+ const role = roleOf(type, relation.role);
188
+ if (relation.as !== undefined && !role?.relationship)
189
+ return [
190
+ invalid([...here, "as"], `${article(type)} ${type}'s ${relation.role} is not a relationship: it takes no as`),
191
+ ];
192
+ if (role === undefined || role.v1)
193
+ continue;
194
+ const target = targetTypeOf(relation);
195
+ if (!role.targets.includes(target))
196
+ return [
197
+ invalid(here, `${article(type)} ${type}'s ${relation.role} is ${role.targets.map((one) => `${article(one)} ${one}`).join(" or ")}`),
198
+ ];
199
+ if (!role.many && relations.some((other, before) => before < index && other.role === relation.role))
200
+ return [invalid(here, `${article(type)} ${type} has one ${relation.role}`, "record.relation-ambiguous")];
201
+ }
202
+ for (const [name, role] of rolesOf(type))
203
+ if (role.required && !relations.some((relation) => relation.role === name))
204
+ return [invalid([...at, "relations"], `${article(type)} ${type} names its ${name} in relations`)];
205
+ return [];
206
+ };
127
207
  const invalid = (at, message, code = "record.invalid") => ({
128
208
  pointer: pointerOf(...at),
129
209
  code,
@@ -161,13 +241,23 @@ export const recordErrors = (record, index) => {
161
241
  return withKey([
162
242
  invalid(secret, "a secret never goes into the store: drop this field at the source", "record.secret-field"),
163
243
  ]);
164
- return withKey(relationErrors(record.relations, [...at, "relations"]));
244
+ const relations = relationErrors(record.relations, [...at, "relations"]);
245
+ return withKey(relations.length > 0 ? relations : typeErrors(record, at));
165
246
  };
166
247
  /** The envelope's own errors (not its records'): when there is one, no record is taken. */
167
248
  export const envelopeErrors = (envelope, account) => {
249
+ const header = headerErrors(envelope, account, ["records"]);
250
+ if (header.length > 0)
251
+ return header;
252
+ if (!Array.isArray(envelope.records))
253
+ return [invalid(["records"], "records is a list", "envelope.invalid")];
254
+ return [];
255
+ };
256
+ /** A JSONL stream's first line, or an envelope without its records: `schema_version`, `source` and `options`. */
257
+ export const headerErrors = (envelope, account, more = []) => {
168
258
  if (!isObject(envelope))
169
259
  return [invalid([], "an envelope is an object", "envelope.invalid")];
170
- const extra = extraKeys(envelope, ["schema_version", "source", "records"]);
260
+ const extra = extraKeys(envelope, ["schema_version", "source", "options", ...more]);
171
261
  if (extra.length > 0)
172
262
  return [invalid([extra[0]], `an envelope has no ${extra[0]}`, "envelope.invalid")];
173
263
  if (envelope.schema_version !== RECORDS_SCHEMA_VERSION)
@@ -192,8 +282,22 @@ export const envelopeErrors = (envelope, account) => {
192
282
  return [
193
283
  invalid(["source", "account"], `the envelope is for account ${JSON.stringify(source.account)}, the import for ${JSON.stringify(account)}`, "envelope.account-mismatch"),
194
284
  ];
195
- if (!Array.isArray(envelope.records))
196
- return [invalid(["records"], "records is a list", "envelope.invalid")];
285
+ const { options } = envelope;
286
+ if (options !== undefined) {
287
+ if (!isObject(options))
288
+ return [invalid(["options"], "options is an object", "envelope.invalid")];
289
+ const unknown = extraKeys(options, ["lines", "phone_region"]);
290
+ if (unknown.length > 0)
291
+ return [invalid(["options", unknown[0]], "options holds lines and phone_region", "envelope.invalid")];
292
+ if (options.phone_region !== undefined &&
293
+ (typeof options.phone_region !== "string" ||
294
+ !PHONE_COUNTRIES.includes(options.phone_region.toLowerCase())))
295
+ return [
296
+ invalid(["options", "phone_region"], `options.phone_region is one of ${PHONE_COUNTRIES.join(", ")}`, "envelope.invalid"),
297
+ ];
298
+ if (options.lines !== undefined && !LINE_OPTIONS.includes(options.lines))
299
+ return [invalid(["options", "lines"], `options.lines is ${LINE_OPTIONS.join(" or ")}`, "envelope.invalid")];
300
+ }
197
301
  return [];
198
302
  };
199
303
  const canonical = (value) => {
@@ -210,39 +314,81 @@ export const recordFingerprint = (fields, relations) => createHash("sha256")
210
314
  .update(JSON.stringify(canonical({
211
315
  fields,
212
316
  relations: relations
213
- // A relation without an amount keeps the fingerprint it had before amounts existed.
317
+ // What a relation did not carry adds nothing, so every fingerprint stored before amounts, refs and
318
+ // `as` existed stays the same. `ref=` and `as=` cannot be taken for an amount, which is a bare decimal.
214
319
  .map((relation) => [
215
320
  relation.role,
216
- relation.type,
217
- relation.external_id,
321
+ ...(relation.ref === undefined ? [relation.type, relation.external_id] : [`ref=${relation.ref}`]),
218
322
  ...(relation.amount === undefined ? [] : [relation.amount]),
323
+ ...(relation.as === undefined ? [] : [`as=${relation.as}`]),
219
324
  ])
220
325
  .sort((a, b) => a.join("\0").localeCompare(b.join("\0"))),
221
326
  })))
222
327
  .digest("hex");
328
+ const BOM = "\uFEFF";
329
+ /** A file's text without the byte-order mark a spreadsheet export puts before it. */
330
+ export const withoutBom = (text) => (text.startsWith(BOM) ? text.slice(1) : text);
331
+ /** One JSONL line as JSON; a line that is not JSON comes back as the text, for the record check to refuse at its index. */
332
+ export const jsonLine = (line) => {
333
+ try {
334
+ return JSON.parse(withoutBom(line));
335
+ }
336
+ catch {
337
+ return line;
338
+ }
339
+ };
223
340
  /**
224
- * A JSONL import as the envelope it stands for: the first line holds `schema_version` and `source`, each further
225
- * non-empty line one record. A line that is not JSON comes back as a record the envelope check refuses, at its index.
341
+ * A JSONL import as the envelope it stands for: the first line holds `schema_version`, `source` and `options`, each
342
+ * further non-empty line one record.
226
343
  */
227
344
  export const envelopeOfJsonl = (text) => {
228
- const lines = text.split(/\r?\n/);
345
+ const lines = withoutBom(text).split(/\r?\n/);
229
346
  const first = lines.findIndex((line) => line.trim() !== "");
230
347
  if (first < 0)
231
348
  return {};
232
- const parse = (line) => {
233
- try {
234
- return JSON.parse(line);
235
- }
236
- catch {
237
- return line;
238
- }
239
- };
240
- const header = parse(lines[first]);
349
+ const header = jsonLine(lines[first]);
241
350
  const records = [];
242
351
  for (let at = first + 1; at < lines.length; at++) {
243
352
  const line = lines[at];
244
353
  if (line.trim() !== "")
245
- records.push(parse(line));
354
+ records.push(jsonLine(line));
246
355
  }
247
356
  return isObject(header) ? { ...header, records } : header;
248
357
  };
358
+ /**
359
+ * A file's text as the envelope it stands for: one JSON envelope, or JSONL, told apart by the first non-empty line;
360
+ * a JSON object holding `records` is a whole envelope.
361
+ */
362
+ export const envelopeOfText = (text) => {
363
+ const clean = withoutBom(text);
364
+ const first = clean.split(/\r?\n/).find((line) => line.trim() !== "");
365
+ const head = first === undefined ? undefined : jsonLine(first);
366
+ if (isObject(head) && !Object.hasOwn(head, "records"))
367
+ return envelopeOfJsonl(clean);
368
+ return jsonLine(clean);
369
+ };
370
+ /**
371
+ * What a record's fields name by external id: a deal's pipeline, a line's product. An invoice's line products only
372
+ * with `options.lines: products`, since v1 kept them as data.
373
+ */
374
+ export const fieldReferences = (record, options = {}) => {
375
+ if (record.operation !== "upsert" || !isRecordType(record.type))
376
+ return [];
377
+ const fields = record.fields ?? {};
378
+ const found = [];
379
+ for (const [key, type] of referencesOf(record.type))
380
+ if (typeof fields[key] === "string")
381
+ found.push({ role: `fields.${key}`, type, external_id: fields[key] });
382
+ if (record.type === "invoice" && options.lines !== "products")
383
+ return found;
384
+ for (const [list, spec] of nestedOf(record.type)) {
385
+ const items = fields[list];
386
+ if (!Array.isArray(items))
387
+ continue;
388
+ for (const item of items)
389
+ for (const [key, type] of Object.entries(spec.references ?? {}))
390
+ if (isObject(item) && typeof item[key] === "string")
391
+ found.push({ role: `fields.${list}.${key}`, type, external_id: item[key] });
392
+ }
393
+ return found;
394
+ };
@@ -55,6 +55,11 @@ const WORDS = {
55
55
  deal: "Deal",
56
56
  lead: "Lead",
57
57
  pipeline: "Pipeline",
58
+ product: "Product",
59
+ contract: "Contract",
60
+ subscription: "Subscription",
61
+ wallet: "Wallet",
62
+ transaction: "Transaction",
58
63
  email: "Email",
59
64
  email_thread: "Email thread",
60
65
  unknown: "Unknown",
@@ -33,7 +33,7 @@ export type Reference = {
33
33
  * Things named by their store id (a task also by its key or the task package's id). `entity` is the name
34
34
  * before organizations and projects: it still parses, so an old file's reference resolves as not found.
35
35
  */
36
- export declare const SIMPLE_REFERENCES: readonly ["note", "document", "person", "organization", "project", "task", "memory", "fact", "bot", "event", "invoice", "payment", "order", "deal", "lead", "pipeline", "entity"];
36
+ export declare const SIMPLE_REFERENCES: readonly ["note", "document", "person", "organization", "project", "task", "memory", "fact", "bot", "event", "invoice", "payment", "order", "deal", "lead", "pipeline", "product", "contract", "subscription", "wallet", "transaction", "entity"];
37
37
  export type SimpleReference = (typeof SIMPLE_REFERENCES)[number];
38
38
  export type RefKindName = Exclude<Reference["type"], "entity">;
39
39
  export interface RefKindSpec<R extends Reference = Reference> {
@@ -22,6 +22,11 @@ export const SIMPLE_REFERENCES = [
22
22
  "deal",
23
23
  "lead",
24
24
  "pipeline",
25
+ "product",
26
+ "contract",
27
+ "subscription",
28
+ "wallet",
29
+ "transaction",
25
30
  "entity",
26
31
  ];
27
32
  const malformed = (text, shape) => new CliError("validation_error", `"${singleLine(text)}" is not a reference — expected ${shape}`, {
@@ -0,0 +1,25 @@
1
+ import type { PhoneCountry } from "./phones.js";
2
+ import type { RecordsEnvelope } from "./records.js";
3
+ export interface VcardOptions {
4
+ provider: string;
5
+ account: string;
6
+ batchId: string;
7
+ /** The country a number without `+` is read in. Left out, such a number is kept as text and reported. */
8
+ region?: PhoneCountry;
9
+ }
10
+ export interface VcardIssue {
11
+ /** The card's place in the file, from 0. */
12
+ card: number;
13
+ message: string;
14
+ }
15
+ /** Whether a file is a vCard address book rather than a JSON or JSONL envelope. */
16
+ export declare const isVcard: (text: string) => boolean;
17
+ /**
18
+ * A vCard file (2.1, 3.0 or 4.0) as a records envelope: one person per card, matched later by its numbers and
19
+ * addresses, and one organization per `ORG` name the person is a member of. Nothing is guessed: a national number
20
+ * is read only in `region`, and a card says nothing about a person it does not hold.
21
+ */
22
+ export declare const envelopeOfVcard: (text: string, { provider, account, batchId, region }: VcardOptions) => {
23
+ envelope: RecordsEnvelope;
24
+ issues: VcardIssue[];
25
+ };
@@ -0,0 +1,267 @@
1
+ import { createHash } from "node:crypto";
2
+ import { typedPhone } from "./mentions.js";
3
+ import { WORD_BODY } from "./record-types.js";
4
+ const MAX_ID = 512;
5
+ const AS_WORD = new RegExp(`^${WORD_BODY}$`);
6
+ /** Whether a file is a vCard address book rather than a JSON or JSONL envelope. */
7
+ export const isVcard = (text) => /^?\s*BEGIN:VCARD\b/i.test(text);
8
+ const isQuotedPrintable = (line) => {
9
+ const colon = line.indexOf(":");
10
+ return /;(ENCODING=)?QUOTED-PRINTABLE\b/i.test(colon < 0 ? line : line.slice(0, colon));
11
+ };
12
+ const PROPERTY_START = /^([A-Za-z0-9-]+\.)?[A-Za-z][A-Za-z0-9-]*(;[^:]*)?:/;
13
+ const isSoft = (line) => line !== undefined && isQuotedPrintable(line) && line.endsWith("=");
14
+ /**
15
+ * Joins folded lines (RFC 6350 3.2) and quoted-printable soft breaks, which vCard 2.1 writes without indent. A soft
16
+ * break never takes a card's BEGIN or END or the next property, and one with nothing after it is dropped.
17
+ */
18
+ const unfolded = (text) => {
19
+ const lines = [];
20
+ for (const raw of text.replace(/^\uFEFF/, "").split(/\r\n|\r|\n/)) {
21
+ const last = lines.length - 1;
22
+ const previous = lines[last];
23
+ const bounds = /^(BEGIN|END):/i.test(raw);
24
+ // A soft break's next line is encoded text; one that reads as `NAME[;params]:` starts the next property.
25
+ if (isSoft(previous) && !bounds && !PROPERTY_START.test(raw))
26
+ lines[last] = previous.slice(0, -1) + raw.replace(/^[ \t]/, "");
27
+ else if (previous !== undefined && /^[ \t]/.test(raw) && !bounds)
28
+ lines[last] = previous + raw.slice(1);
29
+ else {
30
+ if (isSoft(previous))
31
+ lines[last] = previous.slice(0, -1);
32
+ lines.push(raw);
33
+ }
34
+ }
35
+ const last = lines.length - 1;
36
+ if (isSoft(lines[last]))
37
+ lines[last] = lines[last].slice(0, -1);
38
+ return lines.filter((line) => line.trim() !== "");
39
+ };
40
+ /** Splits at the first `:` outside a quoted parameter value. */
41
+ const propertyOf = (line) => {
42
+ let quoted = false;
43
+ let colon = -1;
44
+ for (let index = 0; index < line.length; index += 1) {
45
+ if (line[index] === '"')
46
+ quoted = !quoted;
47
+ else if (line[index] === ":" && !quoted) {
48
+ colon = index;
49
+ break;
50
+ }
51
+ }
52
+ if (colon < 0)
53
+ return undefined;
54
+ const [head = "", ...rest] = line.slice(0, colon).split(";");
55
+ const params = new Map();
56
+ for (const part of rest) {
57
+ const equals = part.indexOf("=");
58
+ // vCard 2.1 writes a bare type or encoding: `TEL;CELL;VOICE`, `;QUOTED-PRINTABLE`.
59
+ const key = equals < 0 ? (/^(QUOTED-PRINTABLE|BASE64|8BIT|7BIT|B)$/i.test(part) ? "ENCODING" : "TYPE") : part.slice(0, equals);
60
+ const values = (equals < 0 ? part : part.slice(equals + 1)).replaceAll('"', "").split(",");
61
+ params.set(key.toUpperCase(), [...(params.get(key.toUpperCase()) ?? []), ...values.map((one) => one.toUpperCase())]);
62
+ }
63
+ const name = head.replace(/^[^.]*\./, "").toUpperCase();
64
+ return { name, params, value: line.slice(colon + 1) };
65
+ };
66
+ const encoder = new TextEncoder();
67
+ const decoded = (property, report) => {
68
+ const encoding = property.params.get("ENCODING")?.[0];
69
+ if (encoding !== "QUOTED-PRINTABLE")
70
+ return property.value;
71
+ const bytes = [];
72
+ const { value } = property;
73
+ for (let index = 0; index < value.length; index += 1) {
74
+ const hex = value.slice(index + 1, index + 3);
75
+ if (value[index] === "=" && /^[0-9A-F]{2}$/i.test(hex)) {
76
+ bytes.push(Number.parseInt(hex, 16));
77
+ index += 2;
78
+ }
79
+ else
80
+ for (const byte of encoder.encode(value[index]))
81
+ bytes.push(byte);
82
+ }
83
+ const charset = property.params.get("CHARSET")?.[0]?.toLowerCase() ?? "utf-8";
84
+ try {
85
+ return new TextDecoder(charset).decode(new Uint8Array(bytes));
86
+ }
87
+ catch {
88
+ report(`${property.name} names the unknown charset ${charset}: read as UTF-8`);
89
+ return new TextDecoder("utf-8").decode(new Uint8Array(bytes));
90
+ }
91
+ };
92
+ /** The value's components (`N`, `ORG`), each with vCard 3.0/4.0's backslash escapes undone. */
93
+ const components = (value) => {
94
+ const parts = [""];
95
+ for (let index = 0; index < value.length; index += 1) {
96
+ const char = value[index];
97
+ if (char === "\\" && index + 1 < value.length) {
98
+ const next = value[index + 1];
99
+ parts[parts.length - 1] += next === "n" || next === "N" ? "\n" : next;
100
+ index += 1;
101
+ }
102
+ else if (char === ";")
103
+ parts.push("");
104
+ else
105
+ parts[parts.length - 1] += char;
106
+ }
107
+ return parts.map((part) => part.trim());
108
+ };
109
+ const textOf = (property, report) => components(decoded(property, report)).join(";").trim();
110
+ /** E.164, or `undefined` when the number has no country of its own and none is given. */
111
+ const e164 = (typed, region) => {
112
+ const text = typed.replace(/^tel:/i, "").replace(/;.*$/, "").trim();
113
+ const international = /^(\+|00)/.test(text);
114
+ if (!international && region === undefined)
115
+ return undefined;
116
+ const value = typedPhone(text, region === undefined ? {} : { phoneCountries: [region] })?.value;
117
+ return value?.startsWith("+") ? value : undefined;
118
+ };
119
+ const foldedName = (name) => name.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
120
+ const hashed = (prefix, parts) => `${prefix}${createHash("sha256").update(parts.join("\n")).digest("hex").slice(0, 32)}`;
121
+ const organizationId = (name) => {
122
+ const id = `org:${foldedName(name)}`;
123
+ return id.length <= MAX_ID ? id : hashed("org:", [foldedName(name)]);
124
+ };
125
+ const titleWord = (title) => {
126
+ const word = title.toLowerCase().trim().replace(/\s+/g, "-");
127
+ return AS_WORD.test(word) ? word : undefined;
128
+ };
129
+ const nameOf = (properties, report) => {
130
+ const full = properties.find(({ name }) => name === "FN");
131
+ const text = full ? textOf(full, report) : "";
132
+ if (text)
133
+ return text;
134
+ const structured = properties.find(({ name }) => name === "N");
135
+ if (!structured)
136
+ return undefined;
137
+ const [family = "", given = "", additional = ""] = components(decoded(structured, report));
138
+ return [given, additional, family].filter(Boolean).join(" ") || undefined;
139
+ };
140
+ const SKIPPED = new Set(["PHOTO", "LOGO", "SOUND", "KEY"]);
141
+ /** The cards, each kept even when its END is missing; what was cut off is reported, never dropped quietly. */
142
+ const cardsOf = (text) => {
143
+ const cards = [];
144
+ const issues = [];
145
+ let card;
146
+ const isBound = (property, name) => property.name === name && property.value.trim().toUpperCase() === "VCARD";
147
+ for (const line of unfolded(text)) {
148
+ const property = propertyOf(line);
149
+ if (!property)
150
+ continue;
151
+ if (isBound(property, "BEGIN")) {
152
+ if (card) {
153
+ issues.push({ card: cards.length, message: "BEGIN:VCARD inside a card: the card ends there, unfinished" });
154
+ cards.push(card);
155
+ }
156
+ card = [];
157
+ }
158
+ else if (isBound(property, "END")) {
159
+ if (card)
160
+ cards.push(card);
161
+ card = undefined;
162
+ }
163
+ else if (card && !SKIPPED.has(property.name))
164
+ card.push(property);
165
+ }
166
+ if (card) {
167
+ issues.push({ card: cards.length, message: "the file ends inside a card, with no END:VCARD" });
168
+ cards.push(card);
169
+ }
170
+ return { cards, issues };
171
+ };
172
+ /**
173
+ * A vCard file (2.1, 3.0 or 4.0) as a records envelope: one person per card, matched later by its numbers and
174
+ * addresses, and one organization per `ORG` name the person is a member of. Nothing is guessed: a national number
175
+ * is read only in `region`, and a card says nothing about a person it does not hold.
176
+ */
177
+ export const envelopeOfVcard = (text, { provider, account, batchId, region }) => {
178
+ const { cards, issues } = cardsOf(text);
179
+ const people = [];
180
+ const organizations = new Map();
181
+ const seen = new Set();
182
+ for (const [index, properties] of cards.entries()) {
183
+ const report = (message) => {
184
+ if (!issues.some((one) => one.card === index && one.message === message))
185
+ issues.push({ card: index, message });
186
+ };
187
+ const values = (wanted) => properties
188
+ .filter(({ name }) => name === wanted)
189
+ .map((one) => textOf(one, report))
190
+ .filter(Boolean);
191
+ const name = nameOf(properties, report);
192
+ const phones = [];
193
+ const unread = [];
194
+ for (const typed of values("TEL")) {
195
+ const value = e164(typed, region);
196
+ if (value !== undefined) {
197
+ if (!phones.includes(value))
198
+ phones.push(value);
199
+ }
200
+ else {
201
+ unread.push(typed);
202
+ issues.push({
203
+ card: index,
204
+ message: `${typed} has no country code${region === undefined ? " and no region was given" : ` in ${region}`}: kept, not matched`,
205
+ });
206
+ }
207
+ }
208
+ const emails = [...new Set(values("EMAIL").map((one) => one.replace(/^mailto:/i, "").toLowerCase()))];
209
+ if (name === undefined && phones.length === 0 && unread.length === 0 && emails.length === 0) {
210
+ report("the card holds no name, number or address: left out");
211
+ continue;
212
+ }
213
+ const uid = values("UID")[0];
214
+ // A cut UID would make two long ones the same record; hashed, as an organization's long name is.
215
+ const externalId = uid === undefined
216
+ ? hashed("vcard:", [name ?? "", ...[...phones].sort(), ...emails.sort()])
217
+ : uid.length <= MAX_ID
218
+ ? uid
219
+ : hashed("vcard:", [uid]);
220
+ if (seen.has(externalId)) {
221
+ issues.push({ card: index, message: `another card of the file is ${externalId}: left out` });
222
+ continue;
223
+ }
224
+ seen.add(externalId);
225
+ const organization = properties.find(({ name }) => name === "ORG");
226
+ const organizationName = organization ? components(decoded(organization, report))[0] : undefined;
227
+ const title = values("TITLE")[0];
228
+ const relations = [];
229
+ if (organizationName) {
230
+ const id = organizationId(organizationName);
231
+ if (!organizations.has(id))
232
+ organizations.set(id, {
233
+ key: id,
234
+ type: "organization",
235
+ external_id: id,
236
+ operation: "upsert",
237
+ fields: { name: organizationName },
238
+ });
239
+ const as = title === undefined ? undefined : titleWord(title);
240
+ relations.push({ role: "member-of", type: "organization", external_id: id, ...(as ? { as } : {}) });
241
+ }
242
+ people.push({
243
+ key: `person:${externalId}`,
244
+ type: "person",
245
+ external_id: externalId,
246
+ operation: "upsert",
247
+ fields: {
248
+ ...(name === undefined ? {} : { name }),
249
+ ...(phones.length ? { phone: phones } : {}),
250
+ ...(emails.length ? { email: emails } : {}),
251
+ ...(unread.length ? { phone_unread: unread } : {}),
252
+ ...(organizationName ? { organization: organizationName } : {}),
253
+ ...(title === undefined ? {} : { title }),
254
+ },
255
+ ...(relations.length ? { relations } : {}),
256
+ });
257
+ }
258
+ return {
259
+ envelope: {
260
+ schema_version: 1,
261
+ source: { provider, account, batch_id: batchId },
262
+ ...(region === undefined ? {} : { options: { phone_region: region } }),
263
+ records: [...organizations.values(), ...people],
264
+ },
265
+ issues,
266
+ };
267
+ };