clivly 0.17.0 → 0.17.1

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 (130) hide show
  1. package/README.md +21 -27
  2. package/{adapter-BpAfha3z.d.mts → adapter-C63F9VZL.d.mts} +1 -1
  3. package/{adapter-BvSigBPG.d.cts → adapter-OO5g17qF.d.cts} +1 -1
  4. package/{auth-adapter-CsZE4ugg.d.cts → auth-adapter-COMP0Fud.d.cts} +1 -1
  5. package/{auth-adapter-Q6CL2VHr.d.mts → auth-adapter-ZlhllVpm.d.mts} +1 -1
  6. package/auth-better-auth.d.cts +1 -1
  7. package/auth-better-auth.d.mts +1 -1
  8. package/auth-clerk.d.cts +1 -1
  9. package/auth-clerk.d.mts +1 -1
  10. package/auth-workos.d.cts +1 -1
  11. package/auth-workos.d.mts +1 -1
  12. package/core-adapter.d.cts +1 -1
  13. package/core-adapter.d.mts +1 -1
  14. package/core-auth-adapter.d.cts +1 -1
  15. package/core-auth-adapter.d.mts +1 -1
  16. package/core-drizzle.d.cts +1 -1
  17. package/core-drizzle.d.mts +1 -1
  18. package/core-entity-config.cjs +1 -1
  19. package/core-entity-config.d.cts +1 -1
  20. package/core-entity-config.d.mts +1 -1
  21. package/core-entity-config.mjs +1 -1
  22. package/core-entity-heuristics.cjs +16 -15
  23. package/core-entity-heuristics.d.cts +3 -3
  24. package/core-entity-heuristics.d.mts +3 -3
  25. package/core-entity-heuristics.mjs +1 -1
  26. package/core-mapping-form.d.cts +1 -1
  27. package/core-mapping-form.d.mts +1 -1
  28. package/core-mappings-config.cjs +1 -1
  29. package/core-mappings-config.d.cts +1 -1
  30. package/core-mappings-config.d.mts +1 -1
  31. package/core-mappings-config.mjs +1 -1
  32. package/core-sync-engine.cjs +1 -1
  33. package/core-sync-engine.d.cts +1 -1
  34. package/core-sync-engine.d.mts +1 -1
  35. package/core-sync-engine.mjs +1 -1
  36. package/core-types.d.cts +1 -1
  37. package/core-types.d.mts +1 -1
  38. package/core-view-compiler.cjs +1 -1
  39. package/core-view-compiler.d.cts +1 -1
  40. package/core-view-compiler.d.mts +1 -1
  41. package/core-view-compiler.mjs +1 -1
  42. package/core.cjs +7 -7
  43. package/core.d.cts +9 -9
  44. package/core.d.mts +9 -9
  45. package/core.mjs +7 -7
  46. package/{drizzle-MUNZgh1l.d.cts → drizzle-B9cjBavj.d.cts} +1 -1
  47. package/{drizzle-UJbPCzPJ.d.mts → drizzle-L5FOGe_-.d.mts} +1 -1
  48. package/drizzle.cjs +2 -2
  49. package/drizzle.d.cts +3 -3
  50. package/drizzle.d.mts +3 -3
  51. package/drizzle.mjs +2 -2
  52. package/{entity-config-nWWgJXLw.cjs → entity-config-DiCJ6mhI.cjs} +1 -1
  53. package/{entity-config-BF7pcXFB.d.cts → entity-config-X-KlnYXX.d.mts} +1 -1
  54. package/{entity-config-pzamFSKw.d.mts → entity-config-dNclLyBM.d.cts} +1 -1
  55. package/{entity-config-DQVSprlG.mjs → entity-config-g_oMPXlN.mjs} +1 -1
  56. package/entity-heuristics-CIParuQe.cjs +655 -0
  57. package/entity-heuristics-DE5ujoHw.mjs +566 -0
  58. package/index.cjs +16 -15
  59. package/index.mjs +4 -3
  60. package/{internal-DtLZyjf8.mjs → internal-9oDwwbNg.mjs} +1 -1
  61. package/{internal-CjJy-cy1.cjs → internal-BKYt5j0l.cjs} +1 -1
  62. package/{internal-Gie7hCpK.d.mts → internal-COALpgov.d.cts} +1 -1
  63. package/{internal-C-uvosSL.d.cts → internal-D3q4FPcA.d.mts} +1 -1
  64. package/internal-adapter.d.cts +1 -1
  65. package/internal-adapter.d.mts +1 -1
  66. package/internal-auth-adapter.d.cts +1 -1
  67. package/internal-auth-adapter.d.mts +1 -1
  68. package/internal-drizzle.d.cts +1 -1
  69. package/internal-drizzle.d.mts +1 -1
  70. package/internal-entity-config.cjs +1 -1
  71. package/internal-entity-config.d.cts +1 -1
  72. package/internal-entity-config.d.mts +1 -1
  73. package/internal-entity-config.mjs +1 -1
  74. package/internal-entity-heuristics.cjs +16 -575
  75. package/internal-entity-heuristics.d.cts +3 -1
  76. package/internal-entity-heuristics.d.mts +3 -1
  77. package/internal-entity-heuristics.mjs +1 -562
  78. package/internal-mapping-form.d.cts +1 -1
  79. package/internal-mapping-form.d.mts +1 -1
  80. package/internal-mappings-config.cjs +1 -1
  81. package/internal-mappings-config.d.cts +1 -1
  82. package/internal-mappings-config.d.mts +1 -1
  83. package/internal-mappings-config.mjs +1 -1
  84. package/internal-sync-engine.cjs +1 -1
  85. package/internal-sync-engine.d.cts +1 -1
  86. package/internal-sync-engine.d.mts +1 -1
  87. package/internal-sync-engine.mjs +1 -1
  88. package/internal-types.d.cts +1 -1
  89. package/internal-types.d.mts +1 -1
  90. package/internal-view-compiler.cjs +1 -1
  91. package/internal-view-compiler.d.cts +1 -1
  92. package/internal-view-compiler.d.mts +1 -1
  93. package/internal-view-compiler.mjs +1 -1
  94. package/internal.cjs +7 -7
  95. package/internal.d.cts +9 -9
  96. package/internal.d.mts +9 -9
  97. package/internal.mjs +7 -7
  98. package/{mapping-form-BymksK7h.d.mts → mapping-form-Bpvgf5b8.d.mts} +1 -1
  99. package/{mapping-form-Cmf8y-1m.d.cts → mapping-form-CV7y6qox.d.cts} +1 -1
  100. package/{mappings-config-Dsz6rcJb.d.cts → mappings-config-BBppW9fp.d.cts} +1 -1
  101. package/{mappings-config-DBG-KnYl.cjs → mappings-config-CNxBrbt9.cjs} +1 -1
  102. package/{mappings-config-C7FPwrJT.mjs → mappings-config-D_g20PyS.mjs} +1 -1
  103. package/{mappings-config-ktJhxmHm.d.mts → mappings-config-Dmm0H6p_.d.mts} +1 -1
  104. package/{namespace-probe-CTkb35Ro.d.cts → namespace-probe-BHk3NcyI.d.cts} +31 -2
  105. package/{namespace-probe-By8SCnym.d.mts → namespace-probe-Dt_HXcI-.d.mts} +31 -2
  106. package/package.json +1 -7
  107. package/{projection-DNi_2dVa.mjs → projection-BkYXvjTr.mjs} +2434 -1147
  108. package/{projection-B8RtxuEq.cjs → projection-By63gMC-.cjs} +2434 -1147
  109. package/{projection-sql-BYv40Hen.mjs → projection-sql-C3gZE3GS.mjs} +1 -1
  110. package/{projection-sql-SuhzhsMe.cjs → projection-sql-CHz7KzNS.cjs} +1 -1
  111. package/{schemas-DySv963y.d.cts → schemas-BSuo_eZQ.d.cts} +97 -35
  112. package/{schemas-DySv963y.d.mts → schemas-BSuo_eZQ.d.mts} +97 -35
  113. package/{sdk-BJ3OkhCq.cjs → sdk-BZSTXPyK.cjs} +161 -27
  114. package/{sdk-CXrarwvs.mjs → sdk-KzHpSf7F.mjs} +161 -27
  115. package/sdk.cjs +2 -2
  116. package/sdk.d.cts +4 -4
  117. package/sdk.d.mts +4 -4
  118. package/sdk.mjs +2 -2
  119. package/{sync-engine-D9ltfqkD.d.cts → sync-engine-C7W0Gkq0.d.cts} +2 -2
  120. package/{sync-engine-C_SwnFgF.d.mts → sync-engine-C9Q2FkR9.d.mts} +2 -2
  121. package/{sync-engine-BTUoH82k.mjs → sync-engine-CwdLkmch.mjs} +1 -1
  122. package/{sync-engine-DBlSP9r2.cjs → sync-engine-Di-vF26b.cjs} +1 -1
  123. package/{types-BtQCi_qP.d.cts → types-C9_2vW5a.d.mts} +1 -1
  124. package/{types-CTOl3pAX.d.mts → types-CQ2DgEH7.d.cts} +1 -1
  125. package/{view-compiler-B8tJ5IGw.mjs → view-compiler-CLTi1VL-.mjs} +2 -2
  126. package/{view-compiler-Ce_QE3dh.cjs → view-compiler-DaOz5QVl.cjs} +2 -2
  127. package/{view-compiler-BZgZisTG.d.mts → view-compiler-M23WiVGG.d.mts} +1 -1
  128. package/{view-compiler-D7GLf1n8.d.cts → view-compiler-cXqt4X-c.d.cts} +1 -1
  129. package/vite.d.cts +1 -1
  130. package/vite.d.mts +1 -1
