@clivly/core 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Clivly
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # @clivly/core
2
+
3
+ ORM- and auth-agnostic contracts and shared domain types for [Clivly](https://clivly.com) — the CRM that lives inside your app.
4
+
5
+ This package defines the interfaces that ORM and auth adapters implement. It has no runtime dependencies.
6
+
7
+ ## Exports
8
+
9
+ | Entry | Contents |
10
+ |---|---|
11
+ | `.` | Everything below, re-exported |
12
+ | `@clivly/core/adapter` | `CRMAdapter` — the interface every ORM implementation fulfils (org-scoped; contacts, companies, deals, tasks, activities) |
13
+ | `@clivly/core/auth-adapter` | `ClivlyAuthAdapter`, `authCustom()`, `MembershipResolver` — pluggable host-app identity + the `crm_members` authorization layer |
14
+ | `@clivly/core/types` | Shared domain types (`Contact`, `Company`, `Deal`, `Task`, `Note`, `Activity`, inputs, filters, `CrmRole`) |
15
+
16
+ ## Usage
17
+
18
+ ```ts
19
+ import type { CRMAdapter } from "@clivly/core";
20
+
21
+ // packages/drizzle implements this; Prisma/Kysely can follow.
22
+ function useAdapter(crm: CRMAdapter) {
23
+ return crm.getContacts(orgId);
24
+ }
25
+ ```
26
+
27
+ ## License
28
+
29
+ MIT
@@ -0,0 +1,33 @@
1
+ import { Activity, Company, Contact, ContactFilters, CreateActivityInput, CreateCompanyInput, CreateContactInput, CreateDealInput, CreateTaskInput, Deal, Task, TaskFilters, UpdateContactInput, UpdateTaskInput } from "./types.mjs";
2
+
3
+ //#region src/adapter.d.ts
4
+ /**
5
+ * The contract every ORM implementation fulfils. `packages/drizzle` is the first
6
+ * implementation; Prisma/Kysely/TypeORM can follow without changes to consumers.
7
+ *
8
+ * Every method is scoped to a single organization (`orgId`) — the adapter is the
9
+ * one place tenant isolation is enforced for CRM data. Implementations only ever
10
+ * read/write Clivly-owned `crm_*` tables; they never mutate host business tables.
11
+ */
12
+ interface CRMAdapter {
13
+ archiveTask(orgId: string, id: string): Promise<Task>;
14
+ completeTask(orgId: string, id: string): Promise<Task>;
15
+ createActivity(orgId: string, data: CreateActivityInput): Promise<Activity>;
16
+ createCompany(orgId: string, data: CreateCompanyInput): Promise<Company>;
17
+ createContact(orgId: string, data: CreateContactInput): Promise<Contact>;
18
+ createDeal(orgId: string, data: CreateDealInput): Promise<Deal>;
19
+ createTask(orgId: string, data: CreateTaskInput): Promise<Task>;
20
+ getActivities(orgId: string, contactId: string): Promise<Activity[]>;
21
+ getCompanies(orgId: string): Promise<Company[]>;
22
+ getContact(orgId: string, id: string): Promise<Contact | null>;
23
+ getContacts(orgId: string, filters?: ContactFilters): Promise<Contact[]>;
24
+ getDeals(orgId: string): Promise<Deal[]>;
25
+ getTasks(orgId: string, filters?: TaskFilters): Promise<Task[]>;
26
+ reopenTask(orgId: string, id: string): Promise<Task>;
27
+ updateContact(orgId: string, id: string, data: UpdateContactInput): Promise<Contact>;
28
+ updateDealStage(orgId: string, id: string, stage: Deal["stage"]): Promise<Deal>;
29
+ updateTask(orgId: string, id: string, data: UpdateTaskInput): Promise<Task>;
30
+ updateTaskStatus(orgId: string, id: string, status: Task["status"]): Promise<Task>;
31
+ }
32
+ //#endregion
33
+ export { CRMAdapter };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,30 @@
1
+ import { CrmRole } from "./types.mjs";
2
+
3
+ //#region src/auth-adapter.d.ts
4
+ interface ClivlyUser {
5
+ email: string;
6
+ id: string;
7
+ name?: string;
8
+ }
9
+ /**
10
+ * Bridges any host auth system into Clivly. Ship adapters wrap a concrete SDK
11
+ * (`@clivly/auth-clerk`, `@clivly/auth-workos`), and `authCustom` wraps an
12
+ * arbitrary `(req) => user` resolver.
13
+ *
14
+ * This answers "who is this person?" only. Authorization ("what can they do in
15
+ * this org?") is the separate `crm_members` layer — see `MembershipResolver`.
16
+ */
17
+ interface ClivlyAuthAdapter {
18
+ getUser(req: Request): Promise<ClivlyUser | null>;
19
+ }
20
+ declare function authCustom(resolver: (req: Request) => Promise<ClivlyUser | null> | ClivlyUser | null): ClivlyAuthAdapter;
21
+ interface CrmMembership {
22
+ orgId: string;
23
+ role: CrmRole;
24
+ userId: string;
25
+ }
26
+ interface MembershipResolver {
27
+ getMembership(userId: string, orgId: string): Promise<CrmMembership | null>;
28
+ }
29
+ //#endregion
30
+ export { ClivlyAuthAdapter, ClivlyUser, CrmMembership, MembershipResolver, authCustom };
@@ -0,0 +1,6 @@
1
+ //#region src/auth-adapter.ts
2
+ function authCustom(resolver) {
3
+ return { getUser: async (req) => await resolver(req) };
4
+ }
5
+ //#endregion
6
+ export { authCustom };
@@ -0,0 +1,258 @@
1
+ import { z } from "zod";
2
+
3
+ //#region src/entity-config.d.ts
4
+ /**
5
+ * Entity Config v2 — the declarative contract that turns Clivly's "schema-aware"
6
+ * promise into a real capability.
7
+ *
8
+ * A CRM entity is no longer a flat table name. It is a *derived entity*: a
9
+ * filtered slice of a host table (`source` + `filter`), a column allowlist
10
+ * (`fields` + `readOnly`), and declared `relationships` to other entities. The
11
+ * same host table can back several entities (e.g. `users` → owners + members)
12
+ * distinguished by `role`.
13
+ *
14
+ * This module is the Phase 1 slice: types, schema, `defineClivlyConfig` (a
15
+ * structural helper) and `validateEntitiesConfig` (semantic validation against
16
+ * the host's discovered schema). It performs NO DB access and generates no SQL —
17
+ * the view compiler (Phase 2) and sync engine (Phase 3) consume this contract.
18
+ */
19
+ /** Canonical CRM concepts a host entity can map onto. */
20
+ declare const CRM_CONCEPTS: readonly ["contact", "company", "deal", "activity", "conversation", "note"];
21
+ type CrmConcept = (typeof CRM_CONCEPTS)[number];
22
+ /**
23
+ * The canonical `fields` keys the mirror actually persists, per concept — the
24
+ * crm_* columns the sync store writes. An entity's `fields` map keys must be one
25
+ * of these: a non-canonical key (e.g. `fullName` instead of `name`) validates
26
+ * structurally but has no destination column, so the store silently writes an
27
+ * empty value. `validateEntitiesConfig` flags those.
28
+ *
29
+ * This is the single source of truth — the Drizzle store imports it, so the
30
+ * two can't drift (the drift is what made the silent-data-loss trap possible).
31
+ * Concepts absent here aren't materialized yet, so their field keys are
32
+ * unconstrained.
33
+ */
34
+ declare const CANONICAL_FIELDS: {
35
+ readonly contact: readonly ["name", "email", "title", "status"];
36
+ readonly company: readonly ["name", "domain", "industry", "size"];
37
+ };
38
+ declare const filterValueSchema: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodUnion<readonly [z.ZodObject<{
39
+ eq: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
40
+ }, z.core.$strict>, z.ZodObject<{
41
+ ne: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
42
+ }, z.core.$strict>, z.ZodObject<{
43
+ in: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
44
+ }, z.core.$strict>, z.ZodObject<{
45
+ notIn: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
46
+ }, z.core.$strict>, z.ZodObject<{
47
+ isNull: z.ZodLiteral<true>;
48
+ }, z.core.$strict>, z.ZodObject<{
49
+ isNotNull: z.ZodLiteral<true>;
50
+ }, z.core.$strict>]>]>;
51
+ /** `$raw` is a reserved key; a column literally named `$raw` is not addressable. */
52
+ declare const filterSchema: z.ZodUnion<readonly [z.ZodObject<{
53
+ $raw: z.ZodString;
54
+ }, z.core.$strict>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodUnion<readonly [z.ZodObject<{
55
+ eq: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
56
+ }, z.core.$strict>, z.ZodObject<{
57
+ ne: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
58
+ }, z.core.$strict>, z.ZodObject<{
59
+ in: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
60
+ }, z.core.$strict>, z.ZodObject<{
61
+ notIn: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
62
+ }, z.core.$strict>, z.ZodObject<{
63
+ isNull: z.ZodLiteral<true>;
64
+ }, z.core.$strict>, z.ZodObject<{
65
+ isNotNull: z.ZodLiteral<true>;
66
+ }, z.core.$strict>]>]>>]>;
67
+ type FilterExpr = z.infer<typeof filterSchema>;
68
+ /** A single column predicate value (scalar shorthand or operator object). */
69
+ type FilterValue = z.infer<typeof filterValueSchema>;
70
+ /**
71
+ * How the link between two entities is expressed in the host schema:
72
+ * - `fkOn: "company"` — FK lives on the company table (e.g. organizations.owner_id)
73
+ * - `fkOn: "contact"` — FK lives on the contact table (e.g. users.organization_id)
74
+ * - `through` — a join table sits between them (many-to-many, role often here)
75
+ * - `$raw` — opaque SQL join fragment (escape hatch; not schema-validated)
76
+ *
77
+ * `column` and the join-table keys are `table.column` or bare `column` strings.
78
+ */
79
+ declare const relationshipViaSchema: z.ZodUnion<readonly [z.ZodObject<{
80
+ fkOn: z.ZodEnum<{
81
+ contact: "contact";
82
+ company: "company";
83
+ }>;
84
+ column: z.ZodString;
85
+ }, z.core.$strict>, z.ZodObject<{
86
+ through: z.ZodString;
87
+ localKey: z.ZodString;
88
+ foreignKey: z.ZodString;
89
+ }, z.core.$strict>, z.ZodObject<{
90
+ $raw: z.ZodString;
91
+ }, z.core.$strict>]>;
92
+ type RelationshipVia = z.infer<typeof relationshipViaSchema>;
93
+ declare const relationshipSchema: z.ZodObject<{
94
+ entity: z.ZodString;
95
+ via: z.ZodUnion<readonly [z.ZodObject<{
96
+ fkOn: z.ZodEnum<{
97
+ contact: "contact";
98
+ company: "company";
99
+ }>;
100
+ column: z.ZodString;
101
+ }, z.core.$strict>, z.ZodObject<{
102
+ through: z.ZodString;
103
+ localKey: z.ZodString;
104
+ foreignKey: z.ZodString;
105
+ }, z.core.$strict>, z.ZodObject<{
106
+ $raw: z.ZodString;
107
+ }, z.core.$strict>]>;
108
+ }, z.core.$strict>;
109
+ type RelationshipSpec = z.infer<typeof relationshipSchema>;
110
+ /** A named map of relationships, as stored on an entity / in the mappings row. */
111
+ declare const relationshipsSchema: z.ZodRecord<z.ZodString, z.ZodObject<{
112
+ entity: z.ZodString;
113
+ via: z.ZodUnion<readonly [z.ZodObject<{
114
+ fkOn: z.ZodEnum<{
115
+ contact: "contact";
116
+ company: "company";
117
+ }>;
118
+ column: z.ZodString;
119
+ }, z.core.$strict>, z.ZodObject<{
120
+ through: z.ZodString;
121
+ localKey: z.ZodString;
122
+ foreignKey: z.ZodString;
123
+ }, z.core.$strict>, z.ZodObject<{
124
+ $raw: z.ZodString;
125
+ }, z.core.$strict>]>;
126
+ }, z.core.$strict>>;
127
+ type RelationshipsMap = z.infer<typeof relationshipsSchema>;
128
+ declare const entitySchema: z.ZodObject<{
129
+ concept: z.ZodEnum<{
130
+ contact: "contact";
131
+ company: "company";
132
+ deal: "deal";
133
+ activity: "activity";
134
+ conversation: "conversation";
135
+ note: "note";
136
+ }>;
137
+ source: z.ZodString;
138
+ role: z.ZodOptional<z.ZodString>;
139
+ filter: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
140
+ $raw: z.ZodString;
141
+ }, z.core.$strict>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodUnion<readonly [z.ZodObject<{
142
+ eq: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
143
+ }, z.core.$strict>, z.ZodObject<{
144
+ ne: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
145
+ }, z.core.$strict>, z.ZodObject<{
146
+ in: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
147
+ }, z.core.$strict>, z.ZodObject<{
148
+ notIn: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
149
+ }, z.core.$strict>, z.ZodObject<{
150
+ isNull: z.ZodLiteral<true>;
151
+ }, z.core.$strict>, z.ZodObject<{
152
+ isNotNull: z.ZodLiteral<true>;
153
+ }, z.core.$strict>]>]>>]>>;
154
+ fields: z.ZodRecord<z.ZodString, z.ZodString>;
155
+ readOnly: z.ZodOptional<z.ZodArray<z.ZodString>>;
156
+ relationships: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
157
+ entity: z.ZodString;
158
+ via: z.ZodUnion<readonly [z.ZodObject<{
159
+ fkOn: z.ZodEnum<{
160
+ contact: "contact";
161
+ company: "company";
162
+ }>;
163
+ column: z.ZodString;
164
+ }, z.core.$strict>, z.ZodObject<{
165
+ through: z.ZodString;
166
+ localKey: z.ZodString;
167
+ foreignKey: z.ZodString;
168
+ }, z.core.$strict>, z.ZodObject<{
169
+ $raw: z.ZodString;
170
+ }, z.core.$strict>]>;
171
+ }, z.core.$strict>>>;
172
+ }, z.core.$strict>;
173
+ type ClivlyEntityConfig = z.infer<typeof entitySchema>;
174
+ declare const entitiesConfigSchema: z.ZodObject<{
175
+ entities: z.ZodRecord<z.ZodString, z.ZodObject<{
176
+ concept: z.ZodEnum<{
177
+ contact: "contact";
178
+ company: "company";
179
+ deal: "deal";
180
+ activity: "activity";
181
+ conversation: "conversation";
182
+ note: "note";
183
+ }>;
184
+ source: z.ZodString;
185
+ role: z.ZodOptional<z.ZodString>;
186
+ filter: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
187
+ $raw: z.ZodString;
188
+ }, z.core.$strict>, z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodUnion<readonly [z.ZodObject<{
189
+ eq: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
190
+ }, z.core.$strict>, z.ZodObject<{
191
+ ne: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
192
+ }, z.core.$strict>, z.ZodObject<{
193
+ in: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
194
+ }, z.core.$strict>, z.ZodObject<{
195
+ notIn: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
196
+ }, z.core.$strict>, z.ZodObject<{
197
+ isNull: z.ZodLiteral<true>;
198
+ }, z.core.$strict>, z.ZodObject<{
199
+ isNotNull: z.ZodLiteral<true>;
200
+ }, z.core.$strict>]>]>>]>>;
201
+ fields: z.ZodRecord<z.ZodString, z.ZodString>;
202
+ readOnly: z.ZodOptional<z.ZodArray<z.ZodString>>;
203
+ relationships: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
204
+ entity: z.ZodString;
205
+ via: z.ZodUnion<readonly [z.ZodObject<{
206
+ fkOn: z.ZodEnum<{
207
+ contact: "contact";
208
+ company: "company";
209
+ }>;
210
+ column: z.ZodString;
211
+ }, z.core.$strict>, z.ZodObject<{
212
+ through: z.ZodString;
213
+ localKey: z.ZodString;
214
+ foreignKey: z.ZodString;
215
+ }, z.core.$strict>, z.ZodObject<{
216
+ $raw: z.ZodString;
217
+ }, z.core.$strict>]>;
218
+ }, z.core.$strict>>>;
219
+ }, z.core.$strict>>;
220
+ }, z.core.$strict>;
221
+ type ClivlyEntitiesConfig = z.infer<typeof entitiesConfigSchema>;
222
+ /**
223
+ * Structural helper for `clivly.config.ts`. Gives full type inference on the
224
+ * literal you pass and eagerly parses it, so shape errors surface at config
225
+ * load rather than at sync time. Does NOT validate against the host schema —
226
+ * that needs the discovered schema; see `validateEntitiesConfig`.
227
+ */
228
+ declare function defineClivlyConfig(config: ClivlyEntitiesConfig): ClivlyEntitiesConfig;
229
+ /**
230
+ * A host table the SDK reported for discovery. Structurally identical to the
231
+ * SDK's `DiscoveredTable`; duplicated here to keep `@clivly/core` free of an
232
+ * SDK dependency (core is the base contract SDK builds on).
233
+ */
234
+ interface DiscoveredSchemaTable {
235
+ columns: string[];
236
+ name: string;
237
+ }
238
+ interface ConfigValidationError {
239
+ message: string;
240
+ /** Dotted path into the config, e.g. `entities.owner.fields.email`. */
241
+ path: string;
242
+ }
243
+ interface ConfigValidationResult {
244
+ errors: ConfigValidationError[];
245
+ valid: boolean;
246
+ }
247
+ /**
248
+ * Validate a (structurally valid) config against the host's discovered schema:
249
+ * source tables exist, mapped columns exist, `readOnly` ⊆ `fields`, filter
250
+ * columns exist, and relationships point at real entities/tables/columns.
251
+ *
252
+ * `$raw` filters and `$raw` relationship joins are opaque and skipped. Returns
253
+ * every error found (not just the first) so a mapping UI or CLI can show them
254
+ * all at once.
255
+ */
256
+ declare function validateEntitiesConfig(config: ClivlyEntitiesConfig, schema: DiscoveredSchemaTable[]): ConfigValidationResult;
257
+ //#endregion
258
+ export { CANONICAL_FIELDS, CRM_CONCEPTS, ClivlyEntitiesConfig, ClivlyEntityConfig, ConfigValidationError, ConfigValidationResult, CrmConcept, DiscoveredSchemaTable, FilterExpr, FilterValue, RelationshipSpec, RelationshipVia, RelationshipsMap, defineClivlyConfig, entitiesConfigSchema, filterSchema, relationshipSchema, relationshipsSchema, validateEntitiesConfig };
@@ -0,0 +1,266 @@
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
+ };
53
+ /**
54
+ * Operator forms for a single column predicate. All predicates on an entity are
55
+ * AND-ed together. `$raw` (see FilterExpr) is the escape hatch for anything the
56
+ * operators can't express.
57
+ */
58
+ const filterOperatorsSchema = z.union([
59
+ z.strictObject({ eq: z.union([
60
+ z.string(),
61
+ z.number(),
62
+ z.boolean()
63
+ ]) }),
64
+ z.strictObject({ ne: z.union([
65
+ z.string(),
66
+ z.number(),
67
+ z.boolean()
68
+ ]) }),
69
+ z.strictObject({ in: z.array(z.union([
70
+ z.string(),
71
+ z.number(),
72
+ z.boolean()
73
+ ])).min(1) }),
74
+ z.strictObject({ notIn: z.array(z.union([
75
+ z.string(),
76
+ z.number(),
77
+ z.boolean()
78
+ ])).min(1) }),
79
+ z.strictObject({ isNull: z.literal(true) }),
80
+ z.strictObject({ isNotNull: z.literal(true) })
81
+ ]);
82
+ const filterValueSchema = z.union([
83
+ z.string(),
84
+ z.number(),
85
+ z.boolean(),
86
+ filterOperatorsSchema
87
+ ]);
88
+ /**
89
+ * A raw SQL predicate fragment. Kept as a *string* (not a query-builder callback)
90
+ * so the whole config stays JSON-serializable — it can be persisted into
91
+ * `crm_entity_mappings` and shipped to the cloud unchanged. Embedded-only in
92
+ * practice; not validated against the schema.
93
+ */
94
+ const rawFilterSchema = z.strictObject({ $raw: z.string().min(1) });
95
+ const columnFilterSchema = z.record(z.string(), filterValueSchema);
96
+ /** `$raw` is a reserved key; a column literally named `$raw` is not addressable. */
97
+ const filterSchema = z.union([rawFilterSchema, columnFilterSchema]);
98
+ /**
99
+ * How the link between two entities is expressed in the host schema:
100
+ * - `fkOn: "company"` — FK lives on the company table (e.g. organizations.owner_id)
101
+ * - `fkOn: "contact"` — FK lives on the contact table (e.g. users.organization_id)
102
+ * - `through` — a join table sits between them (many-to-many, role often here)
103
+ * - `$raw` — opaque SQL join fragment (escape hatch; not schema-validated)
104
+ *
105
+ * `column` and the join-table keys are `table.column` or bare `column` strings.
106
+ */
107
+ const relationshipViaSchema = z.union([
108
+ z.strictObject({
109
+ fkOn: z.enum(["company", "contact"]),
110
+ column: z.string().min(1)
111
+ }),
112
+ z.strictObject({
113
+ through: z.string().min(1),
114
+ localKey: z.string().min(1),
115
+ foreignKey: z.string().min(1)
116
+ }),
117
+ z.strictObject({ $raw: z.string().min(1) })
118
+ ]);
119
+ const relationshipSchema = z.strictObject({
120
+ /** Key of the related entity in the `entities` map. */
121
+ entity: z.string().min(1),
122
+ via: relationshipViaSchema
123
+ });
124
+ /** A named map of relationships, as stored on an entity / in the mappings row. */
125
+ const relationshipsSchema = z.record(z.string(), relationshipSchema);
126
+ const entitySchema = z.strictObject({
127
+ /** Which CRM concept this entity maps onto. */
128
+ concept: z.enum(CRM_CONCEPTS),
129
+ /** Host table (or view) this entity is derived from. */
130
+ source: z.string().min(1),
131
+ /**
132
+ * Distinguishes multiple entities backed by the same table (e.g. "primary"
133
+ * for owners, "secondary" for members). Free text; defaults to "primary".
134
+ */
135
+ role: z.string().min(1).optional(),
136
+ /** Predicate that narrows `source` into this entity's rows. Omit = whole table. */
137
+ filter: filterSchema.optional(),
138
+ /** clivlyField → sourceColumn. At least one field is required. */
139
+ fields: z.record(z.string(), z.string()).refine((f) => Object.keys(f).length > 0, { message: "at least one field must be mapped" }),
140
+ /**
141
+ * Host-owned identity fields. Sync overwrites them; the CRM UI cannot edit
142
+ * them. Must be a subset of `fields` keys.
143
+ */
144
+ readOnly: z.array(z.string()).optional(),
145
+ /** Named relationships to other entities in this config. */
146
+ relationships: z.record(z.string(), relationshipSchema).optional()
147
+ });
148
+ 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" }) });
149
+ /**
150
+ * Structural helper for `clivly.config.ts`. Gives full type inference on the
151
+ * literal you pass and eagerly parses it, so shape errors surface at config
152
+ * load rather than at sync time. Does NOT validate against the host schema —
153
+ * that needs the discovered schema; see `validateEntitiesConfig`.
154
+ */
155
+ function defineClivlyConfig(config) {
156
+ return entitiesConfigSchema.parse(config);
157
+ }
158
+ /** Split a `table.column` / bare `column` ref into its parts. */
159
+ function parseColumnRef(ref) {
160
+ const dot = ref.indexOf(".");
161
+ if (dot === -1) return { column: ref };
162
+ return {
163
+ table: ref.slice(0, dot),
164
+ column: ref.slice(dot + 1)
165
+ };
166
+ }
167
+ /** Shared lookup + error-collection state threaded through the validators. */
168
+ var SchemaValidator = class {
169
+ errors = [];
170
+ columnsByTable = /* @__PURE__ */ new Map();
171
+ constructor(schema) {
172
+ for (const table of schema) this.columnsByTable.set(table.name, new Set(table.columns));
173
+ }
174
+ tableExists(name) {
175
+ return this.columnsByTable.has(name);
176
+ }
177
+ columnExists(table, column) {
178
+ return this.columnsByTable.get(table)?.has(column) ?? false;
179
+ }
180
+ report(path, message) {
181
+ this.errors.push({
182
+ path,
183
+ message
184
+ });
185
+ }
186
+ /** Report if `column` is absent from `table`. Returns whether it existed. */
187
+ requireColumn(path, table, column) {
188
+ if (this.columnExists(table, column)) return true;
189
+ this.report(path, `column "${column}" does not exist on "${table}"`);
190
+ return false;
191
+ }
192
+ };
193
+ function validateFields(v, base, entity) {
194
+ const canonical = CANONICAL_FIELDS[entity.concept];
195
+ for (const [field, column] of Object.entries(entity.fields)) {
196
+ v.requireColumn(`${base}.fields.${field}`, entity.source, column);
197
+ if (canonical && !canonical.includes(field)) v.report(`${base}.fields.${field}`, `"${field}" is not a canonical ${entity.concept} field (expected one of: ${canonical.join(", ")})`);
198
+ }
199
+ }
200
+ function validateReadOnly(v, base, entity) {
201
+ for (const field of entity.readOnly ?? []) if (!(field in entity.fields)) v.report(`${base}.readOnly`, `"${field}" is not one of this entity's fields`);
202
+ }
203
+ function validateFilter(v, base, entity) {
204
+ if (!entity.filter || "$raw" in entity.filter) return;
205
+ for (const column of Object.keys(entity.filter)) v.requireColumn(`${base}.filter.${column}`, entity.source, column);
206
+ }
207
+ function validateFkVia(v, relBase, via, entity, related) {
208
+ const { table, column } = parseColumnRef(via.column);
209
+ const fkTable = table ?? (via.fkOn === "contact" ? entity.source : related?.source);
210
+ const path = `${relBase}.via.column`;
211
+ if (!fkTable) {
212
+ v.report(path, `cannot resolve table for FK column "${via.column}"`);
213
+ return;
214
+ }
215
+ if (!v.tableExists(fkTable)) {
216
+ v.report(path, `table "${fkTable}" is not in the discovered schema`);
217
+ return;
218
+ }
219
+ v.requireColumn(path, fkTable, column);
220
+ }
221
+ function validateThroughVia(v, relBase, via) {
222
+ if (!v.tableExists(via.through)) {
223
+ v.report(`${relBase}.via.through`, `join table "${via.through}" is not in the discovered schema`);
224
+ return;
225
+ }
226
+ v.requireColumn(`${relBase}.via.localKey`, via.through, via.localKey);
227
+ v.requireColumn(`${relBase}.via.foreignKey`, via.through, via.foreignKey);
228
+ }
229
+ function validateRelationship(v, base, config, entity, relName, rel) {
230
+ const relBase = `${base}.relationships.${relName}`;
231
+ const related = config.entities[rel.entity];
232
+ if (!related) v.report(`${relBase}.entity`, `"${rel.entity}" is not a defined entity`);
233
+ const { via } = rel;
234
+ if ("fkOn" in via) validateFkVia(v, relBase, via, entity, related);
235
+ else if ("through" in via) validateThroughVia(v, relBase, via);
236
+ }
237
+ function validateEntity(v, config, key, entity) {
238
+ const base = `entities.${key}`;
239
+ if (!v.tableExists(entity.source)) {
240
+ v.report(`${base}.source`, `table "${entity.source}" is not in the discovered schema`);
241
+ return;
242
+ }
243
+ validateFields(v, base, entity);
244
+ validateReadOnly(v, base, entity);
245
+ validateFilter(v, base, entity);
246
+ for (const [relName, rel] of Object.entries(entity.relationships ?? {})) validateRelationship(v, base, config, entity, relName, rel);
247
+ }
248
+ /**
249
+ * Validate a (structurally valid) config against the host's discovered schema:
250
+ * source tables exist, mapped columns exist, `readOnly` ⊆ `fields`, filter
251
+ * columns exist, and relationships point at real entities/tables/columns.
252
+ *
253
+ * `$raw` filters and `$raw` relationship joins are opaque and skipped. Returns
254
+ * every error found (not just the first) so a mapping UI or CLI can show them
255
+ * all at once.
256
+ */
257
+ function validateEntitiesConfig(config, schema) {
258
+ const validator = new SchemaValidator(schema);
259
+ for (const [key, entity] of Object.entries(config.entities)) validateEntity(validator, config, key, entity);
260
+ return {
261
+ valid: validator.errors.length === 0,
262
+ errors: validator.errors
263
+ };
264
+ }
265
+ //#endregion
266
+ export { CANONICAL_FIELDS, CRM_CONCEPTS, defineClivlyConfig, entitiesConfigSchema, filterSchema, relationshipSchema, relationshipsSchema, validateEntitiesConfig };
@@ -0,0 +1,9 @@
1
+ import { Activity, ActivityType, Company, Contact, ContactFilters, ContactStatus, CreateActivityInput, CreateCompanyInput, CreateContactInput, CreateDealInput, CreateTaskInput, CrmRole, Deal, DealStage, Note, Task, TaskEntityType, TaskFilters, TaskPriority, TaskStatus, UpdateContactInput, UpdateTaskInput } from "./types.mjs";
2
+ import { CRMAdapter } from "./adapter.mjs";
3
+ import { ClivlyAuthAdapter, ClivlyUser, CrmMembership, MembershipResolver, authCustom } from "./auth-adapter.mjs";
4
+ import { CANONICAL_FIELDS, CRM_CONCEPTS, ClivlyEntitiesConfig, ClivlyEntityConfig, ConfigValidationError, ConfigValidationResult, CrmConcept, DiscoveredSchemaTable, FilterExpr, FilterValue, RelationshipSpec, RelationshipVia, RelationshipsMap, defineClivlyConfig, entitiesConfigSchema, filterSchema, relationshipSchema, relationshipsSchema, validateEntitiesConfig } from "./entity-config.mjs";
5
+ import { RelationshipCandidate, buildFilterFromDiscriminator, buildRelationships, relationshipViaSignature } from "./mapping-form.mjs";
6
+ import { EntityMappingRow, mappingsToEntitiesConfig } from "./mappings-config.mjs";
7
+ import { CompileOptions, CompiledView, compileEntityView, compileEntityViews } from "./view-compiler.mjs";
8
+ import { EntitySyncResult, MirrorRecord, PersistAction, SourceRow, SyncAction, SyncResult, SyncStore, reconcile, runSync } from "./sync-engine.mjs";
9
+ export { Activity, ActivityType, CANONICAL_FIELDS, type CRMAdapter, CRM_CONCEPTS, type ClivlyAuthAdapter, type ClivlyEntitiesConfig, type ClivlyEntityConfig, type ClivlyUser, Company, type CompileOptions, type CompiledView, type ConfigValidationError, type ConfigValidationResult, Contact, ContactFilters, ContactStatus, CreateActivityInput, CreateCompanyInput, CreateContactInput, CreateDealInput, CreateTaskInput, type CrmConcept, type CrmMembership, CrmRole, Deal, DealStage, type DiscoveredSchemaTable, type EntityMappingRow, type EntitySyncResult, type FilterExpr, type FilterValue, type MembershipResolver, type MirrorRecord, Note, type PersistAction, type RelationshipCandidate, type RelationshipSpec, type RelationshipVia, type RelationshipsMap, type SourceRow, type SyncAction, type SyncResult, type SyncStore, Task, TaskEntityType, TaskFilters, TaskPriority, TaskStatus, UpdateContactInput, UpdateTaskInput, authCustom, buildFilterFromDiscriminator, buildRelationships, compileEntityView, compileEntityViews, defineClivlyConfig, entitiesConfigSchema, filterSchema, mappingsToEntitiesConfig, reconcile, relationshipSchema, relationshipViaSignature, relationshipsSchema, runSync, validateEntitiesConfig };
package/dist/index.mjs ADDED
@@ -0,0 +1,7 @@
1
+ import { authCustom } from "./auth-adapter.mjs";
2
+ import { CANONICAL_FIELDS, CRM_CONCEPTS, defineClivlyConfig, entitiesConfigSchema, filterSchema, relationshipSchema, relationshipsSchema, validateEntitiesConfig } from "./entity-config.mjs";
3
+ import { buildFilterFromDiscriminator, buildRelationships, relationshipViaSignature } from "./mapping-form.mjs";
4
+ import { mappingsToEntitiesConfig } from "./mappings-config.mjs";
5
+ import { compileEntityView, compileEntityViews } from "./view-compiler.mjs";
6
+ import { reconcile, runSync } from "./sync-engine.mjs";
7
+ export { CANONICAL_FIELDS, CRM_CONCEPTS, authCustom, buildFilterFromDiscriminator, buildRelationships, compileEntityView, compileEntityViews, defineClivlyConfig, entitiesConfigSchema, filterSchema, mappingsToEntitiesConfig, reconcile, relationshipSchema, relationshipViaSignature, relationshipsSchema, runSync, validateEntitiesConfig };