@clivly/core 0.8.0 → 0.9.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 (48) hide show
  1. package/README.md +182 -16
  2. package/dist/drizzle.cjs +82 -1
  3. package/dist/drizzle.d.cts +23 -2
  4. package/dist/drizzle.d.mts +23 -2
  5. package/dist/drizzle.mjs +81 -2
  6. package/dist/entity-config-8Fgr6IOH.mjs +666 -0
  7. package/dist/entity-config-CLxI8dVb.d.cts +556 -0
  8. package/dist/entity-config-CLxI8dVb.d.mts +556 -0
  9. package/dist/entity-config-Dh8aEcgj.cjs +779 -0
  10. package/dist/entity-config.cjs +13 -349
  11. package/dist/entity-config.d.cts +2 -295
  12. package/dist/entity-config.d.mts +2 -295
  13. package/dist/entity-config.mjs +2 -339
  14. package/dist/entity-heuristics.cjs +28 -8
  15. package/dist/entity-heuristics.d.cts +2 -12
  16. package/dist/entity-heuristics.d.mts +2 -12
  17. package/dist/entity-heuristics.mjs +28 -8
  18. package/dist/env-file.cjs +59 -0
  19. package/dist/env-file.d.cts +23 -0
  20. package/dist/env-file.d.mts +23 -0
  21. package/dist/env-file.mjs +55 -0
  22. package/dist/index.cjs +83 -2
  23. package/dist/index.d.cts +72 -2
  24. package/dist/index.d.mts +72 -2
  25. package/dist/index.mjs +69 -3
  26. package/dist/integration-state.cjs +242 -0
  27. package/dist/integration-state.d.cts +88 -0
  28. package/dist/integration-state.d.mts +88 -0
  29. package/dist/integration-state.mjs +232 -0
  30. package/dist/mapping-form.d.cts +1 -1
  31. package/dist/mapping-form.d.mts +1 -1
  32. package/dist/mappings-config.cjs +32 -6
  33. package/dist/mappings-config.d.cts +7 -1
  34. package/dist/mappings-config.d.mts +7 -1
  35. package/dist/mappings-config.mjs +32 -6
  36. package/dist/projection-BXBkh7qp.cjs +98 -0
  37. package/dist/projection-C_EMRmZ8.mjs +75 -0
  38. package/dist/sync-engine.cjs +9 -2
  39. package/dist/sync-engine.d.cts +1 -1
  40. package/dist/sync-engine.d.mts +1 -1
  41. package/dist/sync-engine.mjs +9 -2
  42. package/dist/view-compiler-BpNI8Ttw.cjs +299 -0
  43. package/dist/view-compiler-CcqsGxv4.mjs +270 -0
  44. package/dist/view-compiler.cjs +6 -188
  45. package/dist/view-compiler.d.cts +12 -2
  46. package/dist/view-compiler.d.mts +12 -2
  47. package/dist/view-compiler.mjs +2 -185
  48. package/package.json +21 -1