@@ -0,0 +1,566 @@
1
+ import { a as MATERIALIZING_CONCEPTS } from "./entity-config-g_oMPXlN.mjs";
2
+ import { a as W, c as isTextLike, i as RELATIONSHIP_TIERS, l as isTimestampLike, n as CONCEPT_TIERS, o as isAmbiguous, r as FIELD_TIERS, s as isNumericLike, u as tierFor } from "./mapping-score-CS-MTDL9.mjs";
3
+ // ../core/src/entity-heuristics.ts
4
+ const TARGET_CONCEPTS = [
5
+ "contact",
6
+ "company",
7
+ "deal",
8
+ "activity",
9
+ "conversation",
10
+ "note"
11
+ ];
12
+ const TABLE_PATTERNS = [
13
+ {
14
+ concept: "contact",
15
+ names: [
16
+ "users",
17
+ "customers",
18
+ "clients",
19
+ "accounts",
20
+ "participants",
21
+ "attendees",
22
+ "people",
23
+ "members",
24
+ "contacts",
25
+ "students",
26
+ "pupils",
27
+ "learners",
28
+ "patients",
29
+ "subscribers",
30
+ "donors",
31
+ "guests",
32
+ "residents",
33
+ "tenants",
34
+ "applicants",
35
+ "candidates",
36
+ "leads",
37
+ "prospects"
38
+ ]
39
+ },
40
+ {
41
+ concept: "company",
42
+ names: [
43
+ "companies",
44
+ "organizations",
45
+ "organisations",
46
+ "orgs",
47
+ "teams",
48
+ "businesses",
49
+ "accounts"
50
+ ]
51
+ },
52
+ {
53
+ concept: "deal",
54
+ names: [
55
+ "deals",
56
+ "opportunities",
57
+ "subscriptions",
58
+ "orders",
59
+ "invoices",
60
+ "sales"
61
+ ]
62
+ },
63
+ {
64
+ concept: "conversation",
65
+ names: [
66
+ "conversations",
67
+ "messages",
68
+ "tickets",
69
+ "threads",
70
+ "chats",
71
+ "inbox"
72
+ ]
73
+ },
74
+ {
75
+ concept: "activity",
76
+ names: [
77
+ "events",
78
+ "activities",
79
+ "jobs",
80
+ "logs",
81
+ "audit",
82
+ "shifts",
83
+ "scans",
84
+ "sessions"
85
+ ]
86
+ },
87
+ {
88
+ concept: "note",
89
+ names: [
90
+ "notes",
91
+ "comments",
92
+ "annotations"
93
+ ]
94
+ }
95
+ ];
96
+ const CONCEPT_FIELDS = {
97
+ contact: [
98
+ {
99
+ field: "name",
100
+ candidates: [
101
+ "name",
102
+ "full_name",
103
+ "fullname",
104
+ "display_name",
105
+ "first_name",
106
+ "firstname",
107
+ "given_name"
108
+ ],
109
+ required: false
110
+ },
111
+ {
112
+ field: "email",
113
+ candidates: ["email", "email_address"],
114
+ required: true
115
+ },
116
+ {
117
+ field: "phone",
118
+ candidates: [
119
+ "phone",
120
+ "phone_number",
121
+ "phonenumber",
122
+ "mobile",
123
+ "mobile_number",
124
+ "mobilenumber",
125
+ "telephone"
126
+ ],
127
+ required: false
128
+ }
129
+ ],
130
+ company: [{
131
+ field: "name",
132
+ candidates: [
133
+ "name",
134
+ "company_name",
135
+ "legal_name",
136
+ "title"
137
+ ],
138
+ required: true
139
+ }, {
140
+ field: "domain",
141
+ candidates: [
142
+ "domain",
143
+ "website",
144
+ "url"
145
+ ],
146
+ required: false
147
+ }],
148
+ deal: [
149
+ {
150
+ field: "name",
151
+ candidates: ["name", "title"],
152
+ required: true
153
+ },
154
+ {
155
+ field: "value",
156
+ candidates: [
157
+ "value",
158
+ "amount",
159
+ "total",
160
+ "price"
161
+ ],
162
+ required: false
163
+ },
164
+ {
165
+ field: "stage",
166
+ candidates: [
167
+ "stage",
168
+ "status",
169
+ "state"
170
+ ],
171
+ required: false
172
+ }
173
+ ],
174
+ activity: [
175
+ {
176
+ field: "type",
177
+ candidates: [
178
+ "type",
179
+ "kind",
180
+ "event_type"
181
+ ],
182
+ required: false
183
+ },
184
+ {
185
+ field: "summary",
186
+ candidates: [
187
+ "summary",
188
+ "description",
189
+ "message",
190
+ "title"
191
+ ],
192
+ required: false
193
+ },
194
+ {
195
+ field: "createdAt",
196
+ candidates: [
197
+ "created_at",
198
+ "createdat",
199
+ "timestamp"
200
+ ],
201
+ required: false
202
+ }
203
+ ],
204
+ conversation: [{
205
+ field: "status",
206
+ candidates: ["status", "state"],
207
+ required: false
208
+ }, {
209
+ field: "subject",
210
+ candidates: [
211
+ "subject",
212
+ "title",
213
+ "preview"
214
+ ],
215
+ required: false
216
+ }],
217
+ note: [{
218
+ field: "body",
219
+ candidates: [
220
+ "body",
221
+ "content",
222
+ "text",
223
+ "note"
224
+ ],
225
+ required: true
226
+ }]
227
+ };
228
+ const CURSOR_CANDIDATES = [
229
+ "updatedat",
230
+ "updated_at",
231
+ "modifiedat",
232
+ "modified_at",
233
+ "createdat",
234
+ "created_at"
235
+ ];
236
+ function suggestCursorField(columnKeys) {
237
+ const lowerToActual = new Map(columnKeys.map((c) => [c.toLowerCase(), c]));
238
+ for (const candidate of CURSOR_CANDIDATES) {
239
+ const match = lowerToActual.get(candidate);
240
+ if (match) return match;
241
+ }
242
+ return null;
243
+ }
244
+ const MATERIALIZING = new Set(MATERIALIZING_CONCEPTS);
245
+ const ENDS_IN_CONSONANT_Y = /[^aeiou]y$/;
246
+ const NEEDS_ES = /(s|x|z|ch|sh)$/;
247
+ const IRREGULAR_PLURALS = {
248
+ person: "people",
249
+ child: "children",
250
+ man: "men",
251
+ woman: "women"
252
+ };
253
+ function pluralize(name) {
254
+ const irregular = IRREGULAR_PLURALS[name];
255
+ if (irregular) return irregular;
256
+ if (ENDS_IN_CONSONANT_Y.test(name)) return `${name.slice(0, -1)}ies`;
257
+ if (NEEDS_ES.test(name)) return `${name}es`;
258
+ return `${name}s`;
259
+ }
260
+ function matchesConcept(tableName, concept) {
261
+ const normalized = tableName.toLowerCase();
262
+ const entry = TABLE_PATTERNS.find((p) => p.concept === concept);
263
+ if (!entry) return null;
264
+ const candidates = [normalized, pluralize(normalized)];
265
+ if (candidates.some((candidate) => entry.names.includes(candidate))) return { exact: true };
266
+ if (entry.names.some((name) => candidates.some((candidate) => candidate.includes(name)))) return { exact: false };
267
+ return null;
268
+ }
269
+ const SENSITIVE_COLUMNS = /* @__PURE__ */ new Set([
270
+ "password",
271
+ "password_hash",
272
+ "passwordhash",
273
+ "access_token",
274
+ "accesstoken",
275
+ "api_key",
276
+ "apikey",
277
+ "client_secret",
278
+ "clientsecret",
279
+ "encrypted_password",
280
+ "encryptedpassword",
281
+ "refresh_token",
282
+ "refreshtoken",
283
+ "id_token",
284
+ "idtoken",
285
+ "password_digest",
286
+ "passworddigest",
287
+ "private_key",
288
+ "privatekey",
289
+ "secret",
290
+ "session_token",
291
+ "sessiontoken"
292
+ ]);
293
+ /**
294
+ * Does this table carry credentials? Such tables are withheld from suggestions
295
+ * and from bulk apply, so one click can never map an auth table into the CRM.
296
+ * They stay manually selectable — an explicit, informed choice is legitimate.
297
+ */
298
+ function hasSensitiveColumns(columns) {
299
+ return columns.some(isSensitiveColumn);
300
+ }
301
+ /** Is this one column a credential (a password, token, key or secret)? */
302
+ function isSensitiveColumn(column) {
303
+ return SENSITIVE_COLUMNS.has(column.toLowerCase().replaceAll("-", "_"));
304
+ }
305
+ /**
306
+ * Table names the supported auth libraries create.
307
+ *
308
+ * `hasSensitiveColumns` cannot catch these. Better Auth's `organization` table
309
+ * is `{id, name, slug, logo}` — no credential column anywhere, a real `name`,
310
+ * and "organizations" is in the company vocabulary above. It is, by every
311
+ * signal this module has, an excellent company candidate. On `vue-academy`
312
+ * `clivly init` duly chose it over `campuses`, the actual business table that
313
+ * every student row points at, and the first sync exported rows nothing could
314
+ * receive.
315
+ *
316
+ * Matched on name, deliberately, and this is the inverse of the rule above:
317
+ * withholding a table on a wrong guess is a real loss, so that is decided on
318
+ * columns; *ranking* one below another is cheap to get wrong, so a name match
319
+ * is enough. These are fixed names the plugins create, and an app whose own
320
+ * business table is called `member` still ranks — just after its rivals.
321
+ */
322
+ const FRAMEWORK_TABLE_NAMES = /* @__PURE__ */ new Set([
323
+ "account",
324
+ "session",
325
+ "user",
326
+ "verification",
327
+ "invitation",
328
+ "member",
329
+ "organization",
330
+ "team",
331
+ "team_member",
332
+ "apikey",
333
+ "api_key",
334
+ "jwks",
335
+ "passkey",
336
+ "rate_limit",
337
+ "ratelimit",
338
+ "two_factor",
339
+ "twofactor",
340
+ "__drizzle_migrations",
341
+ "drizzle_migrations"
342
+ ]);
343
+ /**
344
+ * Is this table one your auth library created, rather than one you wrote?
345
+ *
346
+ * Used to rank such tables below the developer's own when both could serve a
347
+ * concept. Never to exclude them: mapping `user` as the contact entity is
348
+ * legitimate for plenty of apps, and it stays selectable.
349
+ */
350
+ function isFrameworkTable(name) {
351
+ return FRAMEWORK_TABLE_NAMES.has(name.toLowerCase().replaceAll("-", "_"));
352
+ }
353
+ function metaFor(table, column) {
354
+ return table.columnsMeta?.find((c) => c.name === column);
355
+ }
356
+ function hasDefiningColumn(concept, columns) {
357
+ const lower = new Set(columns.map((c) => c.toLowerCase()));
358
+ const required = CONCEPT_FIELDS[concept].filter((f) => f.required);
359
+ return required.length > 0 && required.every((f) => f.candidates.some((c) => lower.has(c)));
360
+ }
361
+ function scoreConcepts(table) {
362
+ const out = [];
363
+ for (const concept of TARGET_CONCEPTS) {
364
+ if (!MATERIALIZING.has(concept)) continue;
365
+ const nameMatch = matchesConcept(table.name, concept);
366
+ const definingColumns = hasDefiningColumn(concept, table.columns);
367
+ if (!(nameMatch || definingColumns)) continue;
368
+ let score = 0;
369
+ const reasons = [];
370
+ if (nameMatch?.exact) {
371
+ score += W.nameExact;
372
+ reasons.push(`name matches "${table.name}"`);
373
+ } else if (nameMatch) {
374
+ score += W.nameSubstring;
375
+ reasons.push(`name looks like ${concept}`);
376
+ }
377
+ if (definingColumns) {
378
+ score += W.definingColumn;
379
+ reasons.push(`has the columns a ${concept} needs`);
380
+ }
381
+ if (table.columnsMeta?.some((c) => c.isPrimaryKey)) {
382
+ score += W.hasPrimaryKey;
383
+ reasons.push("has primary key");
384
+ }
385
+ if (table.rowCount !== void 0) {
386
+ if (table.rowCount === 0) {
387
+ score += W.emptyTable;
388
+ reasons.push("table is empty");
389
+ } else {
390
+ score += W.hasRows;
391
+ reasons.push(`${table.rowCount.toLocaleString("en-US")} rows`);
392
+ }
393
+ }
394
+ out.push({
395
+ value: concept,
396
+ score,
397
+ tier: tierFor(score, CONCEPT_TIERS),
398
+ reasons
399
+ });
400
+ }
401
+ return out.sort((a, b) => b.score - a.score);
402
+ }
403
+ function topConcept(table) {
404
+ const ranked = scoreConcepts(table);
405
+ const best = ranked[0];
406
+ if (!best) return null;
407
+ return {
408
+ best,
409
+ ambiguous: isAmbiguous(ranked)
410
+ };
411
+ }
412
+ function requiredFieldsFor(concept) {
413
+ if (concept === "custom") return [];
414
+ return CONCEPT_FIELDS[concept].filter((f) => f.required).map((f) => f.field);
415
+ }
416
+ function validateMapping(requiredFields, fieldMap) {
417
+ const missing = requiredFields.filter((field) => !fieldMap[field]);
418
+ return {
419
+ valid: missing.length === 0,
420
+ missing
421
+ };
422
+ }
423
+ const DISCRIMINATOR_COLUMNS = [
424
+ "role",
425
+ "type",
426
+ "kind",
427
+ "status",
428
+ "state",
429
+ "category",
430
+ "tier"
431
+ ];
432
+ function suggestDiscriminatorColumns(columns) {
433
+ const lowerToActual = new Map(columns.map((c) => [c.toLowerCase(), c]));
434
+ const out = [];
435
+ for (const name of DISCRIMINATOR_COLUMNS) {
436
+ const match = lowerToActual.get(name);
437
+ if (match) out.push(match);
438
+ }
439
+ return out;
440
+ }
441
+ const COMPANY_FK_HINTS = [
442
+ "organization_id",
443
+ "organisation_id",
444
+ "org_id",
445
+ "company_id",
446
+ "account_id",
447
+ "team_id"
448
+ ];
449
+ function firstMatchingColumn(columns, hints) {
450
+ const lowerToActual = new Map(columns.map((c) => [c.toLowerCase(), c]));
451
+ for (const hint of hints) {
452
+ const match = lowerToActual.get(hint);
453
+ if (match) return match;
454
+ }
455
+ return null;
456
+ }
457
+ /**
458
+ * Suggest contact→company relationships. When the source table carries FK
459
+ * metadata (`references`), the target table is a *fact*, not a name guess —
460
+ * that scores highest. Without metadata (v1 hosts) we fall back to the legacy
461
+ * FK-name hints at a lower tier.
462
+ */
463
+ function scoreRelationships(source, allTables) {
464
+ const companyTables = allTables.filter((t) => t.name !== source.name && topConcept(t)?.best.value === "company");
465
+ if (companyTables.length === 0) return [];
466
+ const companyNames = new Set(companyTables.map((t) => t.name.toLowerCase()));
467
+ const out = [];
468
+ const seenTargets = /* @__PURE__ */ new Set();
469
+ for (const col of source.columnsMeta ?? []) {
470
+ const ref = col.references;
471
+ if (!(ref && companyNames.has(ref.table.toLowerCase()))) continue;
472
+ if (seenTargets.has(ref.table.toLowerCase())) continue;
473
+ seenTargets.add(ref.table.toLowerCase());
474
+ out.push({
475
+ value: {
476
+ name: "company",
477
+ entityTable: ref.table,
478
+ via: {
479
+ fkOn: "contact",
480
+ column: `${source.name}.${col.name}`
481
+ }
482
+ },
483
+ score: W.fkResolved,
484
+ tier: tierFor(W.fkResolved, RELATIONSHIP_TIERS),
485
+ reasons: [`foreign key → ${ref.table}.${ref.column}`]
486
+ });
487
+ }
488
+ if (source.columnsMeta?.length) return out.sort((a, b) => b.score - a.score);
489
+ const contactFk = firstMatchingColumn(source.columns, COMPANY_FK_HINTS);
490
+ if (contactFk) out.push({
491
+ value: {
492
+ name: "company",
493
+ entityTable: companyTables[0]?.name ?? "",
494
+ via: {
495
+ fkOn: "contact",
496
+ column: `${source.name}.${contactFk}`
497
+ }
498
+ },
499
+ score: W.fkNameHint,
500
+ tier: tierFor(W.fkNameHint, RELATIONSHIP_TIERS),
501
+ reasons: [`column "${contactFk}" looks like a company link`]
502
+ });
503
+ return out.sort((a, b) => b.score - a.score);
504
+ }
505
+ const FIELD_TYPE_EXPECTATION = {
506
+ name: "text",
507
+ email: "text",
508
+ phone: "text",
509
+ domain: "text",
510
+ stage: "text",
511
+ status: "text",
512
+ subject: "text",
513
+ body: "text",
514
+ summary: "text",
515
+ type: "text",
516
+ value: "numeric",
517
+ createdAt: "timestamp"
518
+ };
519
+ function typeFits(field, type) {
520
+ const expectation = FIELD_TYPE_EXPECTATION[field];
521
+ if (!(expectation && type)) return null;
522
+ if (expectation === "text") return isTextLike(type);
523
+ if (expectation === "numeric") return isNumericLike(type);
524
+ return isTimestampLike(type);
525
+ }
526
+ function scoreFieldMap(concept, table) {
527
+ const lowerToActual = new Map(table.columns.map((c) => [c.toLowerCase(), c]));
528
+ const out = [];
529
+ for (const { field, candidates, required } of CONCEPT_FIELDS[concept]) for (const candidate of candidates) {
530
+ const column = lowerToActual.get(candidate);
531
+ if (!column) continue;
532
+ let score = W.fieldNameMatch;
533
+ const reasons = [`name matches "${column}"`];
534
+ const meta = metaFor(table, column);
535
+ const fits = typeFits(field, meta?.type);
536
+ if (fits === true) {
537
+ score += W.typeCompatible;
538
+ reasons.push(`type ${meta?.type}`);
539
+ } else if (fits === false) {
540
+ score += W.typeMismatch;
541
+ reasons.push(`type ${meta?.type} does not fit ${field}`);
542
+ }
543
+ if (required && meta?.nullable === false) {
544
+ score += W.requiredNotNull;
545
+ reasons.push("not null");
546
+ }
547
+ out.push({
548
+ value: {
549
+ field,
550
+ column,
551
+ required
552
+ },
553
+ score,
554
+ tier: tierFor(score, FIELD_TIERS),
555
+ reasons
556
+ });
557
+ break;
558
+ }
559
+ return out;
560
+ }
561
+ function toFieldMap(scored) {
562
+ const map = {};
563
+ for (const { value } of scored) map[value.field] = value.column;
564
+ return map;
565
+ }
566
+ export { isSensitiveColumn as a, scoreConcepts as c, suggestCursorField as d, suggestDiscriminatorColumns as f, validateMapping as h, isFrameworkTable as i, scoreFieldMap as l, topConcept as m, hasDefiningColumn as n, matchesConcept as o, toFieldMap as p, hasSensitiveColumns as r, requiredFieldsFor as s, TARGET_CONCEPTS as t, scoreRelationships as u };
package/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const require_entity_config = require("./entity-config-nWWgJXLw.cjs");
3
+ const require_entity_config = require("./entity-config-DiCJ6mhI.cjs");
4
4
  require("./mapping-score-D2TCQiOr.cjs");
