@clivly/core 0.8.0 → 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.
Files changed (42) hide show
  1. package/README.md +96 -15
  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-PoOGzvpN.cjs +728 -0
  7. package/dist/entity-config-Tb5bbKLj.mjs +621 -0
  8. package/dist/entity-config.cjs +12 -349
  9. package/dist/entity-config.d.cts +120 -1
  10. package/dist/entity-config.d.mts +120 -1
  11. package/dist/entity-config.mjs +1 -338
  12. package/dist/entity-heuristics.cjs +28 -8
  13. package/dist/entity-heuristics.d.cts +2 -12
  14. package/dist/entity-heuristics.d.mts +2 -12
  15. package/dist/entity-heuristics.mjs +28 -8
  16. package/dist/env-file.cjs +59 -0
  17. package/dist/env-file.d.cts +23 -0
  18. package/dist/env-file.d.mts +23 -0
  19. package/dist/env-file.mjs +55 -0
  20. package/dist/index.cjs +83 -2
  21. package/dist/index.d.cts +73 -3
  22. package/dist/index.d.mts +73 -3
  23. package/dist/index.mjs +69 -3
  24. package/dist/integration-state.cjs +242 -0
  25. package/dist/integration-state.d.cts +88 -0
  26. package/dist/integration-state.d.mts +88 -0
  27. package/dist/integration-state.mjs +232 -0
  28. package/dist/mappings-config-B0W5bVZj.d.mts +168 -0
  29. package/dist/mappings-config-BWo4cRDF.d.cts +168 -0
  30. package/dist/mappings-config.cjs +32 -6
  31. package/dist/mappings-config.d.cts +1 -40
  32. package/dist/mappings-config.d.mts +1 -40
  33. package/dist/mappings-config.mjs +32 -6
  34. package/dist/projection-BXBkh7qp.cjs +98 -0
  35. package/dist/projection-C_EMRmZ8.mjs +75 -0
  36. package/dist/sync-engine.cjs +9 -2
  37. package/dist/sync-engine.mjs +9 -2
  38. package/dist/view-compiler-BKrBA_II.mjs +254 -0
  39. package/dist/view-compiler-BwZ9UgLp.cjs +277 -0
  40. package/dist/view-compiler.cjs +5 -188
  41. package/dist/view-compiler.mjs +1 -184
  42. package/package.json +21 -1
@@ -0,0 +1,55 @@
1
+ //#region src/env-file.ts
2
+ const ENV_FRAMEWORKS = [
3
+ "next",
4
+ "tanstack-start",
5
+ "sveltekit",
6
+ "remix",
7
+ "nuxt",
8
+ "hono-workers"
9
+ ];
10
+ const ENV_FILES = {
11
+ next: ".env.local",
12
+ "tanstack-start": ".env",
13
+ sveltekit: ".env",
14
+ remix: ".env",
15
+ nuxt: ".env",
16
+ "hono-workers": ".dev.vars"
17
+ };
18
+ /** The conventional env file for a framework. `.env` when we do not know. */
19
+ function envFileFor(framework) {
20
+ return ENV_FILES[normalizeFramework(framework)] ?? ".env";
21
+ }
22
+ const ALIASES = {
23
+ next: "next",
24
+ nextjs: "next",
25
+ "next.js": "next",
26
+ "tanstack-start": "tanstack-start",
27
+ tanstack: "tanstack-start",
28
+ sveltekit: "sveltekit",
29
+ remix: "remix",
30
+ nuxt: "nuxt",
31
+ "hono-workers": "hono-workers",
32
+ hono: "hono-workers",
33
+ workers: "hono-workers"
34
+ };
35
+ /** The canonical id for a framework name, or null when unrecognised. */
36
+ function normalizeFramework(framework) {
37
+ if (!framework) return null;
38
+ return ALIASES[framework.toLowerCase()] ?? null;
39
+ }
40
+ /**
41
+ * Which env file to actually write to.
42
+ *
43
+ * Prefers a file that already holds the key over the conventional one: a
44
+ * project that has been running with credentials in `.env` must not suddenly
45
+ * get a second copy in `.env.local`, leaving two files disagreeing and the
46
+ * stale one still loading. Convention applies to new setups, not to a working
47
+ * one someone already has.
48
+ */
49
+ function resolveEnvFile(input) {
50
+ const conventional = envFileFor(input.framework);
51
+ if (input.existing.includes(conventional)) return conventional;
52
+ return input.existing[0] ?? conventional;
53
+ }
54
+ //#endregion
55
+ export { ENV_FRAMEWORKS, envFileFor, normalizeFramework, resolveEnvFile };
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 };
package/dist/index.d.mts 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.mjs";
2
2
  import { CRMAdapter } from "./adapter.mjs";