@@ -0,0 +1,779 @@
1
+ const require_projection = require("./projection-BXBkh7qp.cjs");
2
+ let zod = require("zod");
3
+ //#region src/schema-meta.ts
4
+ /**
5
+ * Accessors over a discovered table's schema-v2 metadata.
6
+ *
7
+ * Every helper treats *absent* metadata as **unknown**, never as a negative
8
+ * fact. `coversUniqueKey` returning false on a v1 payload is what makes
9
+ * projection validation fail closed: we cannot prove a join is many-to-one, so
10
+ * we refuse to compile it rather than guess.
11
+ */
12
+ function columnMetaFor(table, column) {
13
+ return table.columnsMeta?.find((c) => c.name === column);
14
+ }
15
+ /**
16
+ * Every primary-key column. More than one entry means a composite PK, which is
17
+ * why `base_pk` identity is rejected for such tables.
18
+ */
19
+ function primaryKeyColumns(table) {
20
+ return (table.columnsMeta ?? []).filter((c) => c.isPrimaryKey).map((c) => c.name);
21
+ }
22
+ /**
23
+ * Do `columns` contain every column of at least one unique key on `table`?
24
+ *
25
+ * This is the fan-out test. A join whose ON columns cover a unique key of the
26
+ * joined table matches at most one row per base row; one that does not can
27
+ * match many.
28
+ */
29
+ function coversUniqueKey(table, columns) {
30
+ const present = new Set(columns);
31
+ return (table.uniqueConstraints ?? []).some((key) => key.length > 0 && key.every((column) => present.has(column)));
32
+ }
33
+ /** Is this table's payload rich enough to validate a projection against? */
34
+ function hasRichMeta(table) {
35
+ return Boolean(table.columnsMeta && table.uniqueConstraints);
36
+ }
37
+ //#endregion
38
+ //#region src/projection-cardinality.ts
39
+ /**
40
+ * Cardinality analysis for projection joins.
41
+ *
42
+ * A join matches at most one row per base row exactly when the columns it
43
+ * constrains *on the joined table* cover a whole unique key of that table.
44
+ * Anything else can match many rows — "fan-out" — which multiplies the view's
45
+ * output and is only safe if identity is unique per output row.
46
+ *
47
+ * Unknown metadata is treated as fan-out. That is deliberate: we can never
48
+ * prove safety from an absent constraint list, and guessing wrong silently
49
+ * corrupts the mirror.
50
+ */
51
+ /** The join's own columns constrained by its ON conditions. */
52
+ function joinSideColumns(join) {
53
+ const columns = [];
54
+ for (const condition of join.on) for (const ref of [condition.left, condition.right]) if (ref.table === join.key) columns.push(ref.column);
55
+ return columns;
56
+ }
57
+ function joinFansOut(join, joinTable) {
58
+ return !coversUniqueKey(joinTable, joinSideColumns(join));
59
+ }
60
+ /** Every join in the projection that can multiply rows. */
61
+ function fanOutJoins(projection, tablesByName) {
62
+ return projection.joins.filter((join) => {
63
+ const table = tablesByName.get(join.table);
64
+ return table ? joinFansOut(join, table) : true;
65
+ });
66
+ }
67
+ //#endregion
68
+ //#region src/projection-validate.ts
69
+ /**
70
+ * Semantic validation for a projection mapping, against the host's discovered
71
+ * schema.
72
+ *
73
+ * The organising principle is **fail closed**. Every check that cannot be
74
+ * proven safe from the discovered metadata is an error, not a warning: a
75
+ * projection whose `id` column is not unique per output row silently collapses
76
+ * or duplicates mirror rows at sync time, which is the worst failure mode in
77
+ * the system and is invisible until data is already wrong.
78
+ */
79
+ const RESERVED_FIELD = "id";
80
+ const TEXT_TYPES = /* @__PURE__ */ new Set([
81
+ "text",
82
+ "varchar",
83
+ "char",
84
+ "citext",
85
+ "json",
86
+ "jsonb"
87
+ ]);
88
+ function isTextType(type) {
89
+ if (!type) return true;
90
+ const base = type.toLowerCase().split("(")[0]?.trim() ?? "";
91
+ return TEXT_TYPES.has(base);
92
+ }
93
+ function buildResolver(projection, schema) {
94
+ const tablesByName = new Map(schema.map((t) => [t.name, t]));
95
+ const refToTable = /* @__PURE__ */ new Map([[require_projection.BASE_REF, projection.baseTable]]);
96
+ for (const join of projection.joins) refToTable.set(join.key, join.table);
97
+ return {
98
+ tablesByName,
99
+ tableFor(refTable) {
100
+ const name = refToTable.get(refTable);
101
+ return name ? tablesByName.get(name) : void 0;
102
+ }
103
+ };
104
+ }
105
+ function checkRef(errors, resolver, path, ref) {
106
+ const table = resolver.tableFor(ref.table);
107
+ if (!table) {
108
+ errors.push({
109
+ path,
110
+ message: `unknown ref table "${ref.table}"`
111
+ });
112
+ return;
113
+ }
114
+ if (!table.columns.includes(ref.column)) errors.push({
115
+ path,
116
+ message: `column "${ref.column}" does not exist on "${table.name}"`
117
+ });
118
+ }
119
+ function checkTablesExist(errors, projection, resolver, base) {
120
+ let ok = true;
121
+ const names = [{
122
+ name: projection.baseTable,
123
+ path: `${base}.projection.baseTable`
124
+ }, ...projection.joins.map((j, i) => ({
125
+ name: j.table,
126
+ path: `${base}.projection.joins.${i}.table`
127
+ }))];
128
+ for (const { name, path } of names) {
129
+ const table = resolver.tablesByName.get(name);
130
+ if (!table) {
131
+ errors.push({
132
+ path,
133
+ message: `table "${name}" is not in the discovered schema`
134
+ });
135
+ ok = false;
136
+ continue;
137
+ }
138
+ if (!hasRichMeta(table)) {
139
+ errors.push({
140
+ path,
141
+ message: `table "${name}" has no key/column metadata — upgrade @clivly/sdk and re-run discovery before using a projection`
142
+ });
143
+ ok = false;
144
+ }
145
+ }
146
+ return ok;
147
+ }
148
+ function checkStructure(errors, projection, base) {
149
+ const seen = /* @__PURE__ */ new Set();
150
+ projection.joins.forEach((join, index) => {
151
+ const path = `${base}.projection.joins.${index}.key`;
152
+ if (join.key === "base") errors.push({
153
+ path,
154
+ message: `join key "${require_projection.BASE_REF}" is reserved`
155
+ });
156
+ if (seen.has(join.key)) errors.push({
157
+ path,
158
+ message: `duplicate join key "${join.key}"`
159
+ });
160
+ seen.add(join.key);
161
+ });
162
+ for (const field of Object.keys(projection.fieldBindings)) if (field === RESERVED_FIELD) errors.push({
163
+ path: `${base}.projection.fieldBindings.${field}`,
164
+ message: `"${RESERVED_FIELD}" is reserved — the view always projects identity as "id"`
165
+ });
166
+ const declared = /* @__PURE__ */ new Set([require_projection.BASE_REF]);
167
+ for (const [index, join] of projection.joins.entries()) {
168
+ declared.add(join.key);
169
+ for (const condition of join.on) for (const ref of [condition.left, condition.right]) if (!declared.has(ref.table)) errors.push({
170
+ path: `${base}.projection.joins.${index}.on`,
171
+ message: `join "${join.key}" references "${ref.table}", which is declared later`
172
+ });
173
+ }
174
+ }
175
+ function checkRefs(errors, projection, resolver, base, basePk) {
176
+ projection.joins.forEach((join, index) => {
177
+ join.on.forEach((condition, conditionIndex) => {
178
+ const path = `${base}.projection.joins.${index}.on.${conditionIndex}`;
179
+ checkRef(errors, resolver, path, condition.left);
180
+ checkRef(errors, resolver, path, condition.right);
181
+ });
182
+ });
183
+ for (const [field, binding] of Object.entries(projection.fieldBindings)) checkRef(errors, resolver, `${base}.projection.fieldBindings.${field}`, binding.from);
184
+ for (const ref of require_projection.identityRefs(projection.identity, basePk)) checkRef(errors, resolver, `${base}.projection.identity`, ref);
185
+ }
186
+ function checkIdentitySafety(errors, projection, resolver, base, baseTable) {
187
+ const path = `${base}.projection.identity`;
188
+ const pk = primaryKeyColumns(baseTable);
189
+ if (projection.identity.kind === "base_pk" && !projection.identity.column) {
190
+ if (pk.length === 0) {
191
+ errors.push({
192
+ path,
193
+ message: `"${baseTable.name}" has no discovered primary key — name an identity column explicitly`
194
+ });
195
+ return;
196
+ }
197
+ if (pk.length > 1) {
198
+ errors.push({
199
+ path,
200
+ message: `"${baseTable.name}" has a composite primary key (${pk.join(", ")}) — use a composite identity instead`
201
+ });
202
+ return;
203
+ }
204
+ }
205
+ if (projection.identity.kind !== "composite") return;
206
+ for (const part of projection.identity.parts) {
207
+ const table = resolver.tableFor(part.table);
208
+ const meta = table && columnMetaFor(table, part.column);
209
+ if (!meta) continue;
210
+ if (meta.nullable !== false) errors.push({
211
+ path,
212
+ message: `composite identity part "${part.table}.${part.column}" must be NOT NULL — CONCAT_WS skips nulls, so distinct rows would share an id`
213
+ });
214
+ if (isTextType(meta.type)) errors.push({
215
+ path,
216
+ message: `composite identity part "${part.table}.${part.column}" is text-typed — a value containing "::" would make two distinct rows share an id`
217
+ });
218
+ }
219
+ }
220
+ function checkFanOut(errors, projection, resolver, base, basePk) {
221
+ const fanning = fanOutJoins(projection, resolver.tablesByName);
222
+ if (fanning.length === 0) return;
223
+ if (fanning.length > 1) {
224
+ errors.push({
225
+ path: `${base}.projection.joins`,
226
+ message: `at most one fan-out join is allowed; ${fanning.map((j) => `"${j.key}"`).join(", ")} all match multiple rows per base row`
227
+ });
228
+ return;
229
+ }
230
+ const [join] = fanning;
231
+ if (!join) return;
232
+ const joinTable = resolver.tablesByName.get(join.table);
233
+ if (!joinTable) return;
234
+ const identityPath = `${base}.projection.identity`;
235
+ if (projection.identity.kind === "base_pk") {
236
+ errors.push({
237
+ path: identityPath,
238
+ message: `join "${join.key}" fans out, so base_pk identity would give every fanned-out row the same id`
239
+ });
240
+ return;
241
+ }
242
+ if (!coversUniqueKey(joinTable, require_projection.identityRefs(projection.identity, basePk).filter((ref) => ref.table === join.key).map((ref) => ref.column))) errors.push({
243
+ path: identityPath,
244
+ message: `identity does not uniquely identify a row of "${joinTable.name}", which fans out — include a unique key of that table`
245
+ });
246
+ }
247
+ /**
248
+ * Validate a projection against the discovered schema. Returns every error
249
+ * found (not just the first) so a builder UI can show them all at once.
250
+ */
251
+ function validateProjection(projection, schema, base) {
252
+ const errors = [];
253
+ const resolver = buildResolver(projection, schema);
254
+ checkStructure(errors, projection, base);
255
+ if (!checkTablesExist(errors, projection, resolver, base)) return errors;
256
+ const baseTable = resolver.tablesByName.get(projection.baseTable);
257
+ if (!baseTable) return errors;
258
+ const basePk = primaryKeyColumns(baseTable)[0] ?? "id";
259
+ checkRefs(errors, projection, resolver, base, basePk);
260
+ checkIdentitySafety(errors, projection, resolver, base, baseTable);
261
+ checkFanOut(errors, projection, resolver, base, basePk);
262
+ return errors;
263
+ }
264
+ //#endregion
265
+ //#region src/entity-config.ts
266
+ /**
267
+ * Entity Config v2 — the declarative contract that turns Clivly's "schema-aware"
268
+ * promise into a real capability.
269
+ *
270
+ * A CRM entity is no longer a flat table name. It is a *derived entity*: a
271
+ * filtered slice of a host table (`source` + `filter`), a column allowlist
272
+ * (`fields` + `readOnly`), and declared `relationships` to other entities. The
273
+ * same host table can back several entities (e.g. `users` → owners + members)
274
+ * distinguished by `role`.
275
+ *
276
+ * This module is the Phase 1 slice: types, schema, `defineClivlyConfig` (a
277
+ * structural helper) and `validateEntitiesConfig` (semantic validation against
278
+ * the host's discovered schema). It performs NO DB access and generates no SQL —
279
+ * the view compiler (Phase 2) and sync engine (Phase 3) consume this contract.
280
+ */
281
+ /** Canonical CRM concepts a host entity can map onto. */
282
+ const CRM_CONCEPTS = [
283
+ "contact",
284
+ "company",
285
+ "deal",
286
+ "activity",
287
+ "conversation",
288
+ "note"
289
+ ];
290
+ /**
291
+ * The canonical `fields` keys the mirror actually persists, per concept — the
292
+ * crm_* columns the sync store writes. An entity's `fields` map keys must be one
293
+ * of these: a non-canonical key (e.g. `fullName` instead of `name`) validates
294
+ * structurally but has no destination column, so the store silently writes an
295
+ * empty value. `validateEntitiesConfig` flags those.
296
+ *
297
+ * This is the single source of truth — the Drizzle store imports it, so the
298
+ * two can't drift (the drift is what made the silent-data-loss trap possible).
299
+ * Concepts absent here aren't materialized yet, so their field keys are
300
+ * unconstrained.
301
+ */
302
+ const CANONICAL_FIELDS = {
303
+ contact: [
304
+ "name",
305
+ "email",
306
+ "title",
307
+ "status"
308
+ ],
309
+ company: [
310
+ "name",
311
+ "domain",
312
+ "industry",
313
+ "size"
314
+ ],
315
+ deal: [
316
+ "name",
317
+ "value",
318
+ "stage"
319
+ ]
320
+ };
321
+ /**
322
+ * The concepts the mapping→sync pipeline can actually materialize into `crm_*`
323
+ * tables. These are exactly the CANONICAL_FIELDS keys — the Drizzle sync store's
324
+ * `persist()` throws for any other concept, so offering one (in the mapping
325
+ * editor, in suggestions, or via the upsert API) is a broken affordance.
326
+ *
327
+ * The broader CRM_CONCEPTS set still validates structurally, so previously
328
+ * stored rows for not-yet-materialized concepts keep rendering. When a concept
329
+ * gains a sync-store path, add its canonical fields above and it joins this set
330
+ * automatically (guarded by the MATERIALIZING_CONCEPTS drift test).
331
+ */
332
+ const MATERIALIZING_CONCEPTS = [
333
+ "contact",
334
+ "company",
335
+ "deal"
336
+ ];
337
+ /**
338
+ * The org-defined custom-object target. Deliberately NOT a member of
339
+ * CRM_CONCEPTS / CANONICAL_FIELDS / MATERIALIZING_CONCEPTS — a custom object has
340
+ * no fixed canonical columns; its mapping's fieldMap keys ARE its properties.
341
+ * Handled as an explicit branch wherever concepts are switched on, so the
342
+ * canonical-concept invariants (and their drift test) stay intact.
343
+ */
344
+ const CUSTOM_CONCEPT = "custom";
345
+ /**
346
+ * Operator forms for a single column predicate. All predicates on an entity are
347
+ * AND-ed together. `$raw` (see FilterExpr) is the escape hatch for anything the
348
+ * operators can't express.
349
+ */
350
+ const filterOperatorsSchema = zod.z.union([
351
+ zod.z.strictObject({ eq: zod.z.union([
352
+ zod.z.string(),
353
+ zod.z.number(),
354
+ zod.z.boolean()
355
+ ]) }),
356
+ zod.z.strictObject({ ne: zod.z.union([
357
+ zod.z.string(),
358
+ zod.z.number(),
359
+ zod.z.boolean()
360
+ ]) }),
361
+ zod.z.strictObject({ in: zod.z.array(zod.z.union([
362
+ zod.z.string(),
363
+ zod.z.number(),
364
+ zod.z.boolean()
365
+ ])).min(1) }),
366
+ zod.z.strictObject({ notIn: zod.z.array(zod.z.union([
367
+ zod.z.string(),
368
+ zod.z.number(),
369
+ zod.z.boolean()
370
+ ])).min(1) }),
371
+ zod.z.strictObject({ isNull: zod.z.literal(true) }),
372
+ zod.z.strictObject({ isNotNull: zod.z.literal(true) })
373
+ ]);
374
+ const filterValueSchema = zod.z.union([
375
+ zod.z.string(),
376
+ zod.z.number(),
377
+ zod.z.boolean(),
378
+ filterOperatorsSchema
379
+ ]);
380
+ /**
381
+ * A raw SQL predicate fragment. Kept as a *string* (not a query-builder callback)
382
+ * so the whole config stays JSON-serializable — it can be persisted into
383
+ * `crm_entity_mappings` and shipped to the cloud unchanged. Embedded-only in
384
+ * practice; not validated against the schema.
385
+ */
386
+ const rawFilterSchema = zod.z.strictObject({ $raw: zod.z.string().min(1) });
387
+ const columnFilterSchema = zod.z.record(zod.z.string(), filterValueSchema);
388
+ /** `$raw` is a reserved key; a column literally named `$raw` is not addressable. */
389
+ const filterSchema = zod.z.union([rawFilterSchema, columnFilterSchema]);
390
+ /**
391
+ * How the link between two entities is expressed in the host schema:
392
+ * - `fkOn: "company"` — FK lives on the company table (e.g. organizations.owner_id)
393
+ * - `fkOn: "contact"` — FK lives on the contact table (e.g. users.organization_id)
394
+ * - `through` — a join table sits between them (many-to-many, role often here)
395
+ * - `$raw` — opaque SQL join fragment (escape hatch; not schema-validated)
396
+ *
397
+ * `column` and the join-table keys are `table.column` or bare `column` strings.
398
+ */
399
+ const relationshipViaSchema = zod.z.union([
400
+ zod.z.strictObject({
401
+ fkOn: zod.z.enum(["company", "contact"]),
402
+ column: zod.z.string().min(1)
403
+ }),
404
+ zod.z.strictObject({
405
+ through: zod.z.string().min(1),
406
+ localKey: zod.z.string().min(1),
407
+ foreignKey: zod.z.string().min(1)
408
+ }),
409
+ zod.z.strictObject({ $raw: zod.z.string().min(1) })
410
+ ]);
411
+ const relationshipSchema = zod.z.strictObject({
412
+ /** Key of the related entity in the `entities` map. */
413
+ entity: zod.z.string().min(1),
414
+ via: relationshipViaSchema
415
+ });
416
+ /** A named map of relationships, as stored on an entity / in the mappings row. */
417
+ const relationshipsSchema = zod.z.record(zod.z.string(), relationshipSchema);
418
+ const entitySchema = zod.z.strictObject({
419
+ /** Which CRM concept this entity maps onto — a canonical concept or "custom". */
420
+ concept: zod.z.union([zod.z.enum(CRM_CONCEPTS), zod.z.literal(CUSTOM_CONCEPT)]),
421
+ /** Host table (or view) this entity is derived from. */
422
+ source: zod.z.string().min(1),
423
+ /**
424
+ * Distinguishes multiple entities backed by the same table (e.g. "primary"
425
+ * for owners, "secondary" for members). Free text; defaults to "primary".
426
+ */
427
+ role: zod.z.string().min(1).optional(),
428
+ /** Predicate that narrows `source` into this entity's rows. Omit = whole table. */
429
+ filter: filterSchema.optional(),
430
+ /** clivlyField → sourceColumn. At least one field is required. */
431
+ fields: zod.z.record(zod.z.string(), zod.z.string()).refine((f) => Object.keys(f).length > 0, { message: "at least one field must be mapped" }),
432
+ /**
433
+ * Host-owned identity fields. Sync overwrites them; the CRM UI cannot edit
434
+ * them. Must be a subset of `fields` keys.
435
+ */
436
+ readOnly: zod.z.array(zod.z.string()).optional(),
437
+ /** Named relationships to other entities in this config. */
438
+ relationships: zod.z.record(zod.z.string(), relationshipSchema).optional(),
439
+ /**
440
+ * For a "custom" entity, the crm_object_types row this materializes into.
441
+ * Required for custom (enforced at the API layer), unused for standard concepts.
442
+ */
443
+ targetObjectTypeId: zod.z.string().min(1).optional(),
444
+ /**
445
+ * Advanced mapping: derive this entity from a base table plus explicit joins
446
+ * instead of a single source table. Valid only for `concept: "custom"`.
447
+ *
448
+ * When present, `source` still holds `projection.baseTable` and `fields`
449
+ * still holds one entry per binding — both so that every pre-existing reader
450
+ * of this config keeps working — but `projection` is the authored source of
451
+ * truth and the only thing the compiler interprets.
452
+ */
453
+ projection: require_projection.projectionSchema.optional()
454
+ });
455
+ const entitiesConfigSchema = zod.z.strictObject({ entities: zod.z.record(zod.z.string(), entitySchema).refine((e) => Object.keys(e).length > 0, { message: "at least one entity must be defined" }) });
456
+ /** Thrown by `defineClivlyConfig({ strict: true })` on non-canonical field keys. */
457
+ var ClivlyConfigError = class extends Error {
458
+ issues;
459
+ constructor(issues) {
460
+ super(`Clivly config has ${issues.length} non-canonical field mapping(s) that would write empty values at sync time:\n${issues.map((issue) => ` - ${issue.path}: ${issue.message}`).join("\n")}`);
461
+ this.name = "ClivlyConfigError";
462
+ this.issues = issues;
463
+ }
464
+ };
465
+ function nonCanonicalFieldKeys(entity) {
466
+ const canonical = CANONICAL_FIELDS[entity.concept];
467
+ if (!canonical) return [];
468
+ return Object.keys(entity.fields).filter((key) => !canonical.includes(key));
469
+ }
470
+ function nonCanonicalMessage(entity, field) {
471
+ const canonical = CANONICAL_FIELDS[entity.concept] ?? [];
472
+ return `"${field}" is not a canonical ${entity.concept} field (expected one of: ${canonical.join(", ")})`;
473
+ }
474
+ function canonicalFieldIssues(config) {
475
+ const issues = [];
476
+ for (const [key, entity] of Object.entries(config.entities)) for (const field of nonCanonicalFieldKeys(entity)) issues.push({
477
+ path: `entities.${key}.fields.${field}`,
478
+ message: nonCanonicalMessage(entity, field)
479
+ });
480
+ return issues;
481
+ }
482
+ function defaultWarn(message) {
483
+ console.warn(message);
484
+ }
485
+ /**
486
+ * Structural helper for `clivly.config.ts`. Gives full type inference on the
487
+ * literal you pass and eagerly parses it, so shape errors surface at config
488
+ * load rather than at sync time.
489
+ *
490
+ * It also catches the silent-data-loss footgun: a non-canonical field key for a
491
+ * materialised concept (e.g. `fullName` instead of `name` on a `contact`) has no
492
+ * destination column, so the store would write an empty value. By default these
493
+ * are reported via `onWarn` (a `console.warn`); pass `{ strict: true }` to throw
494
+ * a `ClivlyConfigError` instead. Does NOT validate against the host schema — that
495
+ * needs the discovered schema; see `validateEntitiesConfig`.
496
+ */
497
+ /**
498
+ * The `fields` entry a projection binding implies, qualified as `ref.column`.
499
+ * Qualified rather than bare: two bindings can pull the same column name from
500
+ * different tables (`cl.full_name` and `adv.full_name`), which a bare column
501
+ * name cannot tell apart.
502
+ */
503
+ function projectionFields(projection) {
504
+ const fields = {};
505
+ for (const [name, binding] of Object.entries(projection.fieldBindings)) fields[name] = `${binding.from.table}.${binding.from.column}`;
506
+ return fields;
507
+ }
508
+ /**
509
+ * `fields` duplicates `projection.fieldBindings`, and only the bindings are
510
+ * compiled — so a hand-written `fields` that drifts is both silent and
511
+ * invisible. Derive it when omitted, and reject it when it disagrees.
512
+ */
513
+ function normalizeProjectionFields(config) {
514
+ const entities = {};
515
+ for (const [key, entity] of Object.entries(config.entities ?? {})) {
516
+ const projection = entity?.projection;
517
+ if (!projection?.fieldBindings) {
518
+ entities[key] = entity;
519
+ continue;
520
+ }
521
+ const derived = projectionFields(projection);
522
+ const declared = entity.fields;
523
+ if (!declared) {
524
+ entities[key] = {
525
+ ...entity,
526
+ fields: derived
527
+ };
528
+ continue;
529
+ }
530
+ const drifted = [.../* @__PURE__ */ new Set([...Object.keys(derived), ...Object.keys(declared)])].filter((name) => declared[name] !== derived[name]).sort();
531
+ if (drifted.length > 0) {
532
+ const detail = drifted.map((name) => `"${name}": fields has ${declared[name] === void 0 ? "no entry" : `"${declared[name]}"`}, bindings imply ${derived[name] === void 0 ? "no entry" : `"${derived[name]}"`}`).join("; ");
533
+ throw new Error(`Clivly config: entity "${key}" has a \`fields\` map that disagrees with \`projection.fieldBindings\` — ${detail}. Only the bindings are compiled, so the \`fields\` copy would be silently ignored. Omit \`fields\` entirely and it will be derived.`);
534
+ }
535
+ entities[key] = entity;
536
+ }
537
+ return {
538
+ ...config,
539
+ entities
540
+ };
541
+ }
542
+ function defineClivlyConfig(config, options) {
543
+ const parsed = entitiesConfigSchema.parse(normalizeProjectionFields(config));
544
+ const issues = canonicalFieldIssues(parsed);
545
+ if (issues.length > 0) {
546
+ if (options?.strict) throw new ClivlyConfigError(issues);
547
+ const warn = options?.onWarn ?? defaultWarn;
548
+ for (const issue of issues) warn(`⚠ Clivly config: ${issue.message} (${issue.path}) — this field would write an empty value at sync time. Pass { strict: true } to make this throw.`);
549
+ }
550
+ return parsed;
551
+ }
552
+ /** Split a `table.column` / bare `column` ref into its parts. */
553
+ function parseColumnRef(ref) {
554
+ const dot = ref.indexOf(".");
555
+ if (dot === -1) return { column: ref };
556
+ return {
557
+ table: ref.slice(0, dot),
558
+ column: ref.slice(dot + 1)
559
+ };
560
+ }
561
+ /** Shared lookup + error-collection state threaded through the validators. */
562
+ var SchemaValidator = class {
563
+ errors = [];
564
+ columnsByTable = /* @__PURE__ */ new Map();
565
+ constructor(schema) {
566
+ for (const table of schema) this.columnsByTable.set(table.name, new Set(table.columns));
567
+ }
568
+ tableExists(name) {
569
+ return this.columnsByTable.has(name);
570
+ }
571
+ columnExists(table, column) {
572
+ return this.columnsByTable.get(table)?.has(column) ?? false;
573
+ }
574
+ report(path, message) {
575
+ this.errors.push({
576
+ path,
577
+ message
578
+ });
579
+ }
580
+ /** Report if `column` is absent from `table`. Returns whether it existed. */
581
+ requireColumn(path, table, column) {
582
+ if (this.columnExists(table, column)) return true;
583
+ this.report(path, `column "${column}" does not exist on "${table}"`);
584
+ return false;
585
+ }
586
+ };
587
+ function validateFields(v, base, entity) {
588
+ for (const [field, column] of Object.entries(entity.fields)) v.requireColumn(`${base}.fields.${field}`, entity.source, column);
589
+ for (const field of nonCanonicalFieldKeys(entity)) v.report(`${base}.fields.${field}`, nonCanonicalMessage(entity, field));
590
+ }
591
+ function validateReadOnly(v, base, entity) {
592
+ for (const field of entity.readOnly ?? []) if (!(field in entity.fields)) v.report(`${base}.readOnly`, `"${field}" is not one of this entity's fields`);
593
+ }
594
+ function validateFilter(v, base, entity) {
595
+ if (!entity.filter || "$raw" in entity.filter) return;
596
+ for (const column of Object.keys(entity.filter)) v.requireColumn(`${base}.filter.${column}`, entity.source, column);
597
+ }
598
+ function validateFkVia(v, relBase, via, entity, related) {
599
+ const { table, column } = parseColumnRef(via.column);
600
+ const fkTable = table ?? (via.fkOn === "contact" ? entity.source : related?.source);
601
+ const path = `${relBase}.via.column`;
602
+ if (!fkTable) {
603
+ v.report(path, `cannot resolve table for FK column "${via.column}"`);
604
+ return;
605
+ }
606
+ if (!v.tableExists(fkTable)) {
607
+ v.report(path, `table "${fkTable}" is not in the discovered schema`);
608
+ return;
609
+ }
610
+ v.requireColumn(path, fkTable, column);
611
+ }
612
+ function validateThroughVia(v, relBase, via) {
613
+ if (!v.tableExists(via.through)) {
614
+ v.report(`${relBase}.via.through`, `join table "${via.through}" is not in the discovered schema`);
615
+ return;
616
+ }
617
+ v.requireColumn(`${relBase}.via.localKey`, via.through, via.localKey);
618
+ v.requireColumn(`${relBase}.via.foreignKey`, via.through, via.foreignKey);
619
+ }
620
+ function validateRelationship(v, base, config, entity, relName, rel) {
621
+ const relBase = `${base}.relationships.${relName}`;
622
+ const related = config.entities[rel.entity];
623
+ if (!related) v.report(`${relBase}.entity`, `"${rel.entity}" is not a defined entity`);
624
+ const { via } = rel;
625
+ if ("fkOn" in via) validateFkVia(v, relBase, via, entity, related);
626
+ else if ("through" in via) validateThroughVia(v, relBase, via);
627
+ }
628
+ function validateEntity(v, config, key, entity, schema) {
629
+ const base = `entities.${key}`;
630
+ if (!v.tableExists(entity.source)) {
631
+ v.report(`${base}.source`, `table "${entity.source}" is not in the discovered schema`);
632
+ return;
633
+ }
634
+ if (entity.projection) {
635
+ if (entity.concept !== "custom") v.report(`${base}.projection`, `projection mappings are only supported for concept "${CUSTOM_CONCEPT}"`);
636
+ if (!entity.targetObjectTypeId) v.report(`${base}.targetObjectTypeId`, "a projection mapping must target a custom object type");
637
+ if (entity.source !== entity.projection.baseTable) v.report(`${base}.source`, `"source" ("${entity.source}") must match "projection.baseTable" ("${entity.projection.baseTable}") — the view compiler reads baseTable and the sync engine reads source, so a mismatch makes them disagree about which table this entity is`);
638
+ for (const error of validateProjection(entity.projection, schema, base)) v.report(error.path, error.message);
639
+ validateReadOnly(v, base, entity);
640
+ validateFilter(v, base, entity);
641
+ return;
642
+ }
643
+ validateFields(v, base, entity);
644
+ validateReadOnly(v, base, entity);
645
+ validateFilter(v, base, entity);
646
+ for (const [relName, rel] of Object.entries(entity.relationships ?? {})) validateRelationship(v, base, config, entity, relName, rel);
647
+ }
648
+ /**
649
+ * Validate a (structurally valid) config against the host's discovered schema:
650
+ * source tables exist, mapped columns exist, `readOnly` ⊆ `fields`, filter
651
+ * columns exist, and relationships point at real entities/tables/columns.
652
+ *
653
+ * `$raw` filters and `$raw` relationship joins are opaque and skipped. Returns
654
+ * every error found (not just the first) so a mapping UI or CLI can show them
655
+ * all at once.
656
+ */
657
+ function validateEntitiesConfig(config, schema) {
658
+ const validator = new SchemaValidator(schema);
659
+ for (const [key, entity] of Object.entries(config.entities)) validateEntity(validator, config, key, entity, schema);
660
+ return {
661
+ valid: validator.errors.length === 0,
662
+ errors: validator.errors
663
+ };
664
+ }
665
+ //#endregion
666
+ Object.defineProperty(exports, "CANONICAL_FIELDS", {
667
+ enumerable: true,
668
+ get: function() {
669
+ return CANONICAL_FIELDS;
670
+ }
671
+ });
672
+ Object.defineProperty(exports, "CRM_CONCEPTS", {
673
+ enumerable: true,
674
+ get: function() {
675
+ return CRM_CONCEPTS;
676
+ }
677
+ });
678
+ Object.defineProperty(exports, "CUSTOM_CONCEPT", {
679
+ enumerable: true,
680
+ get: function() {
681
+ return CUSTOM_CONCEPT;
682
+ }
683
+ });
684
+ Object.defineProperty(exports, "ClivlyConfigError", {
685
+ enumerable: true,
686
+ get: function() {
687
+ return ClivlyConfigError;
688
+ }
689
+ });
690
+ Object.defineProperty(exports, "MATERIALIZING_CONCEPTS", {
691
+ enumerable: true,
692
+ get: function() {
693
+ return MATERIALIZING_CONCEPTS;
694
+ }
695
+ });
696
+ Object.defineProperty(exports, "columnMetaFor", {
697
+ enumerable: true,
698
+ get: function() {
699
+ return columnMetaFor;
700
+ }
701
+ });
702
+ Object.defineProperty(exports, "coversUniqueKey", {
703
+ enumerable: true,
704
+ get: function() {
705
+ return coversUniqueKey;
706
+ }
707
+ });
708
+ Object.defineProperty(exports, "defineClivlyConfig", {
709
+ enumerable: true,
710
+ get: function() {
711
+ return defineClivlyConfig;
712
+ }
713
+ });
714
+ Object.defineProperty(exports, "entitiesConfigSchema", {
715
+ enumerable: true,
716
+ get: function() {
717
+ return entitiesConfigSchema;
718
+ }
719
+ });
720
+ Object.defineProperty(exports, "fanOutJoins", {
721
+ enumerable: true,
722
+ get: function() {
723
+ return fanOutJoins;
724
+ }
725
+ });
726
+ Object.defineProperty(exports, "filterSchema", {
727
+ enumerable: true,
728
+ get: function() {
729
+ return filterSchema;
730
+ }
731
+ });
732
+ Object.defineProperty(exports, "hasRichMeta", {
733
+ enumerable: true,
734
+ get: function() {
735
+ return hasRichMeta;
736
+ }
737
+ });
738
+ Object.defineProperty(exports, "joinFansOut", {
739
+ enumerable: true,
740
+ get: function() {
741
+ return joinFansOut;
742
+ }
743
+ });
744
+ Object.defineProperty(exports, "primaryKeyColumns", {
745
+ enumerable: true,
746
+ get: function() {
747
+ return primaryKeyColumns;
748
+ }
749
+ });
750
+ Object.defineProperty(exports, "projectionFields", {
751
+ enumerable: true,
752
+ get: function() {
753
+ return projectionFields;
754
+ }
755
+ });
756
+ Object.defineProperty(exports, "relationshipSchema", {
757
+ enumerable: true,
758
+ get: function() {
759
+ return relationshipSchema;
760
+ }
761
+ });
762
+ Object.defineProperty(exports, "relationshipsSchema", {
763
+ enumerable: true,
764
+ get: function() {
765
+ return relationshipsSchema;
766
+ }
767
+ });
768
+ Object.defineProperty(exports, "validateEntitiesConfig", {
769
+ enumerable: true,
770
+ get: function() {
771
+ return validateEntitiesConfig;
772
+ }
773
+ });
774
+ Object.defineProperty(exports, "validateProjection", {
775
+ enumerable: true,
776
+ get: function() {
777
+ return validateProjection;
778
+ }
779
+ });