@clivly/core 0.1.0 → 0.2.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/README.md +57 -0
- package/dist/adapter.cjs +0 -0
- package/dist/adapter.d.cts +36 -0
- package/dist/adapter.d.mts +4 -1
- package/dist/auth-adapter.cjs +7 -0
- package/dist/auth-adapter.d.cts +30 -0
- package/dist/drizzle.cjs +32 -0
- package/dist/drizzle.d.cts +21 -0
- package/dist/drizzle.d.mts +21 -0
- package/dist/drizzle.mjs +31 -0
- package/dist/entity-config.cjs +314 -0
- package/dist/entity-config.d.cts +272 -0
- package/dist/entity-config.d.mts +18 -4
- package/dist/entity-config.mjs +49 -10
- package/dist/entity-heuristics.cjs +344 -0
- package/dist/entity-heuristics.d.cts +43 -0
- package/dist/entity-heuristics.d.mts +43 -0
- package/dist/entity-heuristics.mjs +335 -0
- package/dist/index.cjs +26 -0
- package/dist/index.d.cts +9 -0
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +3 -3
- package/dist/mapping-form.cjs +50 -0
- package/dist/mapping-form.d.cts +35 -0
- package/dist/mappings-config.cjs +99 -0
- package/dist/mappings-config.d.cts +41 -0
- package/dist/mappings-config.mjs +20 -1
- package/dist/sync-engine.cjs +161 -0
- package/dist/sync-engine.d.cts +148 -0
- package/dist/sync-engine.d.mts +14 -4
- package/dist/sync-engine.mjs +39 -18
- package/dist/types.cjs +0 -0
- package/dist/types.d.cts +156 -0
- package/dist/types.d.mts +9 -1
- package/dist/view-compiler.cjs +188 -0
- package/dist/view-compiler.d.cts +64 -0
- package/dist/view-compiler.d.mts +22 -1
- package/dist/view-compiler.mjs +31 -1
- package/package.json +106 -23
package/README.md
CHANGED
|
@@ -12,6 +12,21 @@ This package defines the interfaces that ORM and auth adapters implement. It has
|
|
|
12
12
|
| `@clivly/core/adapter` | `CRMAdapter` — the interface every ORM implementation fulfils (org-scoped; contacts, companies, deals, tasks, activities) |
|
|
13
13
|
| `@clivly/core/auth-adapter` | `ClivlyAuthAdapter`, `authCustom()`, `MembershipResolver` — pluggable host-app identity + the `crm_members` authorization layer |
|
|
14
14
|
| `@clivly/core/types` | Shared domain types (`Contact`, `Company`, `Deal`, `Task`, `Note`, `Activity`, inputs, filters, `CrmRole`) |
|
|
15
|
+
| `@clivly/core/drizzle` | `discoverFromDrizzle(schema)` — derive the discovery shape from a Drizzle schema object. Requires the optional `drizzle-orm` peer dependency |
|
|
16
|
+
|
|
17
|
+
## Schema discovery (Drizzle)
|
|
18
|
+
|
|
19
|
+
`discoverFromDrizzle` turns your Drizzle schema into Clivly's discovery shape, so you don't hand-author table/column arrays:
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { discoverFromDrizzle } from "@clivly/core/drizzle";
|
|
23
|
+
import * as schema from "./db/schema";
|
|
24
|
+
|
|
25
|
+
const tables = discoverFromDrizzle(schema);
|
|
26
|
+
// → [{ name: "participants", columns: ["id", "full_name", "email", …] }, …]
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Column names are the real DB names (`full_name`), not the Drizzle keys (`fullName`). `drizzle-orm` is an **optional peer dependency** — only needed when you import this subpath.
|
|
15
30
|
|
|
16
31
|
## Usage
|
|
17
32
|
|
|
@@ -24,6 +39,48 @@ function useAdapter(crm: CRMAdapter) {
|
|
|
24
39
|
}
|
|
25
40
|
```
|
|
26
41
|
|
|
42
|
+
## The `$raw` escape hatch
|
|
43
|
+
|
|
44
|
+
Entity `filter`s and relationship `via`s accept a `$raw` form — an opaque SQL fragment for predicates the operators can't express (e.g. a cross-table condition):
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
defineClivlyConfig({
|
|
48
|
+
entities: {
|
|
49
|
+
owner: {
|
|
50
|
+
concept: "contact",
|
|
51
|
+
source: "users",
|
|
52
|
+
fields: { name: "full_name", email: "email" },
|
|
53
|
+
filter: { $raw: "role = 'owner' AND deleted_at IS NULL" },
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
**`$raw` is unchecked.** `validateEntitiesConfig` deliberately **skips** `$raw` filters and joins — it can't know your columns are real or your SQL is valid. Two consequences:
|
|
60
|
+
|
|
61
|
+
- **Injection safety is on you.** Never interpolate untrusted input into a `$raw` string; treat it like handwritten SQL. Everything else in the config is escaped for you; `$raw` is not.
|
|
62
|
+
- **Mistakes surface at sync time, not config time** — unless you dry-run it.
|
|
63
|
+
|
|
64
|
+
### Dry-run with `explainEntitiesConfig`
|
|
65
|
+
|
|
66
|
+
`explainEntitiesConfig(config, run, options?)` compiles each entity's view and executes it via a runner you provide, so a broken `$raw` fragment fails **before** the first sync. It never throws — it returns one `ExplainResult` per entity:
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { explainEntitiesConfig } from "@clivly/core";
|
|
70
|
+
|
|
71
|
+
const results = await explainEntitiesConfig(config, (sql) =>
|
|
72
|
+
// Run somewhere side-effect-free — e.g. a transaction you roll back.
|
|
73
|
+
db.transaction(async (tx) => {
|
|
74
|
+
await tx.execute(sql);
|
|
75
|
+
throw new Rollback();
|
|
76
|
+
}).catch(swallowRollback)
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
for (const r of results) {
|
|
80
|
+
if (!r.ok) console.error(`${r.entityKey}: ${r.error}`);
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
27
84
|
## License
|
|
28
85
|
|
|
29
86
|
MIT
|
package/dist/adapter.cjs
ADDED
|
File without changes
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { Activity, Company, Contact, ContactFilters, CreateActivityInput, CreateCompanyInput, CreateContactInput, CreateDealInput, CreateTaskInput, Deal, Task, TaskFilters, UpdateContactInput, UpdateDealInput, UpdateTaskInput } from "./types.cjs";
|
|
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
|
+
deleteDeal(orgId: string, id: string): Promise<Deal | null>;
|
|
21
|
+
getActivities(orgId: string, contactId: string): Promise<Activity[]>;
|
|
22
|
+
getCompanies(orgId: string): Promise<Company[]>;
|
|
23
|
+
getContact(orgId: string, id: string): Promise<Contact | null>;
|
|
24
|
+
getContacts(orgId: string, filters?: ContactFilters): Promise<Contact[]>;
|
|
25
|
+
getDeal(orgId: string, id: string): Promise<Deal | null>;
|
|
26
|
+
getDeals(orgId: string): Promise<Deal[]>;
|
|
27
|
+
getTasks(orgId: string, filters?: TaskFilters): Promise<Task[]>;
|
|
28
|
+
reopenTask(orgId: string, id: string): Promise<Task>;
|
|
29
|
+
updateContact(orgId: string, id: string, data: UpdateContactInput): Promise<Contact>;
|
|
30
|
+
updateDeal(orgId: string, id: string, data: UpdateDealInput): Promise<Deal>;
|
|
31
|
+
updateDealStage(orgId: string, id: string, stage: Deal["stage"]): Promise<Deal>;
|
|
32
|
+
updateTask(orgId: string, id: string, data: UpdateTaskInput): Promise<Task>;
|
|
33
|
+
updateTaskStatus(orgId: string, id: string, status: Task["status"]): Promise<Task>;
|
|
34
|
+
}
|
|
35
|
+
//#endregion
|
|
36
|
+
export { CRMAdapter };
|
package/dist/adapter.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Activity, Company, Contact, ContactFilters, CreateActivityInput, CreateCompanyInput, CreateContactInput, CreateDealInput, CreateTaskInput, Deal, Task, TaskFilters, UpdateContactInput, UpdateTaskInput } from "./types.mjs";
|
|
1
|
+
import { Activity, Company, Contact, ContactFilters, CreateActivityInput, CreateCompanyInput, CreateContactInput, CreateDealInput, CreateTaskInput, Deal, Task, TaskFilters, UpdateContactInput, UpdateDealInput, UpdateTaskInput } from "./types.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/adapter.d.ts
|
|
4
4
|
/**
|
|
@@ -17,14 +17,17 @@ interface CRMAdapter {
|
|
|
17
17
|
createContact(orgId: string, data: CreateContactInput): Promise<Contact>;
|
|
18
18
|
createDeal(orgId: string, data: CreateDealInput): Promise<Deal>;
|
|
19
19
|
createTask(orgId: string, data: CreateTaskInput): Promise<Task>;
|
|
20
|
+
deleteDeal(orgId: string, id: string): Promise<Deal | null>;
|
|
20
21
|
getActivities(orgId: string, contactId: string): Promise<Activity[]>;
|
|
21
22
|
getCompanies(orgId: string): Promise<Company[]>;
|
|
22
23
|
getContact(orgId: string, id: string): Promise<Contact | null>;
|
|
23
24
|
getContacts(orgId: string, filters?: ContactFilters): Promise<Contact[]>;
|
|
25
|
+
getDeal(orgId: string, id: string): Promise<Deal | null>;
|
|
24
26
|
getDeals(orgId: string): Promise<Deal[]>;
|
|
25
27
|
getTasks(orgId: string, filters?: TaskFilters): Promise<Task[]>;
|
|
26
28
|
reopenTask(orgId: string, id: string): Promise<Task>;
|
|
27
29
|
updateContact(orgId: string, id: string, data: UpdateContactInput): Promise<Contact>;
|
|
30
|
+
updateDeal(orgId: string, id: string, data: UpdateDealInput): Promise<Deal>;
|
|
28
31
|
updateDealStage(orgId: string, id: string, stage: Deal["stage"]): Promise<Deal>;
|
|
29
32
|
updateTask(orgId: string, id: string, data: UpdateTaskInput): Promise<Task>;
|
|
30
33
|
updateTaskStatus(orgId: string, id: string, status: Task["status"]): Promise<Task>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { CrmRole } from "./types.cjs";
|
|
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 };
|
package/dist/drizzle.cjs
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let drizzle_orm = require("drizzle-orm");
|
|
3
|
+
//#region src/drizzle.ts
|
|
4
|
+
/**
|
|
5
|
+
* Derive Clivly's discovery shape (table + column names) from a Drizzle schema
|
|
6
|
+
* object — the `* as schema` you pass to `drizzle(client, { schema })`. This
|
|
7
|
+
* delivers the "reads your schema" promise for Drizzle hosts: no hand-authored
|
|
8
|
+
* `DiscoveredTable[]`. Feed the result to the SDK's `schema` option, or diff it
|
|
9
|
+
* against your entity config.
|
|
10
|
+
*
|
|
11
|
+
* Column names are the real database column names (e.g. `full_name`), not the
|
|
12
|
+
* Drizzle property keys (`fullName`). Non-table values in the schema object
|
|
13
|
+
* (relations, enums, helpers) are ignored.
|
|
14
|
+
*
|
|
15
|
+
* `drizzle-orm` is an **optional peer dependency** — you only need it installed
|
|
16
|
+
* when you import this entry (`@clivly/core/drizzle`); the rest of `@clivly/core`
|
|
17
|
+
* stays dependency-free.
|
|
18
|
+
*/
|
|
19
|
+
function discoverFromDrizzle(schema) {
|
|
20
|
+
const tables = [];
|
|
21
|
+
for (const value of Object.values(schema)) {
|
|
22
|
+
if (!(0, drizzle_orm.is)(value, drizzle_orm.Table)) continue;
|
|
23
|
+
const columns = (0, drizzle_orm.getTableColumns)(value);
|
|
24
|
+
tables.push({
|
|
25
|
+
name: (0, drizzle_orm.getTableName)(value),
|
|
26
|
+
columns: Object.values(columns).map((column) => column.name)
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
return tables;
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
exports.discoverFromDrizzle = discoverFromDrizzle;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { DiscoveredSchemaTable } from "./entity-config.cjs";
|
|
2
|
+
|
|
3
|
+
//#region src/drizzle.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Derive Clivly's discovery shape (table + column names) from a Drizzle schema
|
|
6
|
+
* object — the `* as schema` you pass to `drizzle(client, { schema })`. This
|
|
7
|
+
* delivers the "reads your schema" promise for Drizzle hosts: no hand-authored
|
|
8
|
+
* `DiscoveredTable[]`. Feed the result to the SDK's `schema` option, or diff it
|
|
9
|
+
* against your entity config.
|
|
10
|
+
*
|
|
11
|
+
* Column names are the real database column names (e.g. `full_name`), not the
|
|
12
|
+
* Drizzle property keys (`fullName`). Non-table values in the schema object
|
|
13
|
+
* (relations, enums, helpers) are ignored.
|
|
14
|
+
*
|
|
15
|
+
* `drizzle-orm` is an **optional peer dependency** — you only need it installed
|
|
16
|
+
* when you import this entry (`@clivly/core/drizzle`); the rest of `@clivly/core`
|
|
17
|
+
* stays dependency-free.
|
|
18
|
+
*/
|
|
19
|
+
declare function discoverFromDrizzle(schema: Record<string, unknown>): DiscoveredSchemaTable[];
|
|
20
|
+
//#endregion
|
|
21
|
+
export { discoverFromDrizzle };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { DiscoveredSchemaTable } from "./entity-config.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/drizzle.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Derive Clivly's discovery shape (table + column names) from a Drizzle schema
|
|
6
|
+
* object — the `* as schema` you pass to `drizzle(client, { schema })`. This
|
|
7
|
+
* delivers the "reads your schema" promise for Drizzle hosts: no hand-authored
|
|
8
|
+
* `DiscoveredTable[]`. Feed the result to the SDK's `schema` option, or diff it
|
|
9
|
+
* against your entity config.
|
|
10
|
+
*
|
|
11
|
+
* Column names are the real database column names (e.g. `full_name`), not the
|
|
12
|
+
* Drizzle property keys (`fullName`). Non-table values in the schema object
|
|
13
|
+
* (relations, enums, helpers) are ignored.
|
|
14
|
+
*
|
|
15
|
+
* `drizzle-orm` is an **optional peer dependency** — you only need it installed
|
|
16
|
+
* when you import this entry (`@clivly/core/drizzle`); the rest of `@clivly/core`
|
|
17
|
+
* stays dependency-free.
|
|
18
|
+
*/
|
|
19
|
+
declare function discoverFromDrizzle(schema: Record<string, unknown>): DiscoveredSchemaTable[];
|
|
20
|
+
//#endregion
|
|
21
|
+
export { discoverFromDrizzle };
|
package/dist/drizzle.mjs
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Table, getTableColumns, getTableName, is } from "drizzle-orm";
|
|
2
|
+
//#region src/drizzle.ts
|
|
3
|
+
/**
|
|
4
|
+
* Derive Clivly's discovery shape (table + column names) from a Drizzle schema
|
|
5
|
+
* object — the `* as schema` you pass to `drizzle(client, { schema })`. This
|
|
6
|
+
* delivers the "reads your schema" promise for Drizzle hosts: no hand-authored
|
|
7
|
+
* `DiscoveredTable[]`. Feed the result to the SDK's `schema` option, or diff it
|
|
8
|
+
* against your entity config.
|
|
9
|
+
*
|
|
10
|
+
* Column names are the real database column names (e.g. `full_name`), not the
|
|
11
|
+
* Drizzle property keys (`fullName`). Non-table values in the schema object
|
|
12
|
+
* (relations, enums, helpers) are ignored.
|
|
13
|
+
*
|
|
14
|
+
* `drizzle-orm` is an **optional peer dependency** — you only need it installed
|
|
15
|
+
* when you import this entry (`@clivly/core/drizzle`); the rest of `@clivly/core`
|
|
16
|
+
* stays dependency-free.
|
|
17
|
+
*/
|
|
18
|
+
function discoverFromDrizzle(schema) {
|
|
19
|
+
const tables = [];
|
|
20
|
+
for (const value of Object.values(schema)) {
|
|
21
|
+
if (!is(value, Table)) continue;
|
|
22
|
+
const columns = getTableColumns(value);
|
|
23
|
+
tables.push({
|
|
24
|
+
name: getTableName(value),
|
|
25
|
+
columns: Object.values(columns).map((column) => column.name)
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
return tables;
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
export { discoverFromDrizzle };
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let zod = require("zod");
|
|
3
|
+
//#region src/entity-config.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
|
+
const CRM_CONCEPTS = [
|
|
21
|
+
"contact",
|
|
22
|
+
"company",
|
|
23
|
+
"deal",
|
|
24
|
+
"activity",
|
|
25
|
+
"conversation",
|
|
26
|
+
"note"
|
|
27
|
+
];
|
|
28
|
+
/**
|
|
29
|
+
* The canonical `fields` keys the mirror actually persists, per concept — the
|
|
30
|
+
* crm_* columns the sync store writes. An entity's `fields` map keys must be one
|
|
31
|
+
* of these: a non-canonical key (e.g. `fullName` instead of `name`) validates
|
|
32
|
+
* structurally but has no destination column, so the store silently writes an
|
|
33
|
+
* empty value. `validateEntitiesConfig` flags those.
|
|
34
|
+
*
|
|
35
|
+
* This is the single source of truth — the Drizzle store imports it, so the
|
|
36
|
+
* two can't drift (the drift is what made the silent-data-loss trap possible).
|
|
37
|
+
* Concepts absent here aren't materialized yet, so their field keys are
|
|
38
|
+
* unconstrained.
|
|
39
|
+
*/
|
|
40
|
+
const CANONICAL_FIELDS = {
|
|
41
|
+
contact: [
|
|
42
|
+
"name",
|
|
43
|
+
"email",
|
|
44
|
+
"title",
|
|
45
|
+
"status"
|
|
46
|
+
],
|
|
47
|
+
company: [
|
|
48
|
+
"name",
|
|
49
|
+
"domain",
|
|
50
|
+
"industry",
|
|
51
|
+
"size"
|
|
52
|
+
]
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Operator forms for a single column predicate. All predicates on an entity are
|
|
56
|
+
* AND-ed together. `$raw` (see FilterExpr) is the escape hatch for anything the
|
|
57
|
+
* operators can't express.
|
|
58
|
+
*/
|
|
59
|
+
const filterOperatorsSchema = zod.z.union([
|
|
60
|
+
zod.z.strictObject({ eq: zod.z.union([
|
|
61
|
+
zod.z.string(),
|
|
62
|
+
zod.z.number(),
|
|
63
|
+
zod.z.boolean()
|
|
64
|
+
]) }),
|
|
65
|
+
zod.z.strictObject({ ne: zod.z.union([
|
|
66
|
+
zod.z.string(),
|
|
67
|
+
zod.z.number(),
|
|
68
|
+
zod.z.boolean()
|
|
69
|
+
]) }),
|
|
70
|
+
zod.z.strictObject({ in: zod.z.array(zod.z.union([
|
|
71
|
+
zod.z.string(),
|
|
72
|
+
zod.z.number(),
|
|
73
|
+
zod.z.boolean()
|
|
74
|
+
])).min(1) }),
|
|
75
|
+
zod.z.strictObject({ notIn: zod.z.array(zod.z.union([
|
|
76
|
+
zod.z.string(),
|
|
77
|
+
zod.z.number(),
|
|
78
|
+
zod.z.boolean()
|
|
79
|
+
])).min(1) }),
|
|
80
|
+
zod.z.strictObject({ isNull: zod.z.literal(true) }),
|
|
81
|
+
zod.z.strictObject({ isNotNull: zod.z.literal(true) })
|
|
82
|
+
]);
|
|
83
|
+
const filterValueSchema = zod.z.union([
|
|
84
|
+
zod.z.string(),
|
|
85
|
+
zod.z.number(),
|
|
86
|
+
zod.z.boolean(),
|
|
87
|
+
filterOperatorsSchema
|
|
88
|
+
]);
|
|
89
|
+
/**
|
|
90
|
+
* A raw SQL predicate fragment. Kept as a *string* (not a query-builder callback)
|
|
91
|
+
* so the whole config stays JSON-serializable — it can be persisted into
|
|
92
|
+
* `crm_entity_mappings` and shipped to the cloud unchanged. Embedded-only in
|
|
93
|
+
* practice; not validated against the schema.
|
|
94
|
+
*/
|
|
95
|
+
const rawFilterSchema = zod.z.strictObject({ $raw: zod.z.string().min(1) });
|
|
96
|
+
const columnFilterSchema = zod.z.record(zod.z.string(), filterValueSchema);
|
|
97
|
+
/** `$raw` is a reserved key; a column literally named `$raw` is not addressable. */
|
|
98
|
+
const filterSchema = zod.z.union([rawFilterSchema, columnFilterSchema]);
|
|
99
|
+
/**
|
|
100
|
+
* How the link between two entities is expressed in the host schema:
|
|
101
|
+
* - `fkOn: "company"` — FK lives on the company table (e.g. organizations.owner_id)
|
|
102
|
+
* - `fkOn: "contact"` — FK lives on the contact table (e.g. users.organization_id)
|
|
103
|
+
* - `through` — a join table sits between them (many-to-many, role often here)
|
|
104
|
+
* - `$raw` — opaque SQL join fragment (escape hatch; not schema-validated)
|
|
105
|
+
*
|
|
106
|
+
* `column` and the join-table keys are `table.column` or bare `column` strings.
|
|
107
|
+
*/
|
|
108
|
+
const relationshipViaSchema = zod.z.union([
|
|
109
|
+
zod.z.strictObject({
|
|
110
|
+
fkOn: zod.z.enum(["company", "contact"]),
|
|
111
|
+
column: zod.z.string().min(1)
|
|
112
|
+
}),
|
|
113
|
+
zod.z.strictObject({
|
|
114
|
+
through: zod.z.string().min(1),
|
|
115
|
+
localKey: zod.z.string().min(1),
|
|
116
|
+
foreignKey: zod.z.string().min(1)
|
|
117
|
+
}),
|
|
118
|
+
zod.z.strictObject({ $raw: zod.z.string().min(1) })
|
|
119
|
+
]);
|
|
120
|
+
const relationshipSchema = zod.z.strictObject({
|
|
121
|
+
/** Key of the related entity in the `entities` map. */
|
|
122
|
+
entity: zod.z.string().min(1),
|
|
123
|
+
via: relationshipViaSchema
|
|
124
|
+
});
|
|
125
|
+
/** A named map of relationships, as stored on an entity / in the mappings row. */
|
|
126
|
+
const relationshipsSchema = zod.z.record(zod.z.string(), relationshipSchema);
|
|
127
|
+
const entitySchema = zod.z.strictObject({
|
|
128
|
+
/** Which CRM concept this entity maps onto. */
|
|
129
|
+
concept: zod.z.enum(CRM_CONCEPTS),
|
|
130
|
+
/** Host table (or view) this entity is derived from. */
|
|
131
|
+
source: zod.z.string().min(1),
|
|
132
|
+
/**
|
|
133
|
+
* Distinguishes multiple entities backed by the same table (e.g. "primary"
|
|
134
|
+
* for owners, "secondary" for members). Free text; defaults to "primary".
|
|
135
|
+
*/
|
|
136
|
+
role: zod.z.string().min(1).optional(),
|
|
137
|
+
/** Predicate that narrows `source` into this entity's rows. Omit = whole table. */
|
|
138
|
+
filter: filterSchema.optional(),
|
|
139
|
+
/** clivlyField → sourceColumn. At least one field is required. */
|
|
140
|
+
fields: zod.z.record(zod.z.string(), zod.z.string()).refine((f) => Object.keys(f).length > 0, { message: "at least one field must be mapped" }),
|
|
141
|
+
/**
|
|
142
|
+
* Host-owned identity fields. Sync overwrites them; the CRM UI cannot edit
|
|
143
|
+
* them. Must be a subset of `fields` keys.
|
|
144
|
+
*/
|
|
145
|
+
readOnly: zod.z.array(zod.z.string()).optional(),
|
|
146
|
+
/** Named relationships to other entities in this config. */
|
|
147
|
+
relationships: zod.z.record(zod.z.string(), relationshipSchema).optional()
|
|
148
|
+
});
|
|
149
|
+
const entitiesConfigSchema = zod.z.strictObject({ entities: zod.z.record(zod.z.string(), entitySchema).refine((e) => Object.keys(e).length > 0, { message: "at least one entity must be defined" }) });
|
|
150
|
+
/** Thrown by `defineClivlyConfig({ strict: true })` on non-canonical field keys. */
|
|
151
|
+
var ClivlyConfigError = class extends Error {
|
|
152
|
+
issues;
|
|
153
|
+
constructor(issues) {
|
|
154
|
+
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")}`);
|
|
155
|
+
this.name = "ClivlyConfigError";
|
|
156
|
+
this.issues = issues;
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
function nonCanonicalFieldKeys(entity) {
|
|
160
|
+
const canonical = CANONICAL_FIELDS[entity.concept];
|
|
161
|
+
if (!canonical) return [];
|
|
162
|
+
return Object.keys(entity.fields).filter((key) => !canonical.includes(key));
|
|
163
|
+
}
|
|
164
|
+
function nonCanonicalMessage(entity, field) {
|
|
165
|
+
const canonical = CANONICAL_FIELDS[entity.concept] ?? [];
|
|
166
|
+
return `"${field}" is not a canonical ${entity.concept} field (expected one of: ${canonical.join(", ")})`;
|
|
167
|
+
}
|
|
168
|
+
function canonicalFieldIssues(config) {
|
|
169
|
+
const issues = [];
|
|
170
|
+
for (const [key, entity] of Object.entries(config.entities)) for (const field of nonCanonicalFieldKeys(entity)) issues.push({
|
|
171
|
+
path: `entities.${key}.fields.${field}`,
|
|
172
|
+
message: nonCanonicalMessage(entity, field)
|
|
173
|
+
});
|
|
174
|
+
return issues;
|
|
175
|
+
}
|
|
176
|
+
function defaultWarn(message) {
|
|
177
|
+
console.warn(message);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Structural helper for `clivly.config.ts`. Gives full type inference on the
|
|
181
|
+
* literal you pass and eagerly parses it, so shape errors surface at config
|
|
182
|
+
* load rather than at sync time.
|
|
183
|
+
*
|
|
184
|
+
* It also catches the silent-data-loss footgun: a non-canonical field key for a
|
|
185
|
+
* materialised concept (e.g. `fullName` instead of `name` on a `contact`) has no
|
|
186
|
+
* destination column, so the store would write an empty value. By default these
|
|
187
|
+
* are reported via `onWarn` (a `console.warn`); pass `{ strict: true }` to throw
|
|
188
|
+
* a `ClivlyConfigError` instead. Does NOT validate against the host schema — that
|
|
189
|
+
* needs the discovered schema; see `validateEntitiesConfig`.
|
|
190
|
+
*/
|
|
191
|
+
function defineClivlyConfig(config, options) {
|
|
192
|
+
const parsed = entitiesConfigSchema.parse(config);
|
|
193
|
+
const issues = canonicalFieldIssues(parsed);
|
|
194
|
+
if (issues.length > 0) {
|
|
195
|
+
if (options?.strict) throw new ClivlyConfigError(issues);
|
|
196
|
+
const warn = options?.onWarn ?? defaultWarn;
|
|
197
|
+
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.`);
|
|
198
|
+
}
|
|
199
|
+
return parsed;
|
|
200
|
+
}
|
|
201
|
+
/** Split a `table.column` / bare `column` ref into its parts. */
|
|
202
|
+
function parseColumnRef(ref) {
|
|
203
|
+
const dot = ref.indexOf(".");
|
|
204
|
+
if (dot === -1) return { column: ref };
|
|
205
|
+
return {
|
|
206
|
+
table: ref.slice(0, dot),
|
|
207
|
+
column: ref.slice(dot + 1)
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
/** Shared lookup + error-collection state threaded through the validators. */
|
|
211
|
+
var SchemaValidator = class {
|
|
212
|
+
errors = [];
|
|
213
|
+
columnsByTable = /* @__PURE__ */ new Map();
|
|
214
|
+
constructor(schema) {
|
|
215
|
+
for (const table of schema) this.columnsByTable.set(table.name, new Set(table.columns));
|
|
216
|
+
}
|
|
217
|
+
tableExists(name) {
|
|
218
|
+
return this.columnsByTable.has(name);
|
|
219
|
+
}
|
|
220
|
+
columnExists(table, column) {
|
|
221
|
+
return this.columnsByTable.get(table)?.has(column) ?? false;
|
|
222
|
+
}
|
|
223
|
+
report(path, message) {
|
|
224
|
+
this.errors.push({
|
|
225
|
+
path,
|
|
226
|
+
message
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
/** Report if `column` is absent from `table`. Returns whether it existed. */
|
|
230
|
+
requireColumn(path, table, column) {
|
|
231
|
+
if (this.columnExists(table, column)) return true;
|
|
232
|
+
this.report(path, `column "${column}" does not exist on "${table}"`);
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
function validateFields(v, base, entity) {
|
|
237
|
+
for (const [field, column] of Object.entries(entity.fields)) v.requireColumn(`${base}.fields.${field}`, entity.source, column);
|
|
238
|
+
for (const field of nonCanonicalFieldKeys(entity)) v.report(`${base}.fields.${field}`, nonCanonicalMessage(entity, field));
|
|
239
|
+
}
|
|
240
|
+
function validateReadOnly(v, base, entity) {
|
|
241
|
+
for (const field of entity.readOnly ?? []) if (!(field in entity.fields)) v.report(`${base}.readOnly`, `"${field}" is not one of this entity's fields`);
|
|
242
|
+
}
|
|
243
|
+
function validateFilter(v, base, entity) {
|
|
244
|
+
if (!entity.filter || "$raw" in entity.filter) return;
|
|
245
|
+
for (const column of Object.keys(entity.filter)) v.requireColumn(`${base}.filter.${column}`, entity.source, column);
|
|
246
|
+
}
|
|
247
|
+
function validateFkVia(v, relBase, via, entity, related) {
|
|
248
|
+
const { table, column } = parseColumnRef(via.column);
|
|
249
|
+
const fkTable = table ?? (via.fkOn === "contact" ? entity.source : related?.source);
|
|
250
|
+
const path = `${relBase}.via.column`;
|
|
251
|
+
if (!fkTable) {
|
|
252
|
+
v.report(path, `cannot resolve table for FK column "${via.column}"`);
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
if (!v.tableExists(fkTable)) {
|
|
256
|
+
v.report(path, `table "${fkTable}" is not in the discovered schema`);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
v.requireColumn(path, fkTable, column);
|
|
260
|
+
}
|
|
261
|
+
function validateThroughVia(v, relBase, via) {
|
|
262
|
+
if (!v.tableExists(via.through)) {
|
|
263
|
+
v.report(`${relBase}.via.through`, `join table "${via.through}" is not in the discovered schema`);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
v.requireColumn(`${relBase}.via.localKey`, via.through, via.localKey);
|
|
267
|
+
v.requireColumn(`${relBase}.via.foreignKey`, via.through, via.foreignKey);
|
|
268
|
+
}
|
|
269
|
+
function validateRelationship(v, base, config, entity, relName, rel) {
|
|
270
|
+
const relBase = `${base}.relationships.${relName}`;
|
|
271
|
+
const related = config.entities[rel.entity];
|
|
272
|
+
if (!related) v.report(`${relBase}.entity`, `"${rel.entity}" is not a defined entity`);
|
|
273
|
+
const { via } = rel;
|
|
274
|
+
if ("fkOn" in via) validateFkVia(v, relBase, via, entity, related);
|
|
275
|
+
else if ("through" in via) validateThroughVia(v, relBase, via);
|
|
276
|
+
}
|
|
277
|
+
function validateEntity(v, config, key, entity) {
|
|
278
|
+
const base = `entities.${key}`;
|
|
279
|
+
if (!v.tableExists(entity.source)) {
|
|
280
|
+
v.report(`${base}.source`, `table "${entity.source}" is not in the discovered schema`);
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
validateFields(v, base, entity);
|
|
284
|
+
validateReadOnly(v, base, entity);
|
|
285
|
+
validateFilter(v, base, entity);
|
|
286
|
+
for (const [relName, rel] of Object.entries(entity.relationships ?? {})) validateRelationship(v, base, config, entity, relName, rel);
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Validate a (structurally valid) config against the host's discovered schema:
|
|
290
|
+
* source tables exist, mapped columns exist, `readOnly` ⊆ `fields`, filter
|
|
291
|
+
* columns exist, and relationships point at real entities/tables/columns.
|
|
292
|
+
*
|
|
293
|
+
* `$raw` filters and `$raw` relationship joins are opaque and skipped. Returns
|
|
294
|
+
* every error found (not just the first) so a mapping UI or CLI can show them
|
|
295
|
+
* all at once.
|
|
296
|
+
*/
|
|
297
|
+
function validateEntitiesConfig(config, schema) {
|
|
298
|
+
const validator = new SchemaValidator(schema);
|
|
299
|
+
for (const [key, entity] of Object.entries(config.entities)) validateEntity(validator, config, key, entity);
|
|
300
|
+
return {
|
|
301
|
+
valid: validator.errors.length === 0,
|
|
302
|
+
errors: validator.errors
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
//#endregion
|
|
306
|
+
exports.CANONICAL_FIELDS = CANONICAL_FIELDS;
|
|
307
|
+
exports.CRM_CONCEPTS = CRM_CONCEPTS;
|
|
308
|
+
exports.ClivlyConfigError = ClivlyConfigError;
|
|
309
|
+
exports.defineClivlyConfig = defineClivlyConfig;
|
|
310
|
+
exports.entitiesConfigSchema = entitiesConfigSchema;
|
|
311
|
+
exports.filterSchema = filterSchema;
|
|
312
|
+
exports.relationshipSchema = relationshipSchema;
|
|
313
|
+
exports.relationshipsSchema = relationshipsSchema;
|
|
314
|
+
exports.validateEntitiesConfig = validateEntitiesConfig;
|