3
3
  import { ClivlyAuthAdapter, ClivlyUser, CrmMembership, MembershipResolver, authCustom } from "./auth-adapter.mjs";
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.mjs";
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.mjs";
5
5
  import { RelationshipCandidate, buildFilterFromDiscriminator, buildRelationships, relationshipViaSignature } from "./mapping-form.mjs";
6
- import { EntityMappingRow, mappingsToEntitiesConfig } from "./mappings-config.mjs";
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-B0W5bVZj.mjs";
7
7
  import { CompileOptions, CompiledView, DEFAULT_VIEW_PREFIX, ExplainResult, compileEntityView, compileEntityViews, explainEntitiesConfig } from "./view-compiler.mjs";
8
8
  import { EntitySyncResult, MirrorRecord, PersistAction, SourceRow, SyncAction, SyncResult, SyncStore, reconcile, runSync } from "./sync-engine.mjs";
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 };
package/dist/index.mjs CHANGED
@@ -1,7 +1,73 @@
1
1
  import { authCustom } from "./auth-adapter.mjs";
2
- import { CANONICAL_FIELDS, CRM_CONCEPTS, ClivlyConfigError, MATERIALIZING_CONCEPTS, defineClivlyConfig, entitiesConfigSchema, filterSchema, relationshipSchema, relationshipsSchema, validateEntitiesConfig } from "./entity-config.mjs";
2
+ import { i as projectionSchema, n as PROJECTION_KEY_PATTERN, r as identityRefs, t as BASE_REF } from "./projection-C_EMRmZ8.mjs";
3
+ import { _ as hasRichMeta, a as MATERIALIZING_CONCEPTS, c as filterSchema, d as validateEntitiesConfig, f as validateProjection, g as coversUniqueKey, h as columnMetaFor, i as ClivlyConfigError, l as relationshipSchema, m as joinFansOut, n as CRM_CONCEPTS, o as defineClivlyConfig, p as fanOutJoins, s as entitiesConfigSchema, t as CANONICAL_FIELDS, u as relationshipsSchema, v as primaryKeyColumns } from "./entity-config-Tb5bbKLj.mjs";
3
4
  import { buildFilterFromDiscriminator, buildRelationships, relationshipViaSignature } from "./mapping-form.mjs";
4
5
  import { mappingsToEntitiesConfig } from "./mappings-config.mjs";
5
- import { DEFAULT_VIEW_PREFIX, compileEntityView, compileEntityViews, explainEntitiesConfig } from "./view-compiler.mjs";
6
+ import { i as explainEntitiesConfig, n as compileEntityView, r as compileEntityViews, t as DEFAULT_VIEW_PREFIX } from "./view-compiler-BKrBA_II.mjs";
6
7
  import { reconcile, runSync } from "./sync-engine.mjs";