5
- const require_internal_entity_heuristics = require("./internal-entity-heuristics.cjs");
6
- const require_sdk = require("./sdk-BJ3OkhCq.cjs");
5
+ const require_entity_heuristics = require("./entity-heuristics-CIParuQe.cjs");
6
+ const require_sdk = require("./sdk-BZSTXPyK.cjs");
7
7
  let node_child_process = require("node:child_process");
8
8
  let node_fs = require("node:fs");
9
9
  let node_module = require("node:module");
@@ -1771,6 +1771,7 @@ async function runLogin(options) {
1771
1771
  const session = await createPairingSession(options.apiUrl, deps, options.rotate);
1772
1772
  if ("exitCode" in session) return session.exitCode;
1773
1773
  deps.out(`\nApprove this login in your browser:\n ${session.approveUrl}\n`);
1774
+ if (session.userCode) deps.out(`When asked, enter this code: ${session.userCode}\nOnly enter it on a page you opened from this terminal. Never share it.\n`);
1774
1775
  if (options.openBrowser) deps.open(session.approveUrl);
1775
1776
  deps.out("Waiting for approval…");
1776
1777
  const outcome = await pollForApproval(options.apiUrl, deps, session);
@@ -1829,27 +1830,27 @@ function fkPromotedCompanies(tables, contact) {
1829
1830
  const targets = /* @__PURE__ */ new Set();
1830
1831
  for (const column of contact.columns) {
1831
1832
  const table = column.references?.table;
1832
- if (table && !require_internal_entity_heuristics.isFrameworkTable(table)) targets.add(table.toLowerCase());
1833
+ if (table && !require_entity_heuristics.isFrameworkTable(table)) targets.add(table.toLowerCase());
1833
1834
  }
1834
- return tables.filter((t) => targets.has(t.tableName.toLowerCase()) && t.tableName !== contact.tableName && require_internal_entity_heuristics.hasDefiningColumn("company", columnNames(t)));
1835
+ return tables.filter((t) => targets.has(t.tableName.toLowerCase()) && t.tableName !== contact.tableName && require_entity_heuristics.hasDefiningColumn("company", columnNames(t)));
1835
1836
  }
1836
1837
  function rankCandidates$1(tables, concept, contact = null) {
1837
1838
  const promoted = concept === "company" ? fkPromotedCompanies(tables, contact) : [];
1838
1839
  const promotedNames = new Set(promoted.map((t) => t.tableName));
1839
1840
  return tables.map((t) => ({
1840
1841
  t,
1841
- m: require_internal_entity_heuristics.matchesConcept(t.tableName, concept) ?? (promotedNames.has(t.tableName) ? { exact: false } : null)
1842
+ m: require_entity_heuristics.matchesConcept(t.tableName, concept) ?? (promotedNames.has(t.tableName) ? { exact: false } : null)
1842
1843
  })).filter((c) => Boolean(c.m)).sort((a, b) => {
1843
- const usable = Number(require_internal_entity_heuristics.hasDefiningColumn(concept, columnNames(b.t))) - Number(require_internal_entity_heuristics.hasDefiningColumn(concept, columnNames(a.t)));
1844
+ const usable = Number(require_entity_heuristics.hasDefiningColumn(concept, columnNames(b.t))) - Number(require_entity_heuristics.hasDefiningColumn(concept, columnNames(a.t)));
1844
1845
  if (usable !== 0) return usable;
1845
1846
  const aPromoted = promotedNames.has(a.t.tableName);
1846
1847
  if (aPromoted !== promotedNames.has(b.t.tableName)) {
1847
1848
  const loser = aPromoted ? b.t : a.t;
1848
- if (require_internal_entity_heuristics.isFrameworkTable(loser.tableName)) return aPromoted ? -1 : 1;
1849
+ if (require_entity_heuristics.isFrameworkTable(loser.tableName)) return aPromoted ? -1 : 1;
1849
1850
  }
1850
1851
  const exact = Number(b.m.exact) - Number(a.m.exact);
1851
1852
  if (exact !== 0) return exact;
1852
- return Number(require_internal_entity_heuristics.isFrameworkTable(a.t.tableName)) - Number(require_internal_entity_heuristics.isFrameworkTable(b.t.tableName));
1853
+ return Number(require_entity_heuristics.isFrameworkTable(a.t.tableName)) - Number(require_entity_heuristics.isFrameworkTable(b.t.tableName));
1853
1854
  }).map((c) => c.t);
1854
1855
  }
1855
1856
  function selectEntities(tables) {
@@ -1868,7 +1869,7 @@ function selectEntities(tables) {
1868
1869
  }
1869
1870
  function chooseSyncFields(table, todos) {
1870
1871
  const columnKeys = table.columns.map((c) => c.key);
1871
- let cursorField = require_internal_entity_heuristics.suggestCursorField(columnKeys);
1872
+ let cursorField = require_entity_heuristics.suggestCursorField(columnKeys);
1872
1873
  if (!cursorField) {
1873
1874
  cursorField = table.columns.find((c) => c.isPrimary)?.key ?? columnKeys[0] ?? "id";
1874
1875
  todos.push(`No updated_at-like column on "${table.tableName}" — using "${cursorField}" as the sync cursor. Confirm it is monotonic.`);
@@ -1892,10 +1893,10 @@ const SPLIT_NAME_COLUMNS = /* @__PURE__ */ new Set([
1892
1893
  ]);
1893
1894
  function buildEntity(table, concept, todos) {
1894
1895
  const canonical = require_entity_config.CANONICAL_FIELDS[concept];
1895
- const suggested = require_internal_entity_heuristics.toFieldMap(require_internal_entity_heuristics.scoreFieldMap(concept, toScoredTable(table)));
1896
+ const suggested = require_entity_heuristics.toFieldMap(require_entity_heuristics.scoreFieldMap(concept, toScoredTable(table)));
1896
1897
  const fields = {};
1897
1898
  for (const [key, column] of Object.entries(suggested)) if (canonical.includes(key)) fields[key] = column;
1898
- for (const required of require_internal_entity_heuristics.requiredFieldsFor(concept)) if (!fields[required]) todos.push(`Could not map required ${concept} field "${required}" on "${table.tableName}" — add it manually.`);
1899
+ for (const required of require_entity_heuristics.requiredFieldsFor(concept)) if (!fields[required]) todos.push(`Could not map required ${concept} field "${required}" on "${table.tableName}" — add it manually.`);
1899
1900
  const nameColumn = fields.name?.toLowerCase();
1900
1901
  if (nameColumn && SPLIT_NAME_COLUMNS.has(nameColumn)) todos.push(`Mapped ${concept} "name" to "${fields.name}" on "${table.tableName}" — that is the given name only. Clivly mirrors one column per field, so add a full-name column if you want surnames.`);
1901
1902
  const { cursorField, idField } = chooseSyncFields(table, todos);
@@ -1951,11 +1952,11 @@ function planInit(schema, overrides = {}) {
1951
1952
  if (hasMappedFields(candidate)) {
1952
1953
  todos.push(...candidateTodos);
1953
1954
  company = candidate;
1954
- if (require_internal_entity_heuristics.matchesConcept(companyTable.tableName, "contact")) todos.push(`"${companyTable.tableName}" matches both contact and company naming — assigned to company. Swap it to your contact entity if that's wrong.`);
1955
+ if (require_entity_heuristics.matchesConcept(companyTable.tableName, "contact")) todos.push(`"${companyTable.tableName}" matches both contact and company naming — assigned to company. Swap it to your contact entity if that's wrong.`);
1955
1956
  } else todos.push(`"${companyTable.tableName}" looked like a company but no fields could be mapped — left it out. Add it to \`entities\` once you know which columns map to name/domain, or build a derived object from it in Clivly (Integrations → Map as custom object) if the fields live in a joined table.`);
1956
1957
  }
1957
1958
  if (contactTable && contact) {
1958
- const scored = require_internal_entity_heuristics.scoreRelationships(toScoredTable(contactTable), schema.tables.map(toScoredTable));
1959
+ const scored = require_entity_heuristics.scoreRelationships(toScoredTable(contactTable), schema.tables.map(toScoredTable));
1959
1960
  const top = scored[0];
1960
1961
  const runnerUp = scored[1];
1961
1962
  const isClearWinner = top !== void 0 && (runnerUp === void 0 || top.score - runnerUp.score >= 15);
@@ -2036,7 +2037,7 @@ function rankContactCandidates(tables) {
2036
2037
  const columns = new Set(table.columns.flatMap((c) => [c.dbName.toLowerCase(), c.key.toLowerCase()]));
2037
2038
  const reasons = [];
2038
2039
  let score = 0;
2039
- if (require_internal_entity_heuristics.matchesConcept(table.tableName, "contact")) {
2040
+ if (require_entity_heuristics.matchesConcept(table.tableName, "contact")) {
2040
2041
  score += NAME_MATCH_WEIGHT;
2041
2042
  reasons.push("the name looks like a people table");
2042
2043
  }
package/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { t as CANONICAL_FIELDS } from "./entity-config-DQVSprlG.mjs";
2
+ import { t as CANONICAL_FIELDS } from "./entity-config-g_oMPXlN.mjs";
3
3
  import "./mapping-score-CS-MTDL9.mjs";
4
- import { hasDefiningColumn, isFrameworkTable, matchesConcept, requiredFieldsFor, scoreFieldMap, scoreRelationships, suggestCursorField, toFieldMap } from "./internal-entity-heuristics.mjs";
5
- import { n as createClivlySDK, u as isPlaceholderUrl } from "./sdk-CXrarwvs.mjs";
4
+ import { d as suggestCursorField, i as isFrameworkTable, l as scoreFieldMap, n as hasDefiningColumn, o as matchesConcept, p as toFieldMap, s as requiredFieldsFor, u as scoreRelationships } from "./entity-heuristics-DE5ujoHw.mjs";
5
+ import { n as createClivlySDK, u as isPlaceholderUrl } from "./sdk-KzHpSf7F.mjs";
6
6
  import { createRequire } from "node:module";
7
7
  import { spawn } from "node:child_process";
8
8
  import { accessSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, watch, writeFileSync } from "node:fs";
@@ -1770,6 +1770,7 @@ async function runLogin(options) {
1770
1770
  const session = await createPairingSession(options.apiUrl, deps, options.rotate);
1771
1771
  if ("exitCode" in session) return session.exitCode;
1772
1772
  deps.out(`\nApprove this login in your browser:\n ${session.approveUrl}\n`);
1773
+ if (session.userCode) deps.out(`When asked, enter this code: ${session.userCode}\nOnly enter it on a page you opened from this terminal. Never share it.\n`);
1773
1774
  if (options.openBrowser) deps.open(session.approveUrl);
1774
1775
  deps.out("Waiting for approval…");
1775
1776
  const outcome = await pollForApproval(options.apiUrl, deps, session);
@@ -1,4 +1,4 @@
1
- import { a as _enum, o as array, p as string, u as object } from "./projection-DNi_2dVa.mjs";
1
+ import { a as _enum, o as array, p as string, u as object } from "./projection-BkYXvjTr.mjs";
2
2
  // ../core/src/contact-segment.ts
3
3
  /** AND conditions over deliberately mapped host fields, never SQL identifiers. */
4
4
  const contactSegmentSchema = array(object({
@@ -1,4 +1,4 @@
1
- const require_projection = require("./projection-B8RtxuEq.cjs");
1
+ const require_projection = require("./projection-By63gMC-.cjs");
2
2
  // ../core/src/contact-segment.ts
3
3
  /** AND conditions over deliberately mapped host fields, never SQL identifiers. */
4
4
  const contactSegmentSchema = require_projection.array(require_projection.object({