clivly 0.24.0-next.0 → 0.24.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 +26 -14
- package/app-id-5cB6yioz.mjs +53 -0
- package/app-id-DcQ4u1c8.cjs +70 -0
- package/drizzle.cjs +120 -13
- package/drizzle.d.cts +7 -1
- package/drizzle.d.mts +7 -1
- package/drizzle.mjs +126 -19
- package/from-sql-BD7gR4bC.mjs +282 -0
- package/from-sql-CFgXkCe2.cjs +347 -0
- package/{index-CZkp8TV4.d.cts → from-sql-CpGP7K3J.d.mts} +8 -46
- package/{index-Cnrz4ywf.d.mts → from-sql-S8dSvU-e.d.cts} +8 -46
- package/index-BoemTWH4.d.mts +134 -0
- package/index-CIupXz_w.d.cts +134 -0
- package/index.cjs +246 -76
- package/index.d.cts +11 -2
- package/index.d.mts +11 -2
- package/index.mjs +245 -75
- package/introspector-5w2x89RD.mjs +55 -0
- package/introspector-DT_Ma59k.cjs +60 -0
- package/kysely.cjs +56 -0
- package/kysely.d.cts +45 -0
- package/kysely.d.mts +45 -0
- package/kysely.mjs +54 -0
- package/{namespace-probe--GvxJ06J.d.mts → namespace-probe-CUR2zG2l.d.mts} +33 -3
- package/package.json +15 -1
- package/projection-guard-C70l5U24.cjs +170 -0
- package/projection-guard-DOt_nbGn.mjs +147 -0
- package/sdk.cjs +1 -1
- package/sdk.d.cts +1 -1
- package/sdk.d.mts +1 -1
- package/sdk.mjs +1 -1
- package/sql.cjs +14 -7
- package/sql.d.cts +3 -2
- package/sql.d.mts +3 -2
- package/sql.mjs +6 -3
- package/{src-X0-yIA3O.cjs → src-CZIdwwI2.cjs} +162 -59
- package/{src-Dq2nY1Sj.mjs → src-tFhC1Ru2.mjs} +141 -38
- package/supabase-contact-3ke1KKUs.mjs +595 -0
- package/supabase-contact-BXQ0nnLq.cjs +624 -0
- package/supabase.cjs +30 -120
- package/supabase.d.cts +2 -1
- package/supabase.d.mts +2 -1
- package/supabase.mjs +27 -117
- package/{projection-guard-D8VUhCz7.cjs → sync-CdA9dgZz.cjs} +165 -154
- package/{projection-guard-7AMY0aCk.mjs → sync-Q0O-2kFI.mjs} +136 -143
- package/{types-UR-tT4c1.d.cts → types-CzL7lUH9.d.cts} +33 -3
- package/vite.d.cts +1 -1
- package/vite.d.mts +1 -1
- package/discover-BZIPXl23.cjs +0 -200
- package/discover-CFIi43Qn.mjs +0 -195
- package/drizzle-meta-BPnRLpsB.cjs +0 -8
- package/drizzle-meta-D00lFvAk.mjs +0 -3
- package/introspector-BwYgHGcS.cjs +0 -363
- package/introspector-Bz52xOUr.mjs +0 -334
|
@@ -0,0 +1,595 @@
|
|
|
1
|
+
import { r as identityRefs, t as BASE_REF } from "./projection-CzBI2NL8.mjs";
|
|
2
|
+
import { i as compileProjectionJoins, n as compileProjectionFrom, r as compileProjectionIdentity } from "./projection-sql-2joBkLz2.mjs";
|
|
3
|
+
import { a as CURSOR_ALIAS, c as hideCursorAlias, d as postgresDialect, i as normaliseRows, l as keysetPage, n as fromSql, r as narrowedMetaValue, s as exactCursorRead, u as sqlKeysetReads } from "./from-sql-BD7gR4bC.mjs";
|
|
4
|
+
import "./app-id-5cB6yioz.mjs";
|
|
5
|
+
import { C as markAnonymousColumn, S as isAnonymousFilter, b as authTableKind, g as AUTH_USERS_COLUMNS, h as DRIZZLE_META, n as ROW_EXACT_CURSOR_KEY, t as ROW_CURSOR_KEY, v as AUTH_USERS_TABLE, x as filtersAnonymous } from "./sync-Q0O-2kFI.mjs";
|
|
6
|
+
// ../sdk/src/sql/postgres-introspection.ts
|
|
7
|
+
/**
|
|
8
|
+
* POSTGRES-ONLY introspection SQL. Kept apart from `discover.ts` so a MySQL
|
|
9
|
+
* dialect can supply its own strings without touching the assembly logic.
|
|
10
|
+
*/
|
|
11
|
+
const PG_CURRENT_SCHEMA_SQL = "select current_schema() as schema_name";
|
|
12
|
+
/** Base tables and their columns, in declaration order. `$1` = text[] schemas. */
|
|
13
|
+
const PG_COLUMNS_SQL = `
|
|
14
|
+
select c.table_schema as schema_name,
|
|
15
|
+
c.table_name as table_name,
|
|
16
|
+
c.column_name as column_name,
|
|
17
|
+
c.data_type as data_type,
|
|
18
|
+
c.udt_name as udt_name,
|
|
19
|
+
c.character_maximum_length as char_length,
|
|
20
|
+
c.is_nullable as is_nullable
|
|
21
|
+
from information_schema.columns c
|
|
22
|
+
join information_schema.tables t
|
|
23
|
+
on t.table_schema = c.table_schema
|
|
24
|
+
and t.table_name = c.table_name
|
|
25
|
+
and t.table_type = 'BASE TABLE'
|
|
26
|
+
where c.table_schema = any($1::text[])
|
|
27
|
+
order by c.table_schema, c.table_name, c.ordinal_position`;
|
|
28
|
+
/**
|
|
29
|
+
* Every full (non-partial, non-expression) unique index, which covers primary
|
|
30
|
+
* keys and unique constraints alike. Columns come back in key order.
|
|
31
|
+
*/
|
|
32
|
+
const PG_UNIQUE_KEYS_SQL = `
|
|
33
|
+
select n.nspname as schema_name,
|
|
34
|
+
t.relname as table_name,
|
|
35
|
+
i.indisprimary as is_primary,
|
|
36
|
+
(select array_agg(a.attname::text order by k.ord)
|
|
37
|
+
from unnest(i.indkey::int2[]) with ordinality as k(attnum, ord)
|
|
38
|
+
join pg_attribute a on a.attrelid = t.oid and a.attnum = k.attnum) as columns
|
|
39
|
+
from pg_index i
|
|
40
|
+
join pg_class t on t.oid = i.indrelid
|
|
41
|
+
join pg_namespace n on n.oid = t.relnamespace
|
|
42
|
+
where n.nspname = any($1::text[])
|
|
43
|
+
and i.indisunique
|
|
44
|
+
and i.indpred is null
|
|
45
|
+
and i.indexprs is null
|
|
46
|
+
order by n.nspname, t.relname, i.indisprimary desc, i.indexrelid`;
|
|
47
|
+
/** Foreign keys, one row per constraint with both column lists in key order. */
|
|
48
|
+
const PG_FOREIGN_KEYS_SQL = `
|
|
49
|
+
select n.nspname as schema_name,
|
|
50
|
+
t.relname as table_name,
|
|
51
|
+
fn.nspname as foreign_schema,
|
|
52
|
+
ft.relname as foreign_table,
|
|
53
|
+
(select array_agg(a.attname::text order by k.ord)
|
|
54
|
+
from unnest(c.conkey) with ordinality as k(attnum, ord)
|
|
55
|
+
join pg_attribute a on a.attrelid = c.conrelid and a.attnum = k.attnum) as columns,
|
|
56
|
+
(select array_agg(a.attname::text order by k.ord)
|
|
57
|
+
from unnest(c.confkey) with ordinality as k(attnum, ord)
|
|
58
|
+
join pg_attribute a on a.attrelid = c.confrelid and a.attnum = k.attnum) as foreign_columns
|
|
59
|
+
from pg_constraint c
|
|
60
|
+
join pg_class t on t.oid = c.conrelid
|
|
61
|
+
join pg_namespace n on n.oid = t.relnamespace
|
|
62
|
+
join pg_class ft on ft.oid = c.confrelid
|
|
63
|
+
join pg_namespace fn on fn.oid = ft.relnamespace
|
|
64
|
+
where c.contype = 'f'
|
|
65
|
+
and n.nspname = any($1::text[])`;
|
|
66
|
+
// ../sdk/src/sql/discover.ts
|
|
67
|
+
const [AUTH_SCHEMA = "auth", AUTH_USERS_NAME = "users"] = AUTH_USERS_TABLE.split(".");
|
|
68
|
+
const key = (schema, name) => `${schema}\0${name}`;
|
|
69
|
+
const asString = (value) => String(value);
|
|
70
|
+
const asStrings = (value) => Array.isArray(value) ? value.map(asString) : [];
|
|
71
|
+
const LEADING_UNDERSCORE = /^_/;
|
|
72
|
+
/**
|
|
73
|
+
* Normalise information_schema's type names to the vocabulary Drizzle's
|
|
74
|
+
* `getSQLType()` emits, so core's type checks (e.g. the text-typed composite
|
|
75
|
+
* identity guard) treat both discovery paths the same.
|
|
76
|
+
*/
|
|
77
|
+
function columnType$1(row) {
|
|
78
|
+
const dataType = asString(row.data_type);
|
|
79
|
+
const udt = asString(row.udt_name);
|
|
80
|
+
const length = row.char_length === null || row.char_length === void 0 ? "" : `(${asString(row.char_length)})`;
|
|
81
|
+
switch (dataType) {
|
|
82
|
+
case "character varying": return `varchar${length}`;
|
|
83
|
+
case "character": return `char${length}`;
|
|
84
|
+
case "USER-DEFINED": return udt;
|
|
85
|
+
case "ARRAY": return `${udt.replace(LEADING_UNDERSCORE, "")}[]`;
|
|
86
|
+
default: return dataType;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function makeScope(defaultSchema, requested, includeAuth) {
|
|
90
|
+
const allowedAuth = new Set(AUTH_USERS_COLUMNS);
|
|
91
|
+
return {
|
|
92
|
+
allowedAuth,
|
|
93
|
+
defaultSchema,
|
|
94
|
+
qualified: ({ schema, name }) => schema === defaultSchema && schema !== AUTH_SCHEMA ? name : `${schema}.${name}`,
|
|
95
|
+
visible(schema, name) {
|
|
96
|
+
if (name === "crm_clivly_app") return false;
|
|
97
|
+
if (schema === AUTH_SCHEMA) return includeAuth && name === AUTH_USERS_NAME;
|
|
98
|
+
return requested.includes(schema);
|
|
99
|
+
},
|
|
100
|
+
columnAllowed: (schema, column) => schema !== AUTH_SCHEMA || allowedAuth.has(column)
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function collectForeignKeys(rows, scope) {
|
|
104
|
+
const byColumn = /* @__PURE__ */ new Map();
|
|
105
|
+
for (const row of rows) {
|
|
106
|
+
const schema = asString(row.schema_name);
|
|
107
|
+
const name = asString(row.table_name);
|
|
108
|
+
const foreign = {
|
|
109
|
+
schema: asString(row.foreign_schema),
|
|
110
|
+
name: asString(row.foreign_table)
|
|
111
|
+
};
|
|
112
|
+
if (!(scope.visible(schema, name) && scope.visible(foreign.schema, foreign.name))) continue;
|
|
113
|
+
const foreignColumns = asStrings(row.foreign_columns);
|
|
114
|
+
asStrings(row.columns).forEach((column, index) => {
|
|
115
|
+
const foreignColumn = foreignColumns[index];
|
|
116
|
+
if (foreignColumn && scope.columnAllowed(foreign.schema, foreignColumn)) byColumn.set(`${key(schema, name)}\0${column}`, {
|
|
117
|
+
table: scope.qualified(foreign),
|
|
118
|
+
column: foreignColumn
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
return byColumn;
|
|
123
|
+
}
|
|
124
|
+
function keyId(columns) {
|
|
125
|
+
return [...columns].sort().join("\0");
|
|
126
|
+
}
|
|
127
|
+
function collectUniqueKeys(rows, scope) {
|
|
128
|
+
const byTable = /* @__PURE__ */ new Map();
|
|
129
|
+
const primary = /* @__PURE__ */ new Set();
|
|
130
|
+
for (const row of rows) {
|
|
131
|
+
const schema = asString(row.schema_name);
|
|
132
|
+
const name = asString(row.table_name);
|
|
133
|
+
const columns = asStrings(row.columns);
|
|
134
|
+
if (!(scope.visible(schema, name) && columns.length > 0 && columns.every((c) => scope.columnAllowed(schema, c)))) continue;
|
|
135
|
+
const tableKey = key(schema, name);
|
|
136
|
+
const list = byTable.get(tableKey) ?? [];
|
|
137
|
+
if (!list.some((existing) => keyId(existing) === keyId(columns))) list.push(columns);
|
|
138
|
+
byTable.set(tableKey, list);
|
|
139
|
+
if (row.is_primary === true) for (const column of columns) primary.add(`${tableKey}\0${column}`);
|
|
140
|
+
}
|
|
141
|
+
return {
|
|
142
|
+
byTable,
|
|
143
|
+
primary
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* The raw-SQL twin of `discoverFromDrizzle`: reads Postgres catalogs and
|
|
148
|
+
* returns the same `DiscoveredSchemaTable[]` shape. Names are unqualified in
|
|
149
|
+
* the default schema and `schema.table` elsewhere. `auth.users` is reported
|
|
150
|
+
* with only its allowlisted columns; every other `auth.*` table is omitted.
|
|
151
|
+
*/
|
|
152
|
+
async function discoverFromSql(executor, opts = {}) {
|
|
153
|
+
const [current] = await executor.query(PG_CURRENT_SCHEMA_SQL);
|
|
154
|
+
const defaultSchema = asString(current?.schema_name ?? "public");
|
|
155
|
+
const requested = opts.schemas ?? [defaultSchema];
|
|
156
|
+
const schemas = [.../* @__PURE__ */ new Set([...requested, AUTH_SCHEMA])];
|
|
157
|
+
const columnRows = await executor.query(PG_COLUMNS_SQL, [schemas]);
|
|
158
|
+
const uniqueRows = await executor.query(PG_UNIQUE_KEYS_SQL, [schemas]);
|
|
159
|
+
const fkRows = await executor.query(PG_FOREIGN_KEYS_SQL, [schemas]);
|
|
160
|
+
const authExists = columnRows.some((row) => row.schema_name === AUTH_SCHEMA && row.table_name === AUTH_USERS_NAME);
|
|
161
|
+
const includeAuth = (opts.includeAuthUsers ?? true) && authExists;
|
|
162
|
+
const hasAnonymousColumn = columnRows.some((row) => row.schema_name === AUTH_SCHEMA && row.table_name === AUTH_USERS_NAME && row.column_name === "is_anonymous");
|
|
163
|
+
const scope = makeScope(defaultSchema, requested, includeAuth);
|
|
164
|
+
const fkByColumn = collectForeignKeys(fkRows, scope);
|
|
165
|
+
const { byTable, primary } = collectUniqueKeys(uniqueRows, scope);
|
|
166
|
+
const tables = /* @__PURE__ */ new Map();
|
|
167
|
+
for (const row of columnRows) {
|
|
168
|
+
const schema = asString(row.schema_name);
|
|
169
|
+
const name = asString(row.table_name);
|
|
170
|
+
const column = asString(row.column_name);
|
|
171
|
+
if (!(scope.visible(schema, name) && scope.columnAllowed(schema, column))) continue;
|
|
172
|
+
const tableKey = key(schema, name);
|
|
173
|
+
const table = tables.get(tableKey) ?? {
|
|
174
|
+
name: scope.qualified({
|
|
175
|
+
schema,
|
|
176
|
+
name
|
|
177
|
+
}),
|
|
178
|
+
columns: [],
|
|
179
|
+
columnsMeta: [],
|
|
180
|
+
uniqueConstraints: byTable.get(tableKey) ?? []
|
|
181
|
+
};
|
|
182
|
+
tables.set(tableKey, table);
|
|
183
|
+
const references = fkByColumn.get(`${tableKey}\0${column}`);
|
|
184
|
+
const meta = {
|
|
185
|
+
name: column,
|
|
186
|
+
type: columnType$1(row),
|
|
187
|
+
nullable: row.is_nullable === "YES",
|
|
188
|
+
isPrimaryKey: primary.has(`${tableKey}\0${column}`),
|
|
189
|
+
isForeignKey: references !== void 0,
|
|
190
|
+
...references ? { references } : {}
|
|
191
|
+
};
|
|
192
|
+
table.columns.push(column);
|
|
193
|
+
table.columnsMeta?.push(meta);
|
|
194
|
+
}
|
|
195
|
+
const result = [...tables.values()];
|
|
196
|
+
const users = result.find((t) => t.name === AUTH_USERS_TABLE);
|
|
197
|
+
if (users) markAnonymousColumn(users, hasAnonymousColumn);
|
|
198
|
+
return result;
|
|
199
|
+
}
|
|
200
|
+
// ../sdk/src/sql/projection.ts
|
|
201
|
+
const dialect = postgresDialect;
|
|
202
|
+
const META_COLUMN$1 = "raw_user_meta_data";
|
|
203
|
+
const IS_ANONYMOUS = "is_anonymous";
|
|
204
|
+
const CURSOR_FORMAT = `'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'`;
|
|
205
|
+
const ALLOWED_AUTH_COLUMNS = AUTH_USERS_COLUMNS;
|
|
206
|
+
const refToken = (ref) => `${ref.table}.${ref.column}`;
|
|
207
|
+
const refSql = (ref) => `${dialect.quoteIdent(ref.table)}.${dialect.quoteIdent(ref.column)}`;
|
|
208
|
+
function parseRef(value) {
|
|
209
|
+
if (typeof value !== "string") return value;
|
|
210
|
+
const dot = value.indexOf(".");
|
|
211
|
+
if (dot <= 0 || dot === value.length - 1) throw new Error(`fromSqlProjection: cursorField "${value}" must be a ref token like "base.updated_at".`);
|
|
212
|
+
return {
|
|
213
|
+
table: value.slice(0, dot),
|
|
214
|
+
column: value.slice(dot + 1)
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
function assertKnownRef(ref, known, context) {
|
|
218
|
+
if (!known.has(ref.table)) throw new Error(`fromSqlProjection: ${context} names unknown ref "${ref.table}" — expected "${[...known].join("\", \"")}".`);
|
|
219
|
+
}
|
|
220
|
+
const anonymousFilterFor = (alias) => isAnonymousFilter.replace(IS_ANONYMOUS, `${dialect.quoteIdent(alias)}.${dialect.quoteIdent(IS_ANONYMOUS)}`);
|
|
221
|
+
function assertAuthColumnsAllowed(refs, isAuthRef) {
|
|
222
|
+
for (const { ref, binding } of refs) {
|
|
223
|
+
if (!isAuthRef(ref)) continue;
|
|
224
|
+
if (!ALLOWED_AUTH_COLUMNS.includes(ref.column)) throw new Error(`fromSqlProjection: "${AUTH_USERS_TABLE}.${ref.column}" cannot be read — only ${AUTH_USERS_COLUMNS.join(", ")} are exposed.`);
|
|
225
|
+
if (!binding && ref.column === META_COLUMN$1) throw new Error(`fromSqlProjection: "${AUTH_USERS_TABLE}.${META_COLUMN$1}" can only be read as a field, never as an identity, join key or cursor.`);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
function bindingItems(projection, emitted, isAuthRef) {
|
|
229
|
+
const items = [];
|
|
230
|
+
for (const binding of Object.values(projection.fieldBindings)) {
|
|
231
|
+
const token = refToken(binding.from);
|
|
232
|
+
if (emitted.has(token)) continue;
|
|
233
|
+
emitted.add(token);
|
|
234
|
+
const value = isAuthRef(binding.from) && binding.from.column === META_COLUMN$1 ? narrowedMetaValue(refSql(binding.from)) : refSql(binding.from);
|
|
235
|
+
items.push(`${value} AS ${dialect.quoteIdent(token)}`);
|
|
236
|
+
}
|
|
237
|
+
return items;
|
|
238
|
+
}
|
|
239
|
+
function resolveCursor(opts, known) {
|
|
240
|
+
const expression = opts.cursorExpression;
|
|
241
|
+
if (opts.cursorField !== void 0 && expression) throw new Error("fromSqlProjection: pass cursorField or cursorExpression, not both.");
|
|
242
|
+
if (expression) {
|
|
243
|
+
for (const ref of expression.refs) assertKnownRef(ref, known, "cursorExpression");
|
|
244
|
+
const order = `(${expression.order})`;
|
|
245
|
+
return {
|
|
246
|
+
display: expression.display ? `(${expression.display})` : order,
|
|
247
|
+
nullable: expression.nullable,
|
|
248
|
+
order,
|
|
249
|
+
refs: expression.refs,
|
|
250
|
+
token: expression.field
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
if (opts.cursorField === void 0) return null;
|
|
254
|
+
const ref = parseRef(opts.cursorField);
|
|
255
|
+
assertKnownRef(ref, known, "cursorField");
|
|
256
|
+
return {
|
|
257
|
+
display: refSql(ref),
|
|
258
|
+
nullable: opts.cursorNullable ?? true,
|
|
259
|
+
order: refSql(ref),
|
|
260
|
+
refs: [ref],
|
|
261
|
+
token: refToken(ref)
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* The raw-SQL twin of `fromDrizzleProjection`: a `SyncSource` that executes a
|
|
266
|
+
* projection's joins. Rows are keyed by ref token. Read-only. Without a
|
|
267
|
+
* `cursorField` it pages by identity and reports `mode: "full"`.
|
|
268
|
+
*/
|
|
269
|
+
function fromSqlProjection(executor, projection, opts) {
|
|
270
|
+
const known = /* @__PURE__ */ new Set([BASE_REF, ...projection.joins.map((j) => j.key)]);
|
|
271
|
+
const tableOf = new Map([[BASE_REF, projection.baseTable], ...projection.joins.map((j) => [j.key, j.table])]);
|
|
272
|
+
const isAuthRef = (ref) => authTableKind(tableOf.get(ref.table) ?? "") === "users";
|
|
273
|
+
for (const table of tableOf.values()) if (authTableKind(table) === "other") throw new Error(`fromSqlProjection: "${table}" is in the auth schema and cannot be read — only ${AUTH_USERS_TABLE} is exposed.`);
|
|
274
|
+
if (projection.identity.kind === "base_pk" && projection.identity.column === void 0 && opts.basePkColumn === void 0) throw new Error(`fromSqlProjection: projection "${projection.entityKey}" has a base_pk identity with no column — pass { basePkColumn }.`);
|
|
275
|
+
for (const [field, binding] of Object.entries(projection.fieldBindings)) assertKnownRef(binding.from, known, `field "${field}"`);
|
|
276
|
+
const identityRefList = identityRefs(projection.identity, opts.basePkColumn ?? "");
|
|
277
|
+
const cursor = resolveCursor(opts, known);
|
|
278
|
+
assertAuthColumnsAllowed([...Object.values(projection.fieldBindings).map((b) => ({
|
|
279
|
+
ref: b.from,
|
|
280
|
+
binding: true
|
|
281
|
+
})), ...[
|
|
282
|
+
...identityRefList,
|
|
283
|
+
...projection.joins.flatMap((j) => j.on.flatMap((c) => [c.left, c.right])),
|
|
284
|
+
...cursor?.refs ?? []
|
|
285
|
+
].map((ref) => ({
|
|
286
|
+
ref,
|
|
287
|
+
binding: false
|
|
288
|
+
}))], isAuthRef);
|
|
289
|
+
const identityExpr = compileProjectionIdentity(projection, opts.basePkColumn ?? "");
|
|
290
|
+
const excludeAnonymous = opts.excludeAnonymous !== false;
|
|
291
|
+
const joins = compileProjectionJoins(projection).map((join, i) => {
|
|
292
|
+
const spec = projection.joins[i];
|
|
293
|
+
return excludeAnonymous && spec && authTableKind(spec.table) === "users" ? `${join} AND (${anonymousFilterFor(spec.key)})` : join;
|
|
294
|
+
});
|
|
295
|
+
const fromClause = [compileProjectionFrom(projection), ...joins].join(" ");
|
|
296
|
+
const baseGuard = excludeAnonymous && authTableKind(projection.baseTable) === "users" ? `(${anonymousFilterFor(BASE_REF)})` : null;
|
|
297
|
+
const selectItems = [`${identityExpr} AS ${dialect.quoteIdent("id")}`];
|
|
298
|
+
const emitted = /* @__PURE__ */ new Set();
|
|
299
|
+
if (cursor) {
|
|
300
|
+
selectItems.push(`to_char(CAST(${cursor.display} AS timestamptz) AT TIME ZONE 'UTC', ${CURSOR_FORMAT}) AS ${dialect.quoteIdent(cursor.token)}`);
|
|
301
|
+
emitted.add(cursor.token);
|
|
302
|
+
}
|
|
303
|
+
selectItems.push(...bindingItems(projection, emitted, isAuthRef));
|
|
304
|
+
if (cursor) selectItems.push(`${exactCursorRead(cursor.order)} AS ${dialect.quoteIdent(CURSOR_ALIAS)}`);
|
|
305
|
+
const head = `select ${selectItems.join(", ")} ${fromClause}`;
|
|
306
|
+
const page = async (predicate, order, params, limit) => {
|
|
307
|
+
const predicates = [predicate, baseGuard].filter((p) => p !== null);
|
|
308
|
+
const all = [...params, limit];
|
|
309
|
+
const where = predicates.length === 0 ? "" : ` where ${predicates.join(" and ")}`;
|
|
310
|
+
const text = `${head}${where} order by ${order} limit ${dialect.param(all.length)}`;
|
|
311
|
+
return normaliseRows(await executor.query(text, all));
|
|
312
|
+
};
|
|
313
|
+
const fetchIdPage = async ({ afterId, limit }) => await page(afterId === null ? null : `${identityExpr} > ${dialect.param(1)}`, identityExpr, afterId === null ? [] : [afterId], limit);
|
|
314
|
+
const fetchPage = async ({ since, limit }) => {
|
|
315
|
+
if (!cursor) return await fetchIdPage({
|
|
316
|
+
afterId: since?.id ?? null,
|
|
317
|
+
limit
|
|
318
|
+
});
|
|
319
|
+
const rows = await keysetPage(since, limit, sqlKeysetReads(cursor.order, identityExpr, cursor.nullable, page));
|
|
320
|
+
return hideCursorAlias(rows);
|
|
321
|
+
};
|
|
322
|
+
return {
|
|
323
|
+
entity: opts.entity,
|
|
324
|
+
pushSource: projection.baseTable,
|
|
325
|
+
cursorField: cursor?.token ?? "id",
|
|
326
|
+
idField: "id",
|
|
327
|
+
...cursor ? {} : { mode: "full" },
|
|
328
|
+
objectType: opts.objectType,
|
|
329
|
+
fetchPage,
|
|
330
|
+
fetchIdPage
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
// ../sdk/src/sql/supabase-contact.ts
|
|
334
|
+
const PROFILES = "profiles";
|
|
335
|
+
const PROJECTION_KEY = "users";
|
|
336
|
+
const META_COLUMN = "raw_user_meta_data";
|
|
337
|
+
const UPDATED_AT = "updated_at";
|
|
338
|
+
const ID = "id";
|
|
339
|
+
const EPOCH = "timestamptz '1970-01-01 00:00:00+00'";
|
|
340
|
+
const WITH_TIME_ZONE = /with time zone|^timestamptz/i;
|
|
341
|
+
const WITHOUT_TIME_ZONE = /^timestamp/i;
|
|
342
|
+
/**
|
|
343
|
+
* The flat column every Supabase contact row carries for the person's name:
|
|
344
|
+
* the profile's `full_name` (or `name`) when `public.profiles` joins, else
|
|
345
|
+
* `raw_user_meta_data.full_name` (or `.name`). Map a contact's `name` to it.
|
|
346
|
+
*/
|
|
347
|
+
const SUPABASE_CONTACT_NAME_COLUMN = "full_name";
|
|
348
|
+
/** Where the name is looked for, in order, on a profile row and in metadata. */
|
|
349
|
+
const NAME_KEYS = ["full_name", "name"];
|
|
350
|
+
/** The contact table named in options is not in the discovered schema. */
|
|
351
|
+
var ContactTableMissing = class extends Error {
|
|
352
|
+
constructor(table) {
|
|
353
|
+
super(`supabaseContactSource: table "${table}" is not in the schema.`);
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
/** `public.profiles`, when its `id` is a foreign key to auth.users. */
|
|
357
|
+
function joinableProfiles(tables) {
|
|
358
|
+
const profiles = tables.find((t) => t.name === PROFILES);
|
|
359
|
+
const id = profiles?.columnsMeta?.find((c) => c.name === ID);
|
|
360
|
+
return profiles && id?.isForeignKey && id.references?.table === "auth.users" ? profiles : null;
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* The profile columns the join exposes, under their bare names. One that
|
|
364
|
+
* collides with an `auth.users` column (`id`, `email`, `created_at`,
|
|
365
|
+
* `updated_at`...) is dropped, not prefixed: both rows are the same person,
|
|
366
|
+
* so the auth value stays the single source of truth for that name.
|
|
367
|
+
*/
|
|
368
|
+
function profileColumns(profiles, authColumns) {
|
|
369
|
+
const columns = (profiles.columnsMeta ?? []).filter((c) => !authColumns.includes(c.name)).map((c) => ({
|
|
370
|
+
...c,
|
|
371
|
+
isPrimaryKey: false,
|
|
372
|
+
isForeignKey: false
|
|
373
|
+
}));
|
|
374
|
+
return columns.length === 0 ? null : columns;
|
|
375
|
+
}
|
|
376
|
+
/** `columnSql` as a `timestamptz`, or null when its type is no timestamp. */
|
|
377
|
+
function asTimestamptz(columnSql, type) {
|
|
378
|
+
if (type === void 0) return null;
|
|
379
|
+
if (WITH_TIME_ZONE.test(type)) return columnSql;
|
|
380
|
+
return WITHOUT_TIME_ZONE.test(type) ? `CAST(${columnSql} AS timestamptz)` : null;
|
|
381
|
+
}
|
|
382
|
+
const columnType = (table, name) => table.columnsMeta?.find((c) => c.name === name)?.type;
|
|
383
|
+
/**
|
|
384
|
+
* The joined source's cursor: the later of `auth.users.updated_at` and
|
|
385
|
+
* `profiles.updated_at`, so a profile edit moves the row too. `greatest`
|
|
386
|
+
* ignores a NULL, so a user with no profile row (LEFT JOIN) or a NULL
|
|
387
|
+
* profile stamp falls back to the auth stamp. Pushed as the row's
|
|
388
|
+
* `updated_at`, the time the contact last changed in either table.
|
|
389
|
+
*
|
|
390
|
+
* Null (a full snapshot, as before) unless both columns are timestamps.
|
|
391
|
+
* A profile edit is seen only when it moves `profiles.updated_at`, and
|
|
392
|
+
* Supabase does not do that by itself: the table needs a `moddatetime`
|
|
393
|
+
* trigger. A stamp the browser sets (`new Date()`) is not enough: a client
|
|
394
|
+
* clock behind the database lands the edit behind the cursor, and no later
|
|
395
|
+
* delta reads it.
|
|
396
|
+
*/
|
|
397
|
+
function lastChangedCursor(auth, profiles) {
|
|
398
|
+
const q = postgresDialect.quoteIdent;
|
|
399
|
+
const authStamp = asTimestamptz(`${q("base")}.${q(UPDATED_AT)}`, columnType(auth, UPDATED_AT));
|
|
400
|
+
const profileStamp = asTimestamptz(`${q("p")}.${q(UPDATED_AT)}`, columnType(profiles, UPDATED_AT));
|
|
401
|
+
if (!(authStamp && profileStamp)) return null;
|
|
402
|
+
const latest = `greatest(${authStamp}, ${profileStamp})`;
|
|
403
|
+
return {
|
|
404
|
+
field: UPDATED_AT,
|
|
405
|
+
display: latest,
|
|
406
|
+
order: `coalesce(${latest}, ${EPOCH})`,
|
|
407
|
+
nullable: false,
|
|
408
|
+
refs: [{
|
|
409
|
+
table: "base",
|
|
410
|
+
column: UPDATED_AT
|
|
411
|
+
}, {
|
|
412
|
+
table: "p",
|
|
413
|
+
column: UPDATED_AT
|
|
414
|
+
}]
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
const flatKey = (key) => key.startsWith("base.") || key.startsWith("p.") ? key.slice(key.indexOf(".") + 1) : key;
|
|
418
|
+
function profilesProjection(authColumns, joined, cursorField) {
|
|
419
|
+
const bindings = {};
|
|
420
|
+
for (const column of authColumns) if (column !== ID && column !== cursorField) bindings[column] = { from: {
|
|
421
|
+
table: "base",
|
|
422
|
+
column
|
|
423
|
+
} };
|
|
424
|
+
for (const { name } of joined) bindings[name] = { from: {
|
|
425
|
+
table: "p",
|
|
426
|
+
column: name
|
|
427
|
+
} };
|
|
428
|
+
return {
|
|
429
|
+
version: 1,
|
|
430
|
+
kind: "projection",
|
|
431
|
+
entityKey: PROJECTION_KEY,
|
|
432
|
+
baseTable: AUTH_USERS_TABLE,
|
|
433
|
+
joins: [{
|
|
434
|
+
key: "p",
|
|
435
|
+
table: PROFILES,
|
|
436
|
+
type: "left",
|
|
437
|
+
on: [{
|
|
438
|
+
left: {
|
|
439
|
+
table: "base",
|
|
440
|
+
column: "id"
|
|
441
|
+
},
|
|
442
|
+
op: "eq",
|
|
443
|
+
right: {
|
|
444
|
+
table: "p",
|
|
445
|
+
column: "id"
|
|
446
|
+
}
|
|
447
|
+
}]
|
|
448
|
+
}],
|
|
449
|
+
fieldBindings: bindings,
|
|
450
|
+
identity: {
|
|
451
|
+
kind: "base_pk",
|
|
452
|
+
column: "id"
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
const nonEmpty = (value) => typeof value === "string" && value.trim() !== "" ? value : null;
|
|
457
|
+
function metaObject(value) {
|
|
458
|
+
if (typeof value === "string") try {
|
|
459
|
+
const parsed = JSON.parse(value);
|
|
460
|
+
return parsed && typeof parsed === "object" ? parsed : null;
|
|
461
|
+
} catch {
|
|
462
|
+
return null;
|
|
463
|
+
}
|
|
464
|
+
return value && typeof value === "object" ? value : null;
|
|
465
|
+
}
|
|
466
|
+
function firstName(from, keys) {
|
|
467
|
+
for (const key of keys) {
|
|
468
|
+
const found = nonEmpty(from?.[key]);
|
|
469
|
+
if (found) return found;
|
|
470
|
+
}
|
|
471
|
+
return null;
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* The person's name for one flat row: a joined profile's own name columns
|
|
475
|
+
* first (only those the join brought in), then the user's metadata.
|
|
476
|
+
*/
|
|
477
|
+
function contactName(row, profileNameKeys) {
|
|
478
|
+
return firstName(row, profileNameKeys) ?? firstName(metaObject(row[META_COLUMN]), NAME_KEYS);
|
|
479
|
+
}
|
|
480
|
+
const POSITION_KEYS = [ROW_EXACT_CURSOR_KEY, ROW_CURSOR_KEY];
|
|
481
|
+
/**
|
|
482
|
+
* The projection writes each column under its ref token (`p.full_name`). The
|
|
483
|
+
* cloud reads `row[sourceColumn]` through a flat field map, so contact rows go
|
|
484
|
+
* out flat, under bare column names, with `full_name` filled in. Each row
|
|
485
|
+
* keeps its hidden position; `cursorField` must name a flat key.
|
|
486
|
+
*/
|
|
487
|
+
function flatWithName(source, profileNameKeys, cursorField) {
|
|
488
|
+
return {
|
|
489
|
+
...source,
|
|
490
|
+
cursorField,
|
|
491
|
+
async fetchPage(args) {
|
|
492
|
+
return (await source.fetchPage(args)).map((row) => {
|
|
493
|
+
const flat = Object.fromEntries(Object.entries(row).map(([key, value]) => [flatKey(key), value]));
|
|
494
|
+
flat[SUPABASE_CONTACT_NAME_COLUMN] = contactName(flat, profileNameKeys);
|
|
495
|
+
for (const key of POSITION_KEYS) if (key in row) Object.defineProperty(flat, key, {
|
|
496
|
+
value: row[key],
|
|
497
|
+
enumerable: false
|
|
498
|
+
});
|
|
499
|
+
return flat;
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Attach the source metadata `doctor` and the schema upload read (a spread
|
|
506
|
+
* drops it: it is non-enumerable), describing the rows as they are pushed:
|
|
507
|
+
* the advertised table. `derivedColumns` are the ones that do not come from
|
|
508
|
+
* `auth.users` (profile columns, `full_name`), so its column allowlist is
|
|
509
|
+
* not applied to them.
|
|
510
|
+
*/
|
|
511
|
+
function withSourceMeta(source, advertised, authColumns) {
|
|
512
|
+
const sourceMeta = {
|
|
513
|
+
kind: "sql",
|
|
514
|
+
columnKeys: advertised.columns,
|
|
515
|
+
columnsMeta: advertised.columnsMeta,
|
|
516
|
+
cursorField: source.cursorField,
|
|
517
|
+
idField: ID,
|
|
518
|
+
tableName: advertised.name,
|
|
519
|
+
derivedColumns: advertised.columns.filter((c) => !authColumns.includes(c)),
|
|
520
|
+
...advertised.uniqueConstraints === void 0 ? {} : { uniqueConstraints: advertised.uniqueConstraints }
|
|
521
|
+
};
|
|
522
|
+
Object.defineProperty(source, DRIZZLE_META, {
|
|
523
|
+
value: sourceMeta,
|
|
524
|
+
enumerable: false
|
|
525
|
+
});
|
|
526
|
+
return source;
|
|
527
|
+
}
|
|
528
|
+
const NAME_META = {
|
|
529
|
+
name: SUPABASE_CONTACT_NAME_COLUMN,
|
|
530
|
+
type: "text",
|
|
531
|
+
nullable: true,
|
|
532
|
+
isPrimaryKey: false,
|
|
533
|
+
isForeignKey: false
|
|
534
|
+
};
|
|
535
|
+
function advertise(meta, extra) {
|
|
536
|
+
const added = extra.filter((c, i) => !meta.columns.includes(c.name) && extra.findIndex((other) => other.name === c.name) === i);
|
|
537
|
+
return {
|
|
538
|
+
...meta,
|
|
539
|
+
columns: [...meta.columns, ...added.map((c) => c.name)],
|
|
540
|
+
columnsMeta: [...meta.columnsMeta ?? [], ...added]
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* The contact source for a Supabase app, from `discoverFromSql`'s tables.
|
|
545
|
+
* `auth.users` (the default) joins `public.profiles` on `id` when that table
|
|
546
|
+
* qualifies, and every row carries a flat `full_name` (see
|
|
547
|
+
* `SUPABASE_CONTACT_NAME_COLUMN`). Any other table is read as-is by `fromSql`.
|
|
548
|
+
* Throws `ContactTableMissing` when the table is not in `tables`.
|
|
549
|
+
*/
|
|
550
|
+
function supabaseContactSource(executor, tables, opts = {}) {
|
|
551
|
+
const table = opts.table ?? "auth.users";
|
|
552
|
+
const entity = opts.entity ?? table;
|
|
553
|
+
const meta = tables.find((t) => t.name === table);
|
|
554
|
+
if (!meta) throw new ContactTableMissing(table);
|
|
555
|
+
const base = fromSql(executor, {
|
|
556
|
+
entity,
|
|
557
|
+
table,
|
|
558
|
+
meta,
|
|
559
|
+
pushSource: table
|
|
560
|
+
});
|
|
561
|
+
if (table !== "auth.users") return {
|
|
562
|
+
schema: tables,
|
|
563
|
+
source: base,
|
|
564
|
+
table
|
|
565
|
+
};
|
|
566
|
+
const profiles = opts.joinProfiles === false ? null : joinableProfiles(tables);
|
|
567
|
+
const joined = profiles ? profileColumns(profiles, meta.columns) : null;
|
|
568
|
+
const replace = (advertised) => tables.map((t) => t === meta ? advertised : t);
|
|
569
|
+
if (!(profiles && joined)) {
|
|
570
|
+
const advertised = advertise(meta, [NAME_META]);
|
|
571
|
+
return {
|
|
572
|
+
schema: replace(advertised),
|
|
573
|
+
source: withSourceMeta(flatWithName(base, [], base.cursorField), advertised, meta.columns),
|
|
574
|
+
table
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
const profileNameKeys = NAME_KEYS.filter((key) => joined.some((c) => c.name === key));
|
|
578
|
+
const cursor = lastChangedCursor(meta, profiles);
|
|
579
|
+
const projected = fromSqlProjection(executor, profilesProjection(meta.columns, joined, cursor?.field ?? null), {
|
|
580
|
+
entity,
|
|
581
|
+
excludeAnonymous: filtersAnonymous(meta),
|
|
582
|
+
objectType: PROJECTION_KEY,
|
|
583
|
+
...cursor ? { cursorExpression: cursor } : {}
|
|
584
|
+
});
|
|
585
|
+
const advertised = advertise(meta, [...joined, NAME_META]);
|
|
586
|
+
return {
|
|
587
|
+
schema: replace(advertised),
|
|
588
|
+
source: withSourceMeta(flatWithName({
|
|
589
|
+
...projected,
|
|
590
|
+
pushSource: table
|
|
591
|
+
}, profileNameKeys, cursor?.field ?? ID), advertised, meta.columns),
|
|
592
|
+
table
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
export { discoverFromSql as a, fromSqlProjection as i, SUPABASE_CONTACT_NAME_COLUMN as n, supabaseContactSource as r, ContactTableMissing as t };
|