7
- export { CANONICAL_FIELDS, CRM_CONCEPTS, ClivlyConfigError, DEFAULT_VIEW_PREFIX, MATERIALIZING_CONCEPTS, authCustom, buildFilterFromDiscriminator, buildRelationships, compileEntityView, compileEntityViews, defineClivlyConfig, entitiesConfigSchema, explainEntitiesConfig, filterSchema, mappingsToEntitiesConfig, reconcile, relationshipSchema, relationshipViaSignature, relationshipsSchema, runSync, validateEntitiesConfig };
8
+ //#region src/projection-draft.ts
9
+ function emptyProjectionDraft(baseTable) {
10
+ return {
11
+ baseTable,
12
+ entityKey: "",
13
+ fieldBindings: {},
14
+ identity: { kind: "base_pk" },
15
+ joins: []
16
+ };
17
+ }
18
+ /**
19
+ * The ON conditions implied by a foreign key between the two tables, so the
20
+ * builder can pre-fill a join instead of making the user hand-pick columns.
21
+ * Returns [] when no FK relates them — the user then picks manually.
22
+ */
23
+ function suggestJoinConditions(baseTable, joinTable, schema, joinKey) {
24
+ const join = schema.find((t) => t.name === joinTable);
25
+ const conditions = [];
26
+ for (const column of join?.columnsMeta ?? []) if (column.references?.table === baseTable) conditions.push({
27
+ left: {
28
+ table: joinKey,
29
+ column: column.name
30
+ },
31
+ op: "eq",
32
+ right: {
33
+ table: BASE_REF,
34
+ column: column.references.column
35
+ }
36
+ });
37
+ return conditions;
38
+ }
39
+ /** A draft becomes a projection once it has a valid key and ≥1 binding. */
40
+ function draftToProjection(draft) {
41
+ if (!PROJECTION_KEY_PATTERN.test(draft.entityKey)) return null;
42
+ if (Object.keys(draft.fieldBindings).length === 0) return null;
43
+ return {
44
+ version: 1,
45
+ kind: "projection",
46
+ entityKey: draft.entityKey,
47
+ baseTable: draft.baseTable,
48
+ joins: draft.joins,
49
+ fieldBindings: draft.fieldBindings,
50
+ identity: draft.identity
51
+ };
52
+ }
53
+ function draftErrors(draft, schema) {
54
+ const projection = draftToProjection(draft);
55
+ if (!projection) return [{
56
+ path: "projection",
57
+ message: "Name the object and map a field."
58
+ }];
59
+ return validateProjection(projection, schema, "projection");
60
+ }
61
+ /** Per-join fan-out, for the builder's inline cardinality hints. */
62
+ function describeCardinality(draft, schema) {
63
+ const projection = draftToProjection(draft);
64
+ if (!projection) return [];
65
+ const tablesByName = new Map(schema.map((t) => [t.name, t]));
66
+ const fanning = new Set(fanOutJoins(projection, tablesByName).map((j) => j.key));
67
+ return projection.joins.map((join) => ({
68
+ joinKey: join.key,
69
+ fansOut: fanning.has(join.key)
70
+ }));
71
+ }
72
+ //#endregion
73
+ export { BASE_REF, CANONICAL_FIELDS, CRM_CONCEPTS, ClivlyConfigError, DEFAULT_VIEW_PREFIX, MATERIALIZING_CONCEPTS, 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 };
@@ -0,0 +1,242 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/integration-state.ts
3
+ const INTEGRATION_STEPS = [
4
+ "credential",
5
+ "application",
6
+ "schema",
7
+ "mapping",
8
+ "trigger",
9
+ "sync",
10
+ "widget"
11
+ ];
12
+ const INTEGRATION_STEP_LABELS = {
13
+ credential: "Secure credential",
14
+ application: "Application connected",
15
+ schema: "Schema discovered",
16
+ mapping: "Entities mapped",
17
+ trigger: "Clivly can start a sync",
18
+ sync: "First sync observed",
19
+ widget: "Chat widget installed"
20
+ };
21
+ /** Each step's prerequisites. Ordering is enforced by a test, not convention. */
22
+ const STEP_PREREQUISITES = {
23
+ credential: [],
24
+ application: ["credential"],
25
+ schema: ["application"],
26
+ mapping: ["schema"],
27
+ trigger: ["application"],
28
+ sync: ["mapping", "trigger"],
29
+ widget: ["application"]
30
+ };
31
+ function stepIndex(id) {
32
+ return INTEGRATION_STEPS.indexOf(id);
33
+ }
34
+ /** A heartbeat older than this means the app stopped checking in. */
35
+ const HEARTBEAT_STALE_MS = 600 * 1e3;
36
+ function formatAge(ms) {
37
+ if (ms < 6e4) return `${Math.max(1, Math.round(ms / 1e3))}s ago`;
38
+ if (ms < 36e5) return `${Math.round(ms / 6e4)}m ago`;
39
+ return `${Math.round(ms / 36e5)}h ago`;
40
+ }
41
+ function heartbeatAge(facts) {
42
+ return facts.lastHeartbeatAt === null ? null : facts.now - facts.lastHeartbeatAt;
43
+ }
44
+ /** Is the raw condition behind each step met, ignoring prerequisites? */
45
+ function isSatisfied(id, facts) {
46
+ const age = heartbeatAge(facts);
47
+ switch (id) {
48
+ case "credential": return facts.hasCredential;
49
+ case "application": return age !== null && age < HEARTBEAT_STALE_MS;
50
+ case "schema": return facts.discoveredTableCount > 0;
51
+ case "mapping": return facts.mappedEntityCount > 0;
52
+ case "trigger": return facts.triggerConfigured;
53
+ case "sync": return facts.lastRun?.ok === true;
54
+ default: return facts.widgetInstalled;
55
+ }
56
+ }
57
+ function evidenceFor(id, facts) {
58
+ const age = heartbeatAge(facts);
59
+ if (id === "application" && age !== null) return `heartbeat ${formatAge(age)}`;
60
+ if (id === "schema" && facts.discoveredTableCount > 0) return `found ${facts.discoveredTableCount} tables`;
61
+ if (id === "mapping" && facts.mappedEntityCount > 0) return `${facts.mappedEntityCount} entity mapped`;
62
+ if (id === "trigger" && facts.triggerConfigured) return "trigger URL and secret set";
63
+ if (id === "sync" && facts.lastRun) return `last run ${formatAge(facts.now - facts.lastRun.at)}`;
64
+ return null;
65
+ }
66
+ function problemFor(id, facts) {
67
+ if (id === "sync" && facts.lastRun && !facts.lastRun.ok) return {
68
+ code: "sync_failed",
69
+ message: facts.lastRun.message ?? "The last sync run failed.",
70
+ fix: "Open the run log to see the host response."
71
+ };
72
+ if (id === "application") {
73
+ const age = heartbeatAge(facts);
74
+ if (age !== null && age >= HEARTBEAT_STALE_MS) return {
75
+ code: "heartbeat_stale",
76
+ message: `Your app stopped checking in ${formatAge(age)}.`,
77
+ fix: "Start your app, then run `npx clivly status`."
78
+ };
79
+ if (age === null && facts.everConnected) return {
80
+ code: "heartbeat_stale",
81
+ message: "Your application stopped checking in.",
82
+ fix: "Start your app, then run `npx clivly status`."
83
+ };
84
+ }
85
+ return null;
86
+ }
87
+ /**
88
+ * Walk the ladder once. A step is `blocked` when an earlier step it needs has
89
+ * not been satisfied — a prerequisite statement, not a verdict about this step
90
+ * — and only the first unsatisfied step is `active`, so exactly one root cause
91
+ * ever surfaces.
92
+ */
93
+ function resolveSteps(facts) {
94
+ const satisfied = /* @__PURE__ */ new Set();
95
+ const steps = [];
96
+ let activeTaken = false;
97
+ for (const id of INTEGRATION_STEPS) {
98
+ const unmet = STEP_PREREQUISITES[id].find((need) => !satisfied.has(need));
99
+ const label = INTEGRATION_STEP_LABELS[id];
100
+ if (isSatisfied(id, facts)) {
101
+ satisfied.add(id);
102
+ steps.push({
103
+ id,
104
+ label,
105
+ state: "done",
106
+ blockedBy: null,
107
+ evidence: evidenceFor(id, facts),
108
+ problem: null
109
+ });
110
+ continue;
111
+ }
112
+ if (unmet !== void 0) {
113
+ steps.push({
114
+ id,
115
+ label,
116
+ state: "blocked",
117
+ blockedBy: unmet,
118
+ evidence: null,
119
+ problem: null
120
+ });
121
+ continue;
122
+ }
123
+ const problem = problemFor(id, facts);
124
+ let state = "active";
125
+ if (problem) state = "failed";
126
+ else if (id === "widget") state = "skipped";
127
+ const claimsAttention = state === "active" || state === "failed";
128
+ steps.push({
129
+ id,
130
+ label,
131
+ state: activeTaken && state === "active" ? "blocked" : state,
132
+ blockedBy: null,
133
+ evidence: evidenceFor(id, facts),
134
+ problem: activeTaken ? null : problem
135
+ });
136
+ if (claimsAttention) activeTaken = true;
137
+ }
138
+ return steps;
139
+ }
140
+ const STEP_STATUS_WHEN_ACTIVE = {
141
+ credential: "not_configured",
142
+ application: "awaiting_connection",
143
+ schema: "connected",
144
+ mapping: "mapping_required",
145
+ trigger: "trigger_required",
146
+ sync: "ready_to_sync",
147
+ widget: "healthy"
148
+ };
149
+ /**
150
+ * Collapse the ladder to the single status the surfaces switch on. Live
151
+ * conditions — a run in flight, a failure, a heartbeat gone quiet — win over
152
+ * ladder position, because they describe the integration as it is now rather
153
+ * than how far setup once got.
154
+ */
155
+ function deriveStatus(steps, facts) {
156
+ if (facts.syncInFlight) return "syncing";
157
+ if (steps.find((step) => step.id === "application")?.problem?.code === "heartbeat_stale") return "disconnected";
158
+ if (steps.some((step) => step.state === "failed")) return "error";
159
+ const blocking = steps.find((step) => step.state === "active" || step.state === "blocked");
160
+ if (blocking) return STEP_STATUS_WHEN_ACTIVE[blocking.id];
161
+ return facts.warnings.length > 0 ? "warning" : "healthy";
162
+ }
163
+ /**
164
+ * The command that installs Clivly into a host app. Exported because the connect
165
+ * dialog prints it too, and it must be the same string as the one the ladder
166
+ * recommends — that pairing is what C-05 broke.
167
+ */
168
+ const INSTALL_COMMAND = "npx clivly init";
169
+ const NEXT_BY_STEP = {
170
+ credential: {
171
+ label: "Create a credential",
172
+ command: null,
173
+ envFile: null
174
+ },
175
+ application: {
176
+ label: "Install Clivly in your app",
177
+ command: INSTALL_COMMAND,
178
+ envFile: ".env.local"
179
+ },
180
+ schema: {
181
+ label: "Check what the SDK reported",
182
+ command: "npx clivly status",
183
+ envFile: null
184
+ },
185
+ mapping: {
186
+ label: "Choose the table holding your people",
187
+ command: null,
188
+ envFile: null
189
+ },
190
+ trigger: {
191
+ label: "Let Clivly start a sync",
192
+ command: null,
193
+ envFile: null
194
+ },
195
+ sync: {
196
+ label: "Run the first sync",
197
+ command: "npx clivly sync",
198
+ envFile: null
199
+ },
200
+ widget: {
201
+ label: "Install the chat widget",
202
+ command: null,
203
+ envFile: null
204
+ }
205
+ };
206
+ /**
207
+ * THE one producer of `next.command`. Six surfaces previously each invented
208
+ * their own "run this next" string, and one of them named a read-only command
209
+ * as the fix for a write problem (C-05). If you need a command for the
210
+ * next-action slot, call this — do not write another one.
211
+ */
212
+ function nextAction(steps, status) {
213
+ if (status === "healthy" || status === "syncing") return null;
214
+ const blocking = steps.find((step) => step.state === "failed") ?? steps.find((step) => step.state === "active");
215
+ if (!blocking) return null;
216
+ if (blocking.problem?.code === "heartbeat_stale") return {
217
+ label: "Reconnect your app",
218
+ command: "npx clivly status",
219
+ envFile: null
220
+ };
221
+ return NEXT_BY_STEP[blocking.id];
222
+ }
223
+ function computeIntegrationState(facts) {
224
+ const steps = resolveSteps(facts);
225
+ const status = deriveStatus(steps, facts);
226
+ return {
227
+ status,
228
+ steps,
229
+ next: nextAction(steps, status)
230
+ };
231
+ }
232
+ //#endregion
233
+ exports.INSTALL_COMMAND = INSTALL_COMMAND;
234
+ exports.INTEGRATION_STEPS = INTEGRATION_STEPS;
235
+ exports.INTEGRATION_STEP_LABELS = INTEGRATION_STEP_LABELS;
236
+ exports.STEP_PREREQUISITES = STEP_PREREQUISITES;
237
+ exports.computeIntegrationState = computeIntegrationState;
238
+ exports.deriveStatus = deriveStatus;
239
+ exports.formatAge = formatAge;
240
+ exports.nextAction = nextAction;
241
+ exports.resolveSteps = resolveSteps;
242
+ exports.stepIndex = stepIndex;