@clivly/core 0.7.4 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
1
+ import { a as MATERIALIZING_CONCEPTS, c as filterSchema, d as validateEntitiesConfig, i as ClivlyConfigError, l as relationshipSchema, n as CRM_CONCEPTS, o as defineClivlyConfig, r as CUSTOM_CONCEPT, s as entitiesConfigSchema, t as CANONICAL_FIELDS, u as relationshipsSchema } from "./entity-config-Tb5bbKLj.mjs";
339
2
  export { CANONICAL_FIELDS, CRM_CONCEPTS, CUSTOM_CONCEPT, ClivlyConfigError, MATERIALIZING_CONCEPTS, defineClivlyConfig, entitiesConfigSchema, filterSchema, relationshipSchema, relationshipsSchema, validateEntitiesConfig };
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_entity_config = require("./entity-config.cjs");
2
+ const require_entity_config = require("./entity-config-PoOGzvpN.cjs");
3
3
  const require_mapping_score = require("./mapping-score.cjs");
4
4
  //#region src/entity-heuristics.ts
5
5
  const TARGET_CONCEPTS = [
@@ -1,3 +1,4 @@
1
+ import { DiscoveredColumnMeta } from "./entity-config.cjs";
1
2
  import { Scored } from "./mapping-score.cjs";
2
3
  //#region src/entity-heuristics.d.ts
3
4
  declare const TARGET_CONCEPTS: readonly ["contact", "company", "deal", "activity", "conversation", "note"];
@@ -6,17 +7,6 @@ declare function suggestCursorField(columnKeys: string[]): string | null;
6
7
  declare function matchesConcept(tableName: string, concept: TargetConcept): {
7
8
  exact: boolean;
8
9
  } | null;
9
- interface DiscoveredColumnMeta {
10
- isForeignKey?: boolean;
11
- isPrimaryKey?: boolean;
12
- name: string;
13
- nullable?: boolean;
14
- references?: {
15
- table: string;
16
- column: string;
17
- };
18
- type?: string;
19
- }
20
10
  interface ScoredTable {
21
11
  columns: string[];
22
12
  columnsMeta?: DiscoveredColumnMeta[];
@@ -64,4 +54,4 @@ interface FieldSuggestion {
64
54
  declare function scoreFieldMap(concept: TargetConcept, table: ScoredTable): Scored<FieldSuggestion>[];
65
55
  declare function toFieldMap(scored: Scored<FieldSuggestion>[]): Record<string, string>;
66
56
  //#endregion
67
- export { DiscoveredColumnMeta, FieldSuggestion, RelationshipSuggestion, ScoredTable, SuggestedVia, TARGET_CONCEPTS, TargetConcept, matchesConcept, requiredFieldsFor, scoreConcepts, scoreFieldMap, scoreRelationships, suggestCursorField, suggestDiscriminatorColumns, toFieldMap, topConcept, validateMapping };
57
+ export { type DiscoveredColumnMeta, FieldSuggestion, RelationshipSuggestion, ScoredTable, SuggestedVia, TARGET_CONCEPTS, TargetConcept, matchesConcept, requiredFieldsFor, scoreConcepts, scoreFieldMap, scoreRelationships, suggestCursorField, suggestDiscriminatorColumns, toFieldMap, topConcept, validateMapping };
@@ -1,3 +1,4 @@
1
+ import { DiscoveredColumnMeta } from "./entity-config.mjs";
1
2
  import { Scored } from "./mapping-score.mjs";
2
3
  //#region src/entity-heuristics.d.ts
3
4
  declare const TARGET_CONCEPTS: readonly ["contact", "company", "deal", "activity", "conversation", "note"];
@@ -6,17 +7,6 @@ declare function suggestCursorField(columnKeys: string[]): string | null;
6
7
  declare function matchesConcept(tableName: string, concept: TargetConcept): {
7
8
  exact: boolean;
8
9
  } | null;
9
- interface DiscoveredColumnMeta {
10
- isForeignKey?: boolean;
11
- isPrimaryKey?: boolean;
12
- name: string;
13
- nullable?: boolean;
14
- references?: {
15
- table: string;
16
- column: string;
17
- };
18
- type?: string;
19
- }
20
10
  interface ScoredTable {
21
11
  columns: string[];
22
12
  columnsMeta?: DiscoveredColumnMeta[];
@@ -64,4 +54,4 @@ interface FieldSuggestion {
64
54
  declare function scoreFieldMap(concept: TargetConcept, table: ScoredTable): Scored<FieldSuggestion>[];
65
55
  declare function toFieldMap(scored: Scored<FieldSuggestion>[]): Record<string, string>;
66
56
  //#endregion
67
- export { DiscoveredColumnMeta, FieldSuggestion, RelationshipSuggestion, ScoredTable, SuggestedVia, TARGET_CONCEPTS, TargetConcept, matchesConcept, requiredFieldsFor, scoreConcepts, scoreFieldMap, scoreRelationships, suggestCursorField, suggestDiscriminatorColumns, toFieldMap, topConcept, validateMapping };
57
+ export { type DiscoveredColumnMeta, FieldSuggestion, RelationshipSuggestion, ScoredTable, SuggestedVia, TARGET_CONCEPTS, TargetConcept, matchesConcept, requiredFieldsFor, scoreConcepts, scoreFieldMap, scoreRelationships, suggestCursorField, suggestDiscriminatorColumns, toFieldMap, topConcept, validateMapping };
@@ -1,4 +1,4 @@
1
- import { MATERIALIZING_CONCEPTS } from "./entity-config.mjs";
1
+ import { a as MATERIALIZING_CONCEPTS } from "./entity-config-Tb5bbKLj.mjs";
2
2
  import { CONCEPT_TIERS, FIELD_TIERS, RELATIONSHIP_TIERS, W, isAmbiguous, isNumericLike, isTextLike, isTimestampLike, tierFor } from "./mapping-score.mjs";
3
3
  //#region src/entity-heuristics.ts
4
4
  const TARGET_CONCEPTS = [
package/dist/index.cjs CHANGED
@@ -1,10 +1,77 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_auth_adapter = require("./auth-adapter.cjs");
3
- const require_entity_config = require("./entity-config.cjs");
3
+ const require_projection = require("./projection-BXBkh7qp.cjs");
4
+ const require_entity_config = require("./entity-config-PoOGzvpN.cjs");
4
5
  const require_mapping_form = require("./mapping-form.cjs");
5
6
  const require_mappings_config = require("./mappings-config.cjs");
6
- const require_view_compiler = require("./view-compiler.cjs");
7
+ const require_view_compiler = require("./view-compiler-BwZ9UgLp.cjs");
7
8
  const require_sync_engine = require("./sync-engine.cjs");
9
+ //#region src/projection-draft.ts
10
+ function emptyProjectionDraft(baseTable) {
11
+ return {
12
+ baseTable,
13
+ entityKey: "",
14
+ fieldBindings: {},
15
+ identity: { kind: "base_pk" },
16
+ joins: []
17
+ };
18
+ }
19
+ /**
20
+ * The ON conditions implied by a foreign key between the two tables, so the
21
+ * builder can pre-fill a join instead of making the user hand-pick columns.
22
+ * Returns [] when no FK relates them — the user then picks manually.
23
+ */
24
+ function suggestJoinConditions(baseTable, joinTable, schema, joinKey) {
25
+ const join = schema.find((t) => t.name === joinTable);
26
+ const conditions = [];
27
+ for (const column of join?.columnsMeta ?? []) if (column.references?.table === baseTable) conditions.push({
28
+ left: {
29
+ table: joinKey,
30
+ column: column.name
31
+ },
32
+ op: "eq",
33
+ right: {
34
+ table: require_projection.BASE_REF,
35
+ column: column.references.column
36
+ }
37
+ });
38
+ return conditions;
39
+ }
40
+ /** A draft becomes a projection once it has a valid key and ≥1 binding. */
41
+ function draftToProjection(draft) {
42
+ if (!require_projection.PROJECTION_KEY_PATTERN.test(draft.entityKey)) return null;
43
+ if (Object.keys(draft.fieldBindings).length === 0) return null;
44
+ return {
45
+ version: 1,
46
+ kind: "projection",
47
+ entityKey: draft.entityKey,
48
+ baseTable: draft.baseTable,
49
+ joins: draft.joins,
50
+ fieldBindings: draft.fieldBindings,
51
+ identity: draft.identity
52
+ };
53
+ }
54
+ function draftErrors(draft, schema) {
55
+ const projection = draftToProjection(draft);
56
+ if (!projection) return [{
57
+ path: "projection",
58
+ message: "Name the object and map a field."
59
+ }];
60
+ return require_entity_config.validateProjection(projection, schema, "projection");
61
+ }
62
+ /** Per-join fan-out, for the builder's inline cardinality hints. */
63
+ function describeCardinality(draft, schema) {
64
+ const projection = draftToProjection(draft);
65
+ if (!projection) return [];
66
+ const tablesByName = new Map(schema.map((t) => [t.name, t]));
67
+ const fanning = new Set(require_entity_config.fanOutJoins(projection, tablesByName).map((j) => j.key));
68
+ return projection.joins.map((join) => ({
69
+ joinKey: join.key,
70
+ fansOut: fanning.has(join.key)
71
+ }));
72
+ }
73
+ //#endregion
74
+ exports.BASE_REF = require_projection.BASE_REF;
8
75
  exports.CANONICAL_FIELDS = require_entity_config.CANONICAL_FIELDS;
9
76
  exports.CRM_CONCEPTS = require_entity_config.CRM_CONCEPTS;
10
77
  exports.ClivlyConfigError = require_entity_config.ClivlyConfigError;
@@ -13,16 +80,30 @@ exports.MATERIALIZING_CONCEPTS = require_entity_config.MATERIALIZING_CONCEPTS;
13
80
  exports.authCustom = require_auth_adapter.authCustom;
14
81
  exports.buildFilterFromDiscriminator = require_mapping_form.buildFilterFromDiscriminator;
15
82
  exports.buildRelationships = require_mapping_form.buildRelationships;
83
+ exports.columnMetaFor = require_entity_config.columnMetaFor;
16
84
  exports.compileEntityView = require_view_compiler.compileEntityView;
17
85
  exports.compileEntityViews = require_view_compiler.compileEntityViews;
86
+ exports.coversUniqueKey = require_entity_config.coversUniqueKey;
18
87
  exports.defineClivlyConfig = require_entity_config.defineClivlyConfig;
88
+ exports.describeCardinality = describeCardinality;
89
+ exports.draftErrors = draftErrors;
90
+ exports.draftToProjection = draftToProjection;
91
+ exports.emptyProjectionDraft = emptyProjectionDraft;
19
92
  exports.entitiesConfigSchema = require_entity_config.entitiesConfigSchema;
20
93
  exports.explainEntitiesConfig = require_view_compiler.explainEntitiesConfig;
94
+ exports.fanOutJoins = require_entity_config.fanOutJoins;
21
95
  exports.filterSchema = require_entity_config.filterSchema;
96
+ exports.hasRichMeta = require_entity_config.hasRichMeta;
97
+ exports.identityRefs = require_projection.identityRefs;
98
+ exports.joinFansOut = require_entity_config.joinFansOut;
22
99
  exports.mappingsToEntitiesConfig = require_mappings_config.mappingsToEntitiesConfig;
100
+ exports.primaryKeyColumns = require_entity_config.primaryKeyColumns;
101
+ exports.projectionSchema = require_projection.projectionSchema;
23
102
  exports.reconcile = require_sync_engine.reconcile;
24
103
  exports.relationshipSchema = require_entity_config.relationshipSchema;
25
104
  exports.relationshipViaSignature = require_mapping_form.relationshipViaSignature;
26
105
  exports.relationshipsSchema = require_entity_config.relationshipsSchema;
27
106
  exports.runSync = require_sync_engine.runSync;
107
+ exports.suggestJoinConditions = suggestJoinConditions;
28
108
  exports.validateEntitiesConfig = require_entity_config.validateEntitiesConfig;
109
+ exports.validateProjection = require_entity_config.validateProjection;
package/dist/index.d.cts CHANGED
@@ -1,9 +1,79 @@
1
1
  import { Activity, ActivityType, Company, Contact, ContactFilters, ContactStatus, CreateActivityInput, CreateCompanyInput, CreateContactInput, CreateDealInput, CreateTaskInput, CrmRole, Deal, DealStage, Note, RecordSource, Task, TaskEntityType, TaskFilters, TaskPriority, TaskStatus, UpdateContactInput, UpdateDealInput, UpdateTaskInput } from "./types.cjs";
2
2
  import { CRMAdapter } from "./adapter.cjs";
3
3
  import { ClivlyAuthAdapter, ClivlyUser, CrmMembership, MembershipResolver, authCustom } from "./auth-adapter.cjs";
4
- import { CANONICAL_FIELDS, CRM_CONCEPTS, ClivlyConfigError, ClivlyEntitiesConfig, ClivlyEntityConfig, ConfigValidationError, ConfigValidationResult, CrmConcept, DiscoveredSchemaTable, FilterExpr, FilterValue, MATERIALIZING_CONCEPTS, MaterializingConcept, RelationshipSpec, RelationshipVia, RelationshipsMap, defineClivlyConfig, entitiesConfigSchema, filterSchema, relationshipSchema, relationshipsSchema, validateEntitiesConfig } from "./entity-config.cjs";
4
+ import { CANONICAL_FIELDS, CRM_CONCEPTS, ClivlyConfigError, ClivlyEntitiesConfig, ClivlyEntityConfig, ConfigValidationError, ConfigValidationResult, CrmConcept, DiscoveredColumnMeta, DiscoveredSchemaTable, FilterExpr, FilterValue, MATERIALIZING_CONCEPTS, MaterializingConcept, RelationshipSpec, RelationshipVia, RelationshipsMap, defineClivlyConfig, entitiesConfigSchema, filterSchema, relationshipSchema, relationshipsSchema, validateEntitiesConfig } from "./entity-config.cjs";
5
5
  import { RelationshipCandidate, buildFilterFromDiscriminator, buildRelationships, relationshipViaSignature } from "./mapping-form.cjs";
6
- import { EntityMappingRow, mappingsToEntitiesConfig } from "./mappings-config.cjs";
6
+ import { a as ProjectionIdentity, c as ProjectionRef, i as ProjectionFieldBinding, l as identityRefs, n as mappingsToEntitiesConfig, o as ProjectionJoin, r as BASE_REF, s as ProjectionMapping, t as EntityMappingRow, u as projectionSchema } from "./mappings-config-BWo4cRDF.cjs";
7
7
  import { CompileOptions, CompiledView, DEFAULT_VIEW_PREFIX, ExplainResult, compileEntityView, compileEntityViews, explainEntitiesConfig } from "./view-compiler.cjs";
8
8
  import { EntitySyncResult, MirrorRecord, PersistAction, SourceRow, SyncAction, SyncResult, SyncStore, reconcile, runSync } from "./sync-engine.cjs";
9
- export { type Activity, type ActivityType, CANONICAL_FIELDS, type CRMAdapter, CRM_CONCEPTS, type ClivlyAuthAdapter, ClivlyConfigError, type ClivlyEntitiesConfig, type ClivlyEntityConfig, type ClivlyUser, type Company, type CompileOptions, type CompiledView, type ConfigValidationError, type ConfigValidationResult, type Contact, type ContactFilters, type ContactStatus, type CreateActivityInput, type CreateCompanyInput, type CreateContactInput, type CreateDealInput, type CreateTaskInput, type CrmConcept, type CrmMembership, type CrmRole, DEFAULT_VIEW_PREFIX, type Deal, type DealStage, type DiscoveredSchemaTable, type EntityMappingRow, type EntitySyncResult, type ExplainResult, type FilterExpr, type FilterValue, MATERIALIZING_CONCEPTS, type MaterializingConcept, type MembershipResolver, type MirrorRecord, type Note, type PersistAction, type RecordSource, type RelationshipCandidate, type RelationshipSpec, type RelationshipVia, type RelationshipsMap, type SourceRow, type SyncAction, type SyncResult, type SyncStore, type Task, type TaskEntityType, type TaskFilters, type TaskPriority, type TaskStatus, type UpdateContactInput, type UpdateDealInput, type UpdateTaskInput, authCustom, buildFilterFromDiscriminator, buildRelationships, compileEntityView, compileEntityViews, defineClivlyConfig, entitiesConfigSchema, explainEntitiesConfig, filterSchema, mappingsToEntitiesConfig, reconcile, relationshipSchema, relationshipViaSignature, relationshipsSchema, runSync, validateEntitiesConfig };
9
+ //#region src/projection-cardinality.d.ts
10
+ declare function joinFansOut(join: ProjectionJoin, joinTable: DiscoveredSchemaTable): boolean;
11
+ /** Every join in the projection that can multiply rows. */
12
+ declare function fanOutJoins(projection: ProjectionMapping, tablesByName: Map<string, DiscoveredSchemaTable>): ProjectionJoin[];
13
+ //#endregion
14
+ //#region src/projection-draft.d.ts
15
+ /**
16
+ * The builder's in-progress shape.
17
+ *
18
+ * A draft is deliberately looser than a `ProjectionMapping`: it exists while
19
+ * the user is still choosing things, so every field can be empty. All of the
20
+ * builder's rules live here as pure functions, which keeps the React components
21
+ * presentational and lets the rules be tested without a DOM.
22
+ */
23
+ interface ProjectionDraft {
24
+ baseTable: string;
25
+ entityKey: string;
26
+ fieldBindings: Record<string, ProjectionFieldBinding>;
27
+ identity: ProjectionIdentity;
28
+ joins: ProjectionJoin[];
29
+ }
30
+ declare function emptyProjectionDraft(baseTable: string): ProjectionDraft;
31
+ /**
32
+ * The ON conditions implied by a foreign key between the two tables, so the
33
+ * builder can pre-fill a join instead of making the user hand-pick columns.
34
+ * Returns [] when no FK relates them — the user then picks manually.
35
+ */
36
+ declare function suggestJoinConditions(baseTable: string, joinTable: string, schema: DiscoveredSchemaTable[], joinKey: string): ProjectionJoin["on"];
37
+ /** A draft becomes a projection once it has a valid key and ≥1 binding. */
38
+ declare function draftToProjection(draft: ProjectionDraft): ProjectionMapping | null;
39
+ declare function draftErrors(draft: ProjectionDraft, schema: DiscoveredSchemaTable[]): ConfigValidationError[];
40
+ /** Per-join fan-out, for the builder's inline cardinality hints. */
41
+ declare function describeCardinality(draft: ProjectionDraft, schema: DiscoveredSchemaTable[]): Array<{
42
+ fansOut: boolean;
43
+ joinKey: string;
44
+ }>;
45
+ //#endregion
46
+ //#region src/projection-validate.d.ts
47
+ /**
48
+ * Validate a projection against the discovered schema. Returns every error
49
+ * found (not just the first) so a builder UI can show them all at once.
50
+ */
51
+ declare function validateProjection(projection: ProjectionMapping, schema: DiscoveredSchemaTable[], base: string): ConfigValidationError[];
52
+ //#endregion
53
+ //#region src/schema-meta.d.ts
54
+ /**
55
+ * Accessors over a discovered table's schema-v2 metadata.
56
+ *
57
+ * Every helper treats *absent* metadata as **unknown**, never as a negative
58
+ * fact. `coversUniqueKey` returning false on a v1 payload is what makes
59
+ * projection validation fail closed: we cannot prove a join is many-to-one, so
60
+ * we refuse to compile it rather than guess.
61
+ */
62
+ declare function columnMetaFor(table: DiscoveredSchemaTable, column: string): DiscoveredColumnMeta | undefined;
63
+ /**
64
+ * Every primary-key column. More than one entry means a composite PK, which is
65
+ * why `base_pk` identity is rejected for such tables.
66
+ */
67
+ declare function primaryKeyColumns(table: DiscoveredSchemaTable): string[];
68
+ /**
69
+ * Do `columns` contain every column of at least one unique key on `table`?
70
+ *
71
+ * This is the fan-out test. A join whose ON columns cover a unique key of the
72
+ * joined table matches at most one row per base row; one that does not can
73
+ * match many.
74
+ */
75
+ declare function coversUniqueKey(table: DiscoveredSchemaTable, columns: string[]): boolean;
76
+ /** Is this table's payload rich enough to validate a projection against? */
77
+ declare function hasRichMeta(table: DiscoveredSchemaTable): boolean;
78
+ //#endregion
79
+ export { type Activity, type ActivityType, BASE_REF, CANONICAL_FIELDS, type CRMAdapter, CRM_CONCEPTS, type ClivlyAuthAdapter, ClivlyConfigError, type ClivlyEntitiesConfig, type ClivlyEntityConfig, type ClivlyUser, type Company, type CompileOptions, type CompiledView, type ConfigValidationError, type ConfigValidationResult, type Contact, type ContactFilters, type ContactStatus, type CreateActivityInput, type CreateCompanyInput, type CreateContactInput, type CreateDealInput, type CreateTaskInput, type CrmConcept, type CrmMembership, type CrmRole, DEFAULT_VIEW_PREFIX, type Deal, type DealStage, type DiscoveredColumnMeta, type DiscoveredSchemaTable, type EntityMappingRow, type EntitySyncResult, type ExplainResult, type FilterExpr, type FilterValue, MATERIALIZING_CONCEPTS, type MaterializingConcept, type MembershipResolver, type MirrorRecord, type Note, type PersistAction, type ProjectionDraft, type ProjectionFieldBinding, type ProjectionIdentity, type ProjectionJoin, type ProjectionMapping, type ProjectionRef, type RecordSource, type RelationshipCandidate, type RelationshipSpec, type RelationshipVia, type RelationshipsMap, type SourceRow, type SyncAction, type SyncResult, type SyncStore, type Task, type TaskEntityType, type TaskFilters, type TaskPriority, type TaskStatus, type UpdateContactInput, type UpdateDealInput, type UpdateTaskInput, authCustom, buildFilterFromDiscriminator, buildRelationships, columnMetaFor, compileEntityView, compileEntityViews, coversUniqueKey, defineClivlyConfig, describeCardinality, draftErrors, draftToProjection, emptyProjectionDraft, entitiesConfigSchema, explainEntitiesConfig, fanOutJoins, filterSchema, hasRichMeta, identityRefs, joinFansOut, mappingsToEntitiesConfig, primaryKeyColumns, projectionSchema, reconcile, relationshipSchema, relationshipViaSignature, relationshipsSchema, runSync, suggestJoinConditions, validateEntitiesConfig, validateProjection };