@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
@@ -1,295 +1,2 @@
1
- import { z } from "zod";
2
- //#region src/entity-config.d.ts
3
- /**
4
- * Entity Config v2 — the declarative contract that turns Clivly's "schema-aware"
5
- * promise into a real capability.
6
- *
7
- * A CRM entity is no longer a flat table name. It is a *derived entity*: a
8
- * filtered slice of a host table (`source` + `filter`), a column allowlist
9
- * (`fields` + `readOnly`), and declared `relationships` to other entities. The
10
- * same host table can back several entities (e.g. `users` → owners + members)
11
- * distinguished by `role`.
12
- *
13
- * This module is the Phase 1 slice: types, schema, `defineClivlyConfig` (a
14
- * structural helper) and `validateEntitiesConfig` (semantic validation against
15
- * the host's discovered schema). It performs NO DB access and generates no SQL —
16
- * the view compiler (Phase 2) and sync engine (Phase 3) consume this contract.
17
- */
18
- /** Canonical CRM concepts a host entity can map onto. */
19
- declare const CRM_CONCEPTS: readonly ["contact", "company", "deal", "activity", "conversation", "note"];
20
- type CrmConcept = (typeof CRM_CONCEPTS)[number];
21
- /**
22
- * The canonical `fields` keys the mirror actually persists, per concept — the
23
- * crm_* columns the sync store writes. An entity's `fields` map keys must be one
24
- * of these: a non-canonical key (e.g. `fullName` instead of `name`) validates
25
- * structurally but has no destination column, so the store silently writes an
26
- * empty value. `validateEntitiesConfig` flags those.
27
- *
28
- * This is the single source of truth — the Drizzle store imports it, so the
29
- * two can't drift (the drift is what made the silent-data-loss trap possible).
30
- * Concepts absent here aren't materialized yet, so their field keys are
31
- * unconstrained.
32
- */
33
- declare const CANONICAL_FIELDS: {
34
- readonly contact: readonly ["name", "email", "title", "status"];
35
- readonly company: readonly ["name", "domain", "industry", "size"];
36
- readonly deal: readonly ["name", "value", "stage"];
37
- };
38
- /**
39
- * The concepts the mapping→sync pipeline can actually materialize into `crm_*`
40
- * tables. These are exactly the CANONICAL_FIELDS keys — the Drizzle sync store's
41
- * `persist()` throws for any other concept, so offering one (in the mapping
42
- * editor, in suggestions, or via the upsert API) is a broken affordance.
43
- *
44
- * The broader CRM_CONCEPTS set still validates structurally, so previously
45
- * stored rows for not-yet-materialized concepts keep rendering. When a concept
46
- * gains a sync-store path, add its canonical fields above and it joins this set
47
- * automatically (guarded by the MATERIALIZING_CONCEPTS drift test).
48
- */
49
- declare const MATERIALIZING_CONCEPTS: readonly ["contact", "company", "deal"];
50
- type MaterializingConcept = (typeof MATERIALIZING_CONCEPTS)[number];
51
- /**
52
- * The org-defined custom-object target. Deliberately NOT a member of
53
- * CRM_CONCEPTS / CANONICAL_FIELDS / MATERIALIZING_CONCEPTS — a custom object has
54
- * no fixed canonical columns; its mapping's fieldMap keys ARE its properties.
55
- * Handled as an explicit branch wherever concepts are switched on, so the
56
- * canonical-concept invariants (and their drift test) stay intact.
57
- */
58
- declare const CUSTOM_CONCEPT: "custom";
59
- declare const filterValueSchema: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodUnion<readonly [z.ZodObject<{
60
- eq: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
61
- }, z.core.$strict>, z.ZodObject<{
62
- ne: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
63
- }, z.core.$strict>, z.ZodObject<{
64
- in: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
65
- }, z.core.$strict>, z.ZodObject<{
66
- notIn: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
67
- }, z.core.$strict>, z.ZodObject<{
68
- isNull: z.ZodLiteral<true>;
69
- }, z.core.$strict>, z.ZodObject<{
70
- isNotNull: z.ZodLiteral<true>;
71
- }, z.core.$strict>]>]>;
72
- /** `$raw` is a reserved key; a column literally named `$raw` is not addressable. */
73
- declare const filterSchema: z.ZodUnion<readonly [z.ZodObject<{
74
- $raw: z.ZodString;
75
- }, z.core.$strict>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodUnion<readonly [z.ZodObject<{
76
- eq: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
77
- }, z.core.$strict>, z.ZodObject<{
78
- ne: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
79
- }, z.core.$strict>, z.ZodObject<{
80
- in: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
81
- }, z.core.$strict>, z.ZodObject<{
82
- notIn: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
83
- }, z.core.$strict>, z.ZodObject<{
84
- isNull: z.ZodLiteral<true>;
85
- }, z.core.$strict>, z.ZodObject<{
86
- isNotNull: z.ZodLiteral<true>;
87
- }, z.core.$strict>]>]>>]>;
88
- type FilterExpr = z.infer<typeof filterSchema>;
89
- /** A single column predicate value (scalar shorthand or operator object). */
90
- type FilterValue = z.infer<typeof filterValueSchema>;
91
- /**
92
- * How the link between two entities is expressed in the host schema:
93
- * - `fkOn: "company"` — FK lives on the company table (e.g. organizations.owner_id)
94
- * - `fkOn: "contact"` — FK lives on the contact table (e.g. users.organization_id)
95
- * - `through` — a join table sits between them (many-to-many, role often here)
96
- * - `$raw` — opaque SQL join fragment (escape hatch; not schema-validated)
97
- *
98
- * `column` and the join-table keys are `table.column` or bare `column` strings.
99
- */
100
- declare const relationshipViaSchema: z.ZodUnion<readonly [z.ZodObject<{
101
- fkOn: z.ZodEnum<{
102
- contact: "contact";
103
- company: "company";
104
- }>;
105
- column: z.ZodString;
106
- }, z.core.$strict>, z.ZodObject<{
107
- through: z.ZodString;
108
- localKey: z.ZodString;
109
- foreignKey: z.ZodString;
110
- }, z.core.$strict>, z.ZodObject<{
111
- $raw: z.ZodString;
112
- }, z.core.$strict>]>;
113
- type RelationshipVia = z.infer<typeof relationshipViaSchema>;
114
- declare const relationshipSchema: z.ZodObject<{
115
- entity: z.ZodString;
116
- via: z.ZodUnion<readonly [z.ZodObject<{
117
- fkOn: z.ZodEnum<{
118
- contact: "contact";
119
- company: "company";
120
- }>;
121
- column: z.ZodString;
122
- }, z.core.$strict>, z.ZodObject<{
123
- through: z.ZodString;
124
- localKey: z.ZodString;
125
- foreignKey: z.ZodString;
126
- }, z.core.$strict>, z.ZodObject<{
127
- $raw: z.ZodString;
128
- }, z.core.$strict>]>;
129
- }, z.core.$strict>;
130
- type RelationshipSpec = z.infer<typeof relationshipSchema>;
131
- /** A named map of relationships, as stored on an entity / in the mappings row. */
132
- declare const relationshipsSchema: z.ZodRecord<z.ZodString, z.ZodObject<{
133
- entity: z.ZodString;
134
- via: z.ZodUnion<readonly [z.ZodObject<{
135
- fkOn: z.ZodEnum<{
136
- contact: "contact";
137
- company: "company";
138
- }>;
139
- column: z.ZodString;
140
- }, z.core.$strict>, z.ZodObject<{
141
- through: z.ZodString;
142
- localKey: z.ZodString;
143
- foreignKey: z.ZodString;
144
- }, z.core.$strict>, z.ZodObject<{
145
- $raw: z.ZodString;
146
- }, z.core.$strict>]>;
147
- }, z.core.$strict>>;
148
- type RelationshipsMap = z.infer<typeof relationshipsSchema>;
149
- declare const entitySchema: z.ZodObject<{
150
- concept: z.ZodUnion<readonly [z.ZodEnum<{
151
- contact: "contact";
152
- company: "company";
153
- deal: "deal";
154
- activity: "activity";
155
- conversation: "conversation";
156
- note: "note";
157
- }>, z.ZodLiteral<"custom">]>;
158
- source: z.ZodString;
159
- role: z.ZodOptional<z.ZodString>;
160
- filter: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
161
- $raw: z.ZodString;
162
- }, z.core.$strict>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodUnion<readonly [z.ZodObject<{
163
- eq: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
164
- }, z.core.$strict>, z.ZodObject<{
165
- ne: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
166
- }, z.core.$strict>, z.ZodObject<{
167
- in: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
168
- }, z.core.$strict>, z.ZodObject<{
169
- notIn: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
170
- }, z.core.$strict>, z.ZodObject<{
171
- isNull: z.ZodLiteral<true>;
172
- }, z.core.$strict>, z.ZodObject<{
173
- isNotNull: z.ZodLiteral<true>;
174
- }, z.core.$strict>]>]>>]>>;
175
- fields: z.ZodRecord<z.ZodString, z.ZodString>;
176
- readOnly: z.ZodOptional<z.ZodArray<z.ZodString>>;
177
- relationships: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
178
- entity: z.ZodString;
179
- via: z.ZodUnion<readonly [z.ZodObject<{
180
- fkOn: z.ZodEnum<{
181
- contact: "contact";
182
- company: "company";
183
- }>;
184
- column: z.ZodString;
185
- }, z.core.$strict>, z.ZodObject<{
186
- through: z.ZodString;
187
- localKey: z.ZodString;
188
- foreignKey: z.ZodString;
189
- }, z.core.$strict>, z.ZodObject<{
190
- $raw: z.ZodString;
191
- }, z.core.$strict>]>;
192
- }, z.core.$strict>>>;
193
- targetObjectTypeId: z.ZodOptional<z.ZodString>;
194
- }, z.core.$strict>;
195
- type ClivlyEntityConfig = z.infer<typeof entitySchema>;
196
- declare const entitiesConfigSchema: z.ZodObject<{
197
- entities: z.ZodRecord<z.ZodString, z.ZodObject<{
198
- concept: z.ZodUnion<readonly [z.ZodEnum<{
199
- contact: "contact";
200
- company: "company";
201
- deal: "deal";
202
- activity: "activity";
203
- conversation: "conversation";
204
- note: "note";
205
- }>, z.ZodLiteral<"custom">]>;
206
- source: z.ZodString;
207
- role: z.ZodOptional<z.ZodString>;
208
- filter: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
209
- $raw: z.ZodString;
210
- }, z.core.$strict>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodUnion<readonly [z.ZodObject<{
211
- eq: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
212
- }, z.core.$strict>, z.ZodObject<{
213
- ne: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
214
- }, z.core.$strict>, z.ZodObject<{
215
- in: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
216
- }, z.core.$strict>, z.ZodObject<{
217
- notIn: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
218
- }, z.core.$strict>, z.ZodObject<{
219
- isNull: z.ZodLiteral<true>;
220
- }, z.core.$strict>, z.ZodObject<{
221
- isNotNull: z.ZodLiteral<true>;
222
- }, z.core.$strict>]>]>>]>>;
223
- fields: z.ZodRecord<z.ZodString, z.ZodString>;
224
- readOnly: z.ZodOptional<z.ZodArray<z.ZodString>>;
225
- relationships: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
226
- entity: z.ZodString;
227
- via: z.ZodUnion<readonly [z.ZodObject<{
228
- fkOn: z.ZodEnum<{
229
- contact: "contact";
230
- company: "company";
231
- }>;
232
- column: z.ZodString;
233
- }, z.core.$strict>, z.ZodObject<{
234
- through: z.ZodString;
235
- localKey: z.ZodString;
236
- foreignKey: z.ZodString;
237
- }, z.core.$strict>, z.ZodObject<{
238
- $raw: z.ZodString;
239
- }, z.core.$strict>]>;
240
- }, z.core.$strict>>>;
241
- targetObjectTypeId: z.ZodOptional<z.ZodString>;
242
- }, z.core.$strict>>;
243
- }, z.core.$strict>;
244
- type ClivlyEntitiesConfig = z.infer<typeof entitiesConfigSchema>;
245
- /** Thrown by `defineClivlyConfig({ strict: true })` on non-canonical field keys. */
246
- declare class ClivlyConfigError extends Error {
247
- readonly issues: ConfigValidationError[];
248
- constructor(issues: ConfigValidationError[]);
249
- }
250
- /**
251
- * Structural helper for `clivly.config.ts`. Gives full type inference on the
252
- * literal you pass and eagerly parses it, so shape errors surface at config
253
- * load rather than at sync time.
254
- *
255
- * It also catches the silent-data-loss footgun: a non-canonical field key for a
256
- * materialised concept (e.g. `fullName` instead of `name` on a `contact`) has no
257
- * destination column, so the store would write an empty value. By default these
258
- * are reported via `onWarn` (a `console.warn`); pass `{ strict: true }` to throw
259
- * a `ClivlyConfigError` instead. Does NOT validate against the host schema — that
260
- * needs the discovered schema; see `validateEntitiesConfig`.
261
- */
262
- declare function defineClivlyConfig(config: ClivlyEntitiesConfig, options?: {
263
- strict?: boolean;
264
- onWarn?: (message: string) => void;
265
- }): ClivlyEntitiesConfig;
266
- /**
267
- * A host table the SDK reported for discovery. Structurally identical to the
268
- * SDK's `DiscoveredTable`; duplicated here to keep `@clivly/core` free of an
269
- * SDK dependency (core is the base contract SDK builds on).
270
- */
271
- interface DiscoveredSchemaTable {
272
- columns: string[];
273
- name: string;
274
- }
275
- interface ConfigValidationError {
276
- message: string;
277
- /** Dotted path into the config, e.g. `entities.owner.fields.email`. */
278
- path: string;
279
- }
280
- interface ConfigValidationResult {
281
- errors: ConfigValidationError[];
282
- valid: boolean;
283
- }
284
- /**
285
- * Validate a (structurally valid) config against the host's discovered schema:
286
- * source tables exist, mapped columns exist, `readOnly` ⊆ `fields`, filter
287
- * columns exist, and relationships point at real entities/tables/columns.
288
- *
289
- * `$raw` filters and `$raw` relationship joins are opaque and skipped. Returns
290
- * every error found (not just the first) so a mapping UI or CLI can show them
291
- * all at once.
292
- */
293
- declare function validateEntitiesConfig(config: ClivlyEntitiesConfig, schema: DiscoveredSchemaTable[]): ConfigValidationResult;
294
- //#endregion
295
- export { CANONICAL_FIELDS, CRM_CONCEPTS, CUSTOM_CONCEPT, ClivlyConfigError, ClivlyEntitiesConfig, ClivlyEntityConfig, ConfigValidationError, ConfigValidationResult, CrmConcept, DiscoveredSchemaTable, FilterExpr, FilterValue, MATERIALIZING_CONCEPTS, MaterializingConcept, RelationshipSpec, RelationshipVia, RelationshipsMap, defineClivlyConfig, entitiesConfigSchema, filterSchema, relationshipSchema, relationshipsSchema, validateEntitiesConfig };
1
+ import { C as filterSchema, D as validateEntitiesConfig, E as relationshipsSchema, S as entitiesConfigSchema, T as relationshipSchema, _ as MaterializingConcept, a as ClivlyEntitiesConfig, b as RelationshipsMap, c as ClivlyEntityConfigInput, d as CrmConcept, f as DiscoveredColumnMeta, g as MATERIALIZING_CONCEPTS, h as FilterValue, i as ClivlyConfigError, l as ConfigValidationError, m as FilterExpr, n as CRM_CONCEPTS, o as ClivlyEntitiesConfigInput, p as DiscoveredSchemaTable, r as CUSTOM_CONCEPT, s as ClivlyEntityConfig, t as CANONICAL_FIELDS, u as ConfigValidationResult, v as RelationshipSpec, w as projectionFields, x as defineClivlyConfig, y as RelationshipVia } from "./entity-config-CLxI8dVb.mjs";
2
+ export { CANONICAL_FIELDS, CRM_CONCEPTS, CUSTOM_CONCEPT, ClivlyConfigError, ClivlyEntitiesConfig, ClivlyEntitiesConfigInput, ClivlyEntityConfig, ClivlyEntityConfigInput, ConfigValidationError, ConfigValidationResult, CrmConcept, DiscoveredColumnMeta, DiscoveredSchemaTable, FilterExpr, FilterValue, MATERIALIZING_CONCEPTS, MaterializingConcept, RelationshipSpec, RelationshipVia, RelationshipsMap, defineClivlyConfig, entitiesConfigSchema, filterSchema, projectionFields, relationshipSchema, relationshipsSchema, validateEntitiesConfig };
@@ -1,339 +1,2 @@
1
- import { z } from "zod";
2
- //#region src/entity-config.ts
3
- /**
4
- * Entity Config v2 — the declarative contract that turns Clivly's "schema-aware"
5
- * promise into a real capability.
6
- *
7
- * A CRM entity is no longer a flat table name. It is a *derived entity*: a
8
- * filtered slice of a host table (`source` + `filter`), a column allowlist
9
- * (`fields` + `readOnly`), and declared `relationships` to other entities. The
10
- * same host table can back several entities (e.g. `users` → owners + members)
11
- * distinguished by `role`.
12
- *
13
- * This module is the Phase 1 slice: types, schema, `defineClivlyConfig` (a
14
- * structural helper) and `validateEntitiesConfig` (semantic validation against
15
- * the host's discovered schema). It performs NO DB access and generates no SQL —
16
- * the view compiler (Phase 2) and sync engine (Phase 3) consume this contract.
17
- */
18
- /** Canonical CRM concepts a host entity can map onto. */
19
- const CRM_CONCEPTS = [
20
- "contact",
21
- "company",
22
- "deal",
23
- "activity",
24
- "conversation",
25
- "note"
26
- ];
27
- /**
28
- * The canonical `fields` keys the mirror actually persists, per concept — the
29
- * crm_* columns the sync store writes. An entity's `fields` map keys must be one
30
- * of these: a non-canonical key (e.g. `fullName` instead of `name`) validates
31
- * structurally but has no destination column, so the store silently writes an
32
- * empty value. `validateEntitiesConfig` flags those.
33
- *
34
- * This is the single source of truth — the Drizzle store imports it, so the
35
- * two can't drift (the drift is what made the silent-data-loss trap possible).
36
- * Concepts absent here aren't materialized yet, so their field keys are
37
- * unconstrained.
38
- */
39
- const CANONICAL_FIELDS = {
40
- contact: [
41
- "name",
42
- "email",
43
- "title",
44
- "status"
45
- ],
46
- company: [
47
- "name",
48
- "domain",
49
- "industry",
50
- "size"
51
- ],
52
- deal: [
53
- "name",
54
- "value",
55
- "stage"
56
- ]
57
- };
58
- /**
59
- * The concepts the mapping→sync pipeline can actually materialize into `crm_*`
60
- * tables. These are exactly the CANONICAL_FIELDS keys — the Drizzle sync store's
61
- * `persist()` throws for any other concept, so offering one (in the mapping
62
- * editor, in suggestions, or via the upsert API) is a broken affordance.
63
- *
64
- * The broader CRM_CONCEPTS set still validates structurally, so previously
65
- * stored rows for not-yet-materialized concepts keep rendering. When a concept
66
- * gains a sync-store path, add its canonical fields above and it joins this set
67
- * automatically (guarded by the MATERIALIZING_CONCEPTS drift test).
68
- */
69
- const MATERIALIZING_CONCEPTS = [
70
- "contact",
71
- "company",
72
- "deal"
73
- ];
74
- /**
75
- * The org-defined custom-object target. Deliberately NOT a member of
76
- * CRM_CONCEPTS / CANONICAL_FIELDS / MATERIALIZING_CONCEPTS — a custom object has
77
- * no fixed canonical columns; its mapping's fieldMap keys ARE its properties.
78
- * Handled as an explicit branch wherever concepts are switched on, so the
79
- * canonical-concept invariants (and their drift test) stay intact.
80
- */
81
- const CUSTOM_CONCEPT = "custom";
82
- /**
83
- * Operator forms for a single column predicate. All predicates on an entity are
84
- * AND-ed together. `$raw` (see FilterExpr) is the escape hatch for anything the
85
- * operators can't express.
86
- */
87
- const filterOperatorsSchema = z.union([
88
- z.strictObject({ eq: z.union([
89
- z.string(),
90
- z.number(),
91
- z.boolean()
92
- ]) }),
93
- z.strictObject({ ne: z.union([
94
- z.string(),
95
- z.number(),
96
- z.boolean()
97
- ]) }),
98
- z.strictObject({ in: z.array(z.union([
99
- z.string(),
100
- z.number(),
101
- z.boolean()
102
- ])).min(1) }),
103
- z.strictObject({ notIn: z.array(z.union([
104
- z.string(),
105
- z.number(),
106
- z.boolean()
107
- ])).min(1) }),
108
- z.strictObject({ isNull: z.literal(true) }),
109
- z.strictObject({ isNotNull: z.literal(true) })
110
- ]);
111
- const filterValueSchema = z.union([
112
- z.string(),
113
- z.number(),
114
- z.boolean(),
115
- filterOperatorsSchema
116
- ]);
117
- /**
118
- * A raw SQL predicate fragment. Kept as a *string* (not a query-builder callback)
119
- * so the whole config stays JSON-serializable — it can be persisted into
120
- * `crm_entity_mappings` and shipped to the cloud unchanged. Embedded-only in
121
- * practice; not validated against the schema.
122
- */
123
- const rawFilterSchema = z.strictObject({ $raw: z.string().min(1) });
124
- const columnFilterSchema = z.record(z.string(), filterValueSchema);
125
- /** `$raw` is a reserved key; a column literally named `$raw` is not addressable. */
126
- const filterSchema = z.union([rawFilterSchema, columnFilterSchema]);
127
- /**
128
- * How the link between two entities is expressed in the host schema:
129
- * - `fkOn: "company"` — FK lives on the company table (e.g. organizations.owner_id)
130
- * - `fkOn: "contact"` — FK lives on the contact table (e.g. users.organization_id)
131
- * - `through` — a join table sits between them (many-to-many, role often here)
132
- * - `$raw` — opaque SQL join fragment (escape hatch; not schema-validated)
133
- *
134
- * `column` and the join-table keys are `table.column` or bare `column` strings.
135
- */
136
- const relationshipViaSchema = z.union([
137
- z.strictObject({
138
- fkOn: z.enum(["company", "contact"]),
139
- column: z.string().min(1)
140
- }),
141
- z.strictObject({
142
- through: z.string().min(1),
143
- localKey: z.string().min(1),
144
- foreignKey: z.string().min(1)
145
- }),
146
- z.strictObject({ $raw: z.string().min(1) })
147
- ]);
148
- const relationshipSchema = z.strictObject({
149
- /** Key of the related entity in the `entities` map. */
150
- entity: z.string().min(1),
151
- via: relationshipViaSchema
152
- });
153
- /** A named map of relationships, as stored on an entity / in the mappings row. */
154
- const relationshipsSchema = z.record(z.string(), relationshipSchema);
155
- const entitySchema = z.strictObject({
156
- /** Which CRM concept this entity maps onto — a canonical concept or "custom". */
157
- concept: z.union([z.enum(CRM_CONCEPTS), z.literal(CUSTOM_CONCEPT)]),
158
- /** Host table (or view) this entity is derived from. */
159
- source: z.string().min(1),
160
- /**
161
- * Distinguishes multiple entities backed by the same table (e.g. "primary"
162
- * for owners, "secondary" for members). Free text; defaults to "primary".
163
- */
164
- role: z.string().min(1).optional(),
165
- /** Predicate that narrows `source` into this entity's rows. Omit = whole table. */
166
- filter: filterSchema.optional(),
167
- /** clivlyField → sourceColumn. At least one field is required. */
168
- fields: z.record(z.string(), z.string()).refine((f) => Object.keys(f).length > 0, { message: "at least one field must be mapped" }),
169
- /**
170
- * Host-owned identity fields. Sync overwrites them; the CRM UI cannot edit
171
- * them. Must be a subset of `fields` keys.
172
- */
173
- readOnly: z.array(z.string()).optional(),
174
- /** Named relationships to other entities in this config. */
175
- relationships: z.record(z.string(), relationshipSchema).optional(),
176
- /**
177
- * For a "custom" entity, the crm_object_types row this materializes into.
178
- * Required for custom (enforced at the API layer), unused for standard concepts.
179
- */
180
- targetObjectTypeId: z.string().min(1).optional()
181
- });
182
- const entitiesConfigSchema = z.strictObject({ entities: z.record(z.string(), entitySchema).refine((e) => Object.keys(e).length > 0, { message: "at least one entity must be defined" }) });
183
- /** Thrown by `defineClivlyConfig({ strict: true })` on non-canonical field keys. */
184
- var ClivlyConfigError = class extends Error {
185
- issues;
186
- constructor(issues) {
187
- 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")}`);
188
- this.name = "ClivlyConfigError";
189
- this.issues = issues;
190
- }
191
- };
192
- function nonCanonicalFieldKeys(entity) {
193
- const canonical = CANONICAL_FIELDS[entity.concept];
194
- if (!canonical) return [];
195
- return Object.keys(entity.fields).filter((key) => !canonical.includes(key));
196
- }
197
- function nonCanonicalMessage(entity, field) {
198
- const canonical = CANONICAL_FIELDS[entity.concept] ?? [];
199
- return `"${field}" is not a canonical ${entity.concept} field (expected one of: ${canonical.join(", ")})`;
200
- }
201
- function canonicalFieldIssues(config) {
202
- const issues = [];
203
- for (const [key, entity] of Object.entries(config.entities)) for (const field of nonCanonicalFieldKeys(entity)) issues.push({
204
- path: `entities.${key}.fields.${field}`,
205
- message: nonCanonicalMessage(entity, field)
206
- });
207
- return issues;
208
- }
209
- function defaultWarn(message) {
210
- console.warn(message);
211
- }
212
- /**
213
- * Structural helper for `clivly.config.ts`. Gives full type inference on the
214
- * literal you pass and eagerly parses it, so shape errors surface at config
215
- * load rather than at sync time.
216
- *
217
- * It also catches the silent-data-loss footgun: a non-canonical field key for a
218
- * materialised concept (e.g. `fullName` instead of `name` on a `contact`) has no
219
- * destination column, so the store would write an empty value. By default these
220
- * are reported via `onWarn` (a `console.warn`); pass `{ strict: true }` to throw
221
- * a `ClivlyConfigError` instead. Does NOT validate against the host schema — that
222
- * needs the discovered schema; see `validateEntitiesConfig`.
223
- */
224
- function defineClivlyConfig(config, options) {
225
- const parsed = entitiesConfigSchema.parse(config);
226
- const issues = canonicalFieldIssues(parsed);
227
- if (issues.length > 0) {
228
- if (options?.strict) throw new ClivlyConfigError(issues);
229
- const warn = options?.onWarn ?? defaultWarn;
230
- 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.`);
231
- }
232
- return parsed;
233
- }
234
- /** Split a `table.column` / bare `column` ref into its parts. */
235
- function parseColumnRef(ref) {
236
- const dot = ref.indexOf(".");
237
- if (dot === -1) return { column: ref };
238
- return {
239
- table: ref.slice(0, dot),
240
- column: ref.slice(dot + 1)
241
- };
242
- }
243
- /** Shared lookup + error-collection state threaded through the validators. */
244
- var SchemaValidator = class {
245
- errors = [];
246
- columnsByTable = /* @__PURE__ */ new Map();
247
- constructor(schema) {
248
- for (const table of schema) this.columnsByTable.set(table.name, new Set(table.columns));
249
- }
250
- tableExists(name) {
251
- return this.columnsByTable.has(name);
252
- }
253
- columnExists(table, column) {
254
- return this.columnsByTable.get(table)?.has(column) ?? false;
255
- }
256
- report(path, message) {
257
- this.errors.push({
258
- path,
259
- message
260
- });
261
- }
262
- /** Report if `column` is absent from `table`. Returns whether it existed. */
263
- requireColumn(path, table, column) {
264
- if (this.columnExists(table, column)) return true;
265
- this.report(path, `column "${column}" does not exist on "${table}"`);
266
- return false;
267
- }
268
- };
269
- function validateFields(v, base, entity) {
270
- for (const [field, column] of Object.entries(entity.fields)) v.requireColumn(`${base}.fields.${field}`, entity.source, column);
271
- for (const field of nonCanonicalFieldKeys(entity)) v.report(`${base}.fields.${field}`, nonCanonicalMessage(entity, field));
272
- }
273
- function validateReadOnly(v, base, entity) {
274
- for (const field of entity.readOnly ?? []) if (!(field in entity.fields)) v.report(`${base}.readOnly`, `"${field}" is not one of this entity's fields`);
275
- }
276
- function validateFilter(v, base, entity) {
277
- if (!entity.filter || "$raw" in entity.filter) return;
278
- for (const column of Object.keys(entity.filter)) v.requireColumn(`${base}.filter.${column}`, entity.source, column);
279
- }
280
- function validateFkVia(v, relBase, via, entity, related) {
281
- const { table, column } = parseColumnRef(via.column);
282
- const fkTable = table ?? (via.fkOn === "contact" ? entity.source : related?.source);
283
- const path = `${relBase}.via.column`;
284
- if (!fkTable) {
285
- v.report(path, `cannot resolve table for FK column "${via.column}"`);
286
- return;
287
- }
288
- if (!v.tableExists(fkTable)) {
289
- v.report(path, `table "${fkTable}" is not in the discovered schema`);
290
- return;
291
- }
292
- v.requireColumn(path, fkTable, column);
293
- }
294
- function validateThroughVia(v, relBase, via) {
295
- if (!v.tableExists(via.through)) {
296
- v.report(`${relBase}.via.through`, `join table "${via.through}" is not in the discovered schema`);
297
- return;
298
- }
299
- v.requireColumn(`${relBase}.via.localKey`, via.through, via.localKey);
300
- v.requireColumn(`${relBase}.via.foreignKey`, via.through, via.foreignKey);
301
- }
302
- function validateRelationship(v, base, config, entity, relName, rel) {
303
- const relBase = `${base}.relationships.${relName}`;
304
- const related = config.entities[rel.entity];
305
- if (!related) v.report(`${relBase}.entity`, `"${rel.entity}" is not a defined entity`);
306
- const { via } = rel;
307
- if ("fkOn" in via) validateFkVia(v, relBase, via, entity, related);
308
- else if ("through" in via) validateThroughVia(v, relBase, via);
309
- }
310
- function validateEntity(v, config, key, entity) {
311
- const base = `entities.${key}`;
312
- if (!v.tableExists(entity.source)) {
313
- v.report(`${base}.source`, `table "${entity.source}" is not in the discovered schema`);
314
- return;
315
- }
316
- validateFields(v, base, entity);
317
- validateReadOnly(v, base, entity);
318
- validateFilter(v, base, entity);
319
- for (const [relName, rel] of Object.entries(entity.relationships ?? {})) validateRelationship(v, base, config, entity, relName, rel);
320
- }
321
- /**
322
- * Validate a (structurally valid) config against the host's discovered schema:
323
- * source tables exist, mapped columns exist, `readOnly` ⊆ `fields`, filter
324
- * columns exist, and relationships point at real entities/tables/columns.
325
- *
326
- * `$raw` filters and `$raw` relationship joins are opaque and skipped. Returns
327
- * every error found (not just the first) so a mapping UI or CLI can show them
328
- * all at once.
329
- */
330
- function validateEntitiesConfig(config, schema) {
331
- const validator = new SchemaValidator(schema);
332
- for (const [key, entity] of Object.entries(config.entities)) validateEntity(validator, config, key, entity);
333
- return {
334
- valid: validator.errors.length === 0,
335
- errors: validator.errors
336
- };
337
- }
338
- //#endregion
339
- export { CANONICAL_FIELDS, CRM_CONCEPTS, CUSTOM_CONCEPT, ClivlyConfigError, MATERIALIZING_CONCEPTS, defineClivlyConfig, entitiesConfigSchema, filterSchema, relationshipSchema, relationshipsSchema, validateEntitiesConfig };
1
+ import { a as MATERIALIZING_CONCEPTS, c as filterSchema, d as relationshipsSchema, f as validateEntitiesConfig, i as ClivlyConfigError, l as projectionFields, n as CRM_CONCEPTS, o as defineClivlyConfig, r as CUSTOM_CONCEPT, s as entitiesConfigSchema, t as CANONICAL_FIELDS, u as relationshipSchema } from "./entity-config-8Fgr6IOH.mjs";
2
+ export { CANONICAL_FIELDS, CRM_CONCEPTS, CUSTOM_CONCEPT, ClivlyConfigError, MATERIALIZING_CONCEPTS, defineClivlyConfig, entitiesConfigSchema, filterSchema, projectionFields, relationshipSchema, relationshipsSchema, validateEntitiesConfig };