@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.
@@ -0,0 +1,155 @@
1
+ //#region src/view-compiler.ts
2
+ /**
3
+ * View compiler (Phase 2) — turns a validated entity config into read-only
4
+ * Postgres view DDL.
5
+ *
6
+ * Each entity compiles to `crm_src_<entity>`: a projection over the host table
7
+ * that (a) selects the source primary key as `id` (the sync engine's
8
+ * `source_ref`), (b) aliases mapped columns to their Clivly field names,
9
+ * (c) resolves each relationship to a `<relationship>_ref` column carrying the
10
+ * host-side key, and (d) applies the entity's filter as a WHERE clause.
11
+ *
12
+ * The view is the security boundary: it exposes only allow-listed columns, and
13
+ * the sync engine (Phase 3) reads exclusively from it — never the raw table.
14
+ * Relationship refs stay host-side keys here; Phase 3 maps `<rel>_ref` onto the
15
+ * corresponding `crm_companies.id` mirror row.
16
+ *
17
+ * Pure string generation — no DB access. Config is developer-authored, but all
18
+ * identifiers and literals are still escaped so output is deterministic and
19
+ * injection-safe.
20
+ */
21
+ /** The source primary-key column. Assumed `id`; the sync engine reads it as `source_ref`. */
22
+ const SOURCE_KEY = "id";
23
+ const DEFAULT_VIEW_PREFIX = "crm_src_";
24
+ const DEFAULT_ROLE = "primary";
25
+ /** Quote a single identifier part, escaping embedded double-quotes. */
26
+ function quoteIdent(name) {
27
+ return `"${name.replace(/"/g, "\"\"")}"`;
28
+ }
29
+ /** Emit a SQL literal for a scalar filter value. */
30
+ function quoteLiteral(value) {
31
+ if (typeof value === "number") return String(value);
32
+ if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
33
+ return `'${value.replace(/'/g, "''")}'`;
34
+ }
35
+ function quoteList(values) {
36
+ return `(${values.map((v) => quoteLiteral(v)).join(", ")})`;
37
+ }
38
+ /** Compile one column predicate into a SQL boolean expression. */
39
+ function compilePredicate(table, column, value) {
40
+ const col = `${quoteIdent(table)}.${quoteIdent(column)}`;
41
+ if (value === null || typeof value !== "object") return `${col} = ${quoteLiteral(value)}`;
42
+ if ("eq" in value) return `${col} = ${quoteLiteral(value.eq)}`;
43
+ if ("ne" in value) return `${col} <> ${quoteLiteral(value.ne)}`;
44
+ if ("in" in value) return `${col} IN ${quoteList(value.in)}`;
45
+ if ("notIn" in value) return `${col} NOT IN ${quoteList(value.notIn)}`;
46
+ if ("isNull" in value) return `${col} IS NULL`;
47
+ if ("isNotNull" in value) return `${col} IS NOT NULL`;
48
+ throw new Error(`unsupported filter predicate on ${table}.${column}`);
49
+ }
50
+ /**
51
+ * Build the WHERE conditions for an entity. Returns an array of SQL fragments
52
+ * (ANDed by the caller). `$raw` filters pass through verbatim.
53
+ */
54
+ function compileFilterConditions(table, filter) {
55
+ if (!filter) return [];
56
+ if ("$raw" in filter) return [`(${filter.$raw})`];
57
+ return Object.entries(filter).map(([column, value]) => compilePredicate(table, column, value));
58
+ }
59
+ /** Split a `table.column` ref, defaulting the table when unqualified. */
60
+ function refParts(ref, defaultTable) {
61
+ const dot = ref.indexOf(".");
62
+ if (dot === -1) return {
63
+ table: defaultTable,
64
+ column: ref
65
+ };
66
+ return {
67
+ table: ref.slice(0, dot),
68
+ column: ref.slice(dot + 1)
69
+ };
70
+ }
71
+ function compileRelationship(relName, rel, source, related) {
72
+ const refCol = `${relName}_ref`;
73
+ const refAlias = quoteIdent(refCol);
74
+ const { via } = rel;
75
+ if ("fkOn" in via) {
76
+ const relatedTable = related?.source ?? "";
77
+ if (via.fkOn === "company") {
78
+ const { table, column } = refParts(via.column, relatedTable);
79
+ const relatedFilter = compileFilterConditions(table, related?.filter);
80
+ const on = [`${quoteIdent(table)}.${quoteIdent(column)} = ${quoteIdent(source.source)}.${quoteIdent(SOURCE_KEY)}`, ...relatedFilter].join(" AND ");
81
+ return {
82
+ clause: `LEFT JOIN ${quoteIdent(table)} ON ${on}`,
83
+ refSelect: `${quoteIdent(table)}.${quoteIdent(SOURCE_KEY)} AS ${refAlias}`,
84
+ refColumn: refCol
85
+ };
86
+ }
87
+ const { table, column } = refParts(via.column, source.source);
88
+ const on = [`${quoteIdent(relatedTable)}.${quoteIdent(SOURCE_KEY)} = ${quoteIdent(table)}.${quoteIdent(column)}`, ...compileFilterConditions(relatedTable, related?.filter)].join(" AND ");
89
+ return {
90
+ clause: `LEFT JOIN ${quoteIdent(relatedTable)} ON ${on}`,
91
+ refSelect: `${quoteIdent(relatedTable)}.${quoteIdent(SOURCE_KEY)} AS ${refAlias}`,
92
+ refColumn: refCol
93
+ };
94
+ }
95
+ if ("through" in via) {
96
+ const on = `${quoteIdent(via.through)}.${quoteIdent(via.localKey)} = ${quoteIdent(source.source)}.${quoteIdent(SOURCE_KEY)}`;
97
+ return {
98
+ clause: `LEFT JOIN ${quoteIdent(via.through)} ON ${on}`,
99
+ refSelect: `${quoteIdent(via.through)}.${quoteIdent(via.foreignKey)} AS ${refAlias}`,
100
+ refColumn: refCol
101
+ };
102
+ }
103
+ return {
104
+ clause: via.$raw,
105
+ refSelect: null,
106
+ refColumn: refCol
107
+ };
108
+ }
109
+ function compileEntityView(config, entityKey, options = {}) {
110
+ const entity = config.entities[entityKey];
111
+ if (!entity) throw new Error(`entity "${entityKey}" is not defined`);
112
+ const viewName = `${options.viewPrefix ?? DEFAULT_VIEW_PREFIX}${entityKey}`;
113
+ const src = entity.source;
114
+ const selectItems = [`${quoteIdent(src)}.${quoteIdent(SOURCE_KEY)} AS ${quoteIdent("id")}`];
115
+ const columns = ["id"];
116
+ for (const [field, column] of Object.entries(entity.fields)) {
117
+ selectItems.push(`${quoteIdent(src)}.${quoteIdent(column)} AS ${quoteIdent(field)}`);
118
+ columns.push(field);
119
+ }
120
+ const joins = [];
121
+ for (const [relName, rel] of Object.entries(entity.relationships ?? {})) {
122
+ const compiled = compileRelationship(relName, rel, entity, config.entities[rel.entity]);
123
+ joins.push(compiled.clause);
124
+ if (compiled.refSelect) {
125
+ selectItems.push(compiled.refSelect);
126
+ columns.push(compiled.refColumn);
127
+ }
128
+ }
129
+ const conditions = compileFilterConditions(src, entity.filter);
130
+ if (options.orgScope) conditions.push(`${quoteIdent(src)}.${quoteIdent(options.orgScope.column)} = ${quoteLiteral(options.orgScope.value)}`);
131
+ const lines = [
132
+ options.securityInvoker ?? true ? `CREATE OR REPLACE VIEW ${quoteIdent(viewName)} WITH (security_invoker = true) AS` : `CREATE OR REPLACE VIEW ${quoteIdent(viewName)} AS`,
133
+ `SELECT ${selectItems.join(", ")}`,
134
+ `FROM ${quoteIdent(src)}`,
135
+ ...joins
136
+ ];
137
+ if (conditions.length > 0) lines.push(`WHERE ${conditions.join(" AND ")}`);
138
+ const sql = `${lines.join("\n")};`;
139
+ return {
140
+ entityKey,
141
+ viewName,
142
+ concept: entity.concept,
143
+ role: entity.role ?? DEFAULT_ROLE,
144
+ sourceTable: src,
145
+ columns,
146
+ sql,
147
+ dropSql: `DROP VIEW IF EXISTS ${quoteIdent(viewName)};`
148
+ };
149
+ }
150
+ /** Compile every entity in the config into its view, in declaration order. */
151
+ function compileEntityViews(config, options = {}) {
152
+ return Object.keys(config.entities).map((key) => compileEntityView(config, key, options));
153
+ }
154
+ //#endregion
155
+ export { compileEntityView, compileEntityViews };
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@clivly/core",
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "ORM/auth-agnostic CRM adapter contracts and shared domain types for Clivly.",
7
+ "license": "MIT",
8
+ "sideEffects": false,
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.mts",
12
+ "import": "./dist/index.mjs"
13
+ },
14
+ "./adapter": {
15
+ "types": "./dist/adapter.d.mts",
16
+ "import": "./dist/adapter.mjs"
17
+ },
18
+ "./auth-adapter": {
19
+ "types": "./dist/auth-adapter.d.mts",
20
+ "import": "./dist/auth-adapter.mjs"
21
+ },
22
+ "./entity-config": {
23
+ "types": "./dist/entity-config.d.mts",
24
+ "import": "./dist/entity-config.mjs"
25
+ },
26
+ "./mappings-config": {
27
+ "types": "./dist/mappings-config.d.mts",
28
+ "import": "./dist/mappings-config.mjs"
29
+ },
30
+ "./mapping-form": {
31
+ "types": "./dist/mapping-form.d.mts",
32
+ "import": "./dist/mapping-form.mjs"
33
+ },
34
+ "./view-compiler": {
35
+ "types": "./dist/view-compiler.d.mts",
36
+ "import": "./dist/view-compiler.mjs"
37
+ },
38
+ "./sync-engine": {
39
+ "types": "./dist/sync-engine.d.mts",
40
+ "import": "./dist/sync-engine.mjs"
41
+ },
42
+ "./types": {
43
+ "types": "./dist/types.d.mts",
44
+ "import": "./dist/types.mjs"
45
+ }
46
+ },
47
+ "files": [
48
+ "dist"
49
+ ],
50
+ "publishConfig": {
51
+ "access": "public"
52
+ },
53
+ "dependencies": {
54
+ "zod": "^4.1.13"
55
+ },
56
+ "devDependencies": {
57
+ "tsdown": "^0.21.9",
58
+ "typescript": "^6",
59
+ "vitest": "^3.2.4",
60
+ "@clivly.com/config": "0.0.0"
61
+ },
62
+ "scripts": {
63
+ "build": "tsdown",
64
+ "check-types": "tsc --noEmit",
65
+ "test": "vitest run"
66
+ },
67
+ "main": "./dist/index.mjs",
68
+ "types": "./dist/index.d.mts"
69
+ }