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.
Files changed (54) hide show
  1. package/README.md +26 -14
  2. package/app-id-5cB6yioz.mjs +53 -0
  3. package/app-id-DcQ4u1c8.cjs +70 -0
  4. package/drizzle.cjs +120 -13
  5. package/drizzle.d.cts +7 -1
  6. package/drizzle.d.mts +7 -1
  7. package/drizzle.mjs +126 -19
  8. package/from-sql-BD7gR4bC.mjs +282 -0
  9. package/from-sql-CFgXkCe2.cjs +347 -0
  10. package/{index-CZkp8TV4.d.cts → from-sql-CpGP7K3J.d.mts} +8 -46
  11. package/{index-Cnrz4ywf.d.mts → from-sql-S8dSvU-e.d.cts} +8 -46
  12. package/index-BoemTWH4.d.mts +134 -0
  13. package/index-CIupXz_w.d.cts +134 -0
  14. package/index.cjs +246 -76
  15. package/index.d.cts +11 -2
  16. package/index.d.mts +11 -2
  17. package/index.mjs +245 -75
  18. package/introspector-5w2x89RD.mjs +55 -0
  19. package/introspector-DT_Ma59k.cjs +60 -0
  20. package/kysely.cjs +56 -0
  21. package/kysely.d.cts +45 -0
  22. package/kysely.d.mts +45 -0
  23. package/kysely.mjs +54 -0
  24. package/{namespace-probe--GvxJ06J.d.mts → namespace-probe-CUR2zG2l.d.mts} +33 -3
  25. package/package.json +15 -1
  26. package/projection-guard-C70l5U24.cjs +170 -0
  27. package/projection-guard-DOt_nbGn.mjs +147 -0
  28. package/sdk.cjs +1 -1
  29. package/sdk.d.cts +1 -1
  30. package/sdk.d.mts +1 -1
  31. package/sdk.mjs +1 -1
  32. package/sql.cjs +14 -7
  33. package/sql.d.cts +3 -2
  34. package/sql.d.mts +3 -2
  35. package/sql.mjs +6 -3
  36. package/{src-X0-yIA3O.cjs → src-CZIdwwI2.cjs} +162 -59
  37. package/{src-Dq2nY1Sj.mjs → src-tFhC1Ru2.mjs} +141 -38
  38. package/supabase-contact-3ke1KKUs.mjs +595 -0
  39. package/supabase-contact-BXQ0nnLq.cjs +624 -0
  40. package/supabase.cjs +30 -120
  41. package/supabase.d.cts +2 -1
  42. package/supabase.d.mts +2 -1
  43. package/supabase.mjs +27 -117
  44. package/{projection-guard-D8VUhCz7.cjs → sync-CdA9dgZz.cjs} +165 -154
  45. package/{projection-guard-7AMY0aCk.mjs → sync-Q0O-2kFI.mjs} +136 -143
  46. package/{types-UR-tT4c1.d.cts → types-CzL7lUH9.d.cts} +33 -3
  47. package/vite.d.cts +1 -1
  48. package/vite.d.mts +1 -1
  49. package/discover-BZIPXl23.cjs +0 -200
  50. package/discover-CFIi43Qn.mjs +0 -195
  51. package/drizzle-meta-BPnRLpsB.cjs +0 -8
  52. package/drizzle-meta-D00lFvAk.mjs +0 -3
  53. package/introspector-BwYgHGcS.cjs +0 -363
  54. package/introspector-Bz52xOUr.mjs +0 -334
@@ -1,10 +1,4 @@
1
- import { a as isSensitiveColumn } from "./entity-heuristics-DAxqagJA.mjs";
2
1
  // ../sdk/src/sql/supabase-auth-users.ts
3
- /**
4
- * The one Supabase `auth` table Clivly may read, and exactly how much of it.
5
- * Every other `auth.*` table is refused; secrets (`encrypted_password`,
6
- * tokens, `raw_app_meta_data`) are never in this list.
7
- */
8
2
  const AUTH_USERS_TABLE = "auth.users";
9
3
  const AUTH_USERS_COLUMNS = [
10
4
  "id",
@@ -23,6 +17,29 @@ const AUTH_USERS_META_KEYS = [
23
17
  ];
24
18
  /** Anonymous sign-ins are not customers. */
25
19
  const isAnonymousFilter = "coalesce(is_anonymous, false) = false";
20
+ /** The column `isAnonymousFilter` reads; Supabase Auth added it in 2024. */
21
+ const IS_ANONYMOUS_COLUMN = "is_anonymous";
22
+ const ANONYMOUS_COLUMN_KEY = "__clivly_auth_has_is_anonymous__";
23
+ /**
24
+ * Record on discovery's `auth.users` entry whether the live table has
25
+ * `is_anonymous`. The column is never advertised: it is not in the allowlist.
26
+ */
27
+ function markAnonymousColumn(table, present) {
28
+ Object.defineProperty(table, ANONYMOUS_COLUMN_KEY, {
29
+ value: present,
30
+ enumerable: false
31
+ });
32
+ }
33
+ /**
34
+ * Whether reads of `auth.users` should exclude anonymous sign-ins. False only
35
+ * when discovery saw no `is_anonymous` column (Supabase Auth before 2024, so
36
+ * no anonymous sign-ins exist to exclude): filtering on it there would fail
37
+ * every page with "column does not exist". A table entry discovery did not
38
+ * build (no mark) still filters, the safe default.
39
+ */
40
+ function filtersAnonymous(table) {
41
+ return table?.[ANONYMOUS_COLUMN_KEY] !== false;
42
+ }
26
43
  const QUOTES = /"/g;
27
44
  /**
28
45
  * Whether a projection table name points into Supabase's `auth` schema, and if
@@ -34,6 +51,8 @@ function authTableKind(name) {
34
51
  if (!normal.startsWith("auth.")) return null;
35
52
  return normal === "auth.users" ? "users" : "other";
36
53
  }
54
+ // ../sdk/src/drizzle-meta.ts
55
+ const DRIZZLE_META = "__clivly_drizzle_source_meta__";
37
56
  // ../sdk/src/entity-source.ts
38
57
  const CONCEPT_KEYS = {
39
58
  contact: "contacts",
@@ -112,28 +131,72 @@ const DEFAULT_ID_FIELD = "id";
112
131
  * `nextCursor` falls back to it only where the column itself is null.
113
132
  */
114
133
  const ROW_CURSOR_KEY = "__clivly_row_cursor__";
115
- function isAfter(candidate, current) {
116
- const ct = candidate.time.getTime();
117
- const bt = current.time.getTime();
118
- if (ct !== bt) return ct > bt;
119
- return candidate.id > current.id;
134
+ /**
135
+ * Non-enumerable key a source sets on a row to give its cursor at the
136
+ * database's full precision (`YYYY-MM-DDTHH:MM:SS.ffffffZ`). A JS Date keeps
137
+ * only milliseconds; `nextCursor` carries this as the cursor's `exact` value so
138
+ * the next page compares in Postgres at microseconds.
139
+ */
140
+ const ROW_EXACT_CURSOR_KEY = "__clivly_row_cursor_exact__";
141
+ const EXACT_CURSOR_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/;
142
+ const ISO_DATE_LENGTH = 10;
143
+ /**
144
+ * Whether `value` is a real instant in ISO 8601 UTC: it parses, and its date
145
+ * part survives the round trip (so `2026-02-30` or month 99 never pass).
146
+ */
147
+ function isValidIsoTime(value) {
148
+ const parsed = new Date(value);
149
+ return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, ISO_DATE_LENGTH) === value.slice(0, ISO_DATE_LENGTH);
120
150
  }
151
+ /** Whether `value` is an exact (microsecond) cursor time. */
152
+ const isExactCursorTime = (value) => EXACT_CURSOR_TIME.test(value) && isValidIsoTime(value);
121
153
  function nextCursor(rows, cursorField, idField, current) {
122
- let max = current;
154
+ const positions = [];
123
155
  for (const row of rows) {
124
- const raw = row[cursorField] ?? row["__clivly_row_cursor__"];
125
- if (raw === null || raw === void 0) continue;
126
- const time = raw instanceof Date ? raw : new Date(String(raw));
127
- if (Number.isNaN(time.getTime())) continue;
128
- const idRaw = row[idField];
129
- const candidate = {
130
- time,
131
- id: idRaw === null || idRaw === void 0 ? "" : String(idRaw)
132
- };
133
- if (!max || isAfter(candidate, max)) max = candidate;
156
+ const position = rowPosition(row, cursorField, idField);
157
+ if (position) positions.push(position);
134
158
  }
159
+ const last = positions.at(-1);
160
+ if (!last) return current;
161
+ if (inKeysetOrder(positions, current)) return last;
162
+ let max = current;
163
+ for (const position of positions) if (!max || compareTimes(position, max) > 0 || compareTimes(position, max) === 0 && position.id > max.id) max = position;
135
164
  return max;
136
165
  }
166
+ function compareTimes(a, b) {
167
+ const diff = a.time.getTime() - b.time.getTime();
168
+ if (diff !== 0) return Math.sign(diff);
169
+ if (a.exact && b.exact && a.exact !== b.exact) return a.exact > b.exact ? 1 : -1;
170
+ return 0;
171
+ }
172
+ function inKeysetOrder(positions, current) {
173
+ let previous = current;
174
+ for (const position of positions) {
175
+ if (previous && compareTimes(position, previous) < 0) return false;
176
+ previous = position;
177
+ }
178
+ return true;
179
+ }
180
+ /** Whether two positions are the same (time, exact time and id). */
181
+ function sameCursor(a, b) {
182
+ if (a === null || b === null) return a === b;
183
+ return a.time.getTime() === b.time.getTime() && a.id === b.id && a.exact === b.exact;
184
+ }
185
+ function rowPosition(row, cursorField, idField) {
186
+ if (!row) return null;
187
+ const exactRaw = row[ROW_EXACT_CURSOR_KEY];
188
+ const exact = typeof exactRaw === "string" ? exactRaw : void 0;
189
+ const raw = exact ?? row["__clivly_row_cursor__"] ?? row[cursorField];
190
+ if (raw === null || raw === void 0) return null;
191
+ const time = raw instanceof Date ? raw : new Date(String(raw));
192
+ if (Number.isNaN(time.getTime())) return null;
193
+ const idRaw = row[idField];
194
+ return {
195
+ time,
196
+ id: idRaw === null || idRaw === void 0 ? "" : String(idRaw),
197
+ ...exact === void 0 ? {} : { exact }
198
+ };
199
+ }
137
200
  function idOnlyCursor(rows, idField, current) {
138
201
  const raw = rows.at(-1)?.[idField];
139
202
  if (raw === null || raw === void 0) return current;
@@ -142,6 +205,17 @@ function idOnlyCursor(rows, idField, current) {
142
205
  time: /* @__PURE__ */ new Date(0)
143
206
  };
144
207
  }
208
+ /**
209
+ * Where `source` stands after reading `rows`. A `full`-mode source (no change
210
+ * column) is positioned by its last row's id; any other by its last row's
211
+ * `(cursorField, idField)`. Every reader of a source's pages (the
212
+ * delta and full sync loops and the delete check's id listing) goes through
213
+ * here, so an id-only source can never be read as if its id were a time.
214
+ */
215
+ function advanceCursor(source, rows, current) {
216
+ const idField = source.idField ?? DEFAULT_ID_FIELD;
217
+ return source.mode === "full" ? idOnlyCursor(rows, idField, current) : nextCursor(rows, source.cursorField, idField, current);
218
+ }
145
219
  const CREATED_AT_CANDIDATES = [
146
220
  "created_at",
147
221
  "createdAt",
@@ -168,7 +242,7 @@ function sourceTimeFields(source, rows) {
168
242
  function toWireCursor(cursor) {
169
243
  return {
170
244
  id: cursor.id,
171
- time: cursor.time.toISOString()
245
+ time: cursor.exact ?? cursor.time.toISOString()
172
246
  };
173
247
  }
174
248
  /**
@@ -183,7 +257,11 @@ function parseWireCursors(value) {
183
257
  const { id, time } = raw;
184
258
  if (typeof id !== "string" || typeof time !== "string") continue;
185
259
  const parsed = new Date(time);
186
- if (!Number.isNaN(parsed.getTime())) out[entity] = {
260
+ if (!Number.isNaN(parsed.getTime())) out[entity] = isExactCursorTime(time) ? {
261
+ id,
262
+ time: parsed,
263
+ exact: time
264
+ } : {
187
265
  id,
188
266
  time: parsed
189
267
  };
@@ -199,7 +277,6 @@ function cursorReport(source, cursor, report) {
199
277
  async function syncSource(args) {
200
278
  const { source, path, since, batchSize, push, objectType, maxRows } = args;
201
279
  const reportCursor = args.reportCursor ?? true;
202
- const idField = source.idField ?? DEFAULT_ID_FIELD;
203
280
  let cursor = since;
204
281
  let pushed = 0;
205
282
  const resumedFrom = since === null ? null : since.time.toISOString();
@@ -210,7 +287,7 @@ async function syncSource(args) {
210
287
  });
211
288
  if (rows.length === 0) break;
212
289
  const capped = maxRows === void 0 ? rows : rows.slice(0, maxRows);
213
- const next = nextCursor(capped, source.cursorField, idField, cursor);
290
+ const next = advanceCursor(source, capped, cursor);
214
291
  if (!await push(path, {
215
292
  source: pushSourceOf(source),
216
293
  rows: capped,
@@ -226,8 +303,13 @@ async function syncSource(args) {
226
303
  ok: false
227
304
  };
228
305
  pushed += capped.length;
306
+ const stalled = sameCursor(next, cursor);
229
307
  cursor = next;
230
308
  if (maxRows !== void 0 || rows.length < batchSize) break;
309
+ if (stalled) {
310
+ console.warn(`[clivly] sync of "${source.entity}" stopped: a full page of ${rows.length} rows did not move its position. Check that fetchPage pages after \`since\` in (${source.cursorField}, id) order and that ${source.cursorField} holds readable times.`);
311
+ break;
312
+ }
231
313
  }
232
314
  return {
233
315
  pushed,
@@ -235,10 +317,24 @@ async function syncSource(args) {
235
317
  ok: true
236
318
  };
237
319
  }
320
+ const PUSH_BODY_LIMIT_MB = 10;
321
+ const BYTES_PER_MB = 1048576;
322
+ const PUSH_WARN_BYTES = 9 * BYTES_PER_MB;
323
+ const SIZE_SAMPLE_ROWS = 200;
324
+ const utf8 = new TextEncoder();
325
+ function estimatedJsonBytes(rows) {
326
+ const sample = rows.slice(0, SIZE_SAMPLE_ROWS);
327
+ return utf8.encode(JSON.stringify(sample)).length / sample.length * rows.length;
328
+ }
329
+ function warnIfNearPushLimit(entity, rows) {
330
+ const bytes = estimatedJsonBytes(rows);
331
+ if (bytes < PUSH_WARN_BYTES) return;
332
+ const mb = (bytes / BYTES_PER_MB).toFixed(1);
333
+ console.warn(`[clivly] full sync of "${entity}" is about ${mb} MB for ${rows.length} rows, one push body, and Clivly refuses a push over ${PUSH_BODY_LIMIT_MB} MB (413). Give the source an updated_at cursor so it syncs as deltas, or read fewer columns. For the Supabase auth.users + public.profiles contact, add an updated_at column (with a moddatetime trigger) to public.profiles, or skip the join: supabaseContactSource(executor, schema, { joinProfiles: false }) in clivly.config.ts, or createSupabaseClivly({ ..., contact: { table: "auth.users", joinProfiles: false } }) in the Edge Function.`);
334
+ }
238
335
  async function fullSyncSource(args) {
239
336
  const { source, path, batchSize, push, objectType } = args;
240
337
  const reportCursor = args.reportCursor ?? true;
241
- const idField = source.idField ?? DEFAULT_ID_FIELD;
242
338
  const all = [];
243
339
  let cursor = null;
244
340
  for (;;) {
@@ -248,16 +344,25 @@ async function fullSyncSource(args) {
248
344
  });
249
345
  if (rows.length === 0) break;
250
346
  all.push(...rows);
251
- const next = source.mode === "full" ? idOnlyCursor(rows, idField, cursor) : nextCursor(rows, source.cursorField, idField, cursor);
252
- const stalled = next !== null && cursor !== null && next.time.getTime() === cursor.time.getTime() && next.id === cursor.id;
347
+ const next = advanceCursor(source, rows, cursor);
348
+ const stalled = sameCursor(next, cursor);
253
349
  cursor = next;
254
- if (rows.length < batchSize || stalled) break;
350
+ if (rows.length < batchSize) break;
351
+ if (stalled) {
352
+ console.warn(`[clivly] full sync of "${source.entity}" stopped and pushed nothing: a full page of ${rows.length} rows did not move its position. Check that fetchPage pages after \`since\` in (${source.cursorField}, id) order and that ${source.cursorField} holds readable times.`);
353
+ return {
354
+ pushed: 0,
355
+ cursor: null,
356
+ ok: false
357
+ };
358
+ }
255
359
  }
256
360
  if (all.length === 0) return {
257
361
  pushed: 0,
258
362
  cursor: null,
259
363
  ok: true
260
364
  };
365
+ warnIfNearPushLimit(source.entity, all);
261
366
  const ok = await push(path, {
262
367
  source: pushSourceOf(source),
263
368
  rows: all,
@@ -274,116 +379,4 @@ async function fullSyncSource(args) {
274
379
  ok
275
380
  };
276
381
  }
277
- // ../sdk/src/projection-guard.ts
278
- /**
279
- * Tables auth libraries keep live credentials in. Whole-table: their secrets
280
- * sit in columns with generic names (`token`, `value`) that a column rule
281
- * cannot single out. `user`, `member` and `organization` are not here — they
282
- * are legitimate contact and company sources.
283
- */
284
- const CREDENTIAL_TABLES = /* @__PURE__ */ new Set([
285
- "session",
286
- "verification",
287
- "two_factor",
288
- "twofactor",
289
- "passkey",
290
- "apikey",
291
- "api_key",
292
- "jwks"
293
- ]);
294
- const BASE_ALIAS = "base";
295
- const AUTH_USERS_ALLOWED = AUTH_USERS_COLUMNS;
296
- /**
297
- * Supabase's `auth` schema: only `auth.users`, and only its allowlisted
298
- * columns. `allowSensitive` never widens this.
299
- */
300
- function authTableError(table) {
301
- return authTableKind(table) === "other" ? `Table "${table}" is in Supabase's auth schema and is never synced; only auth.users is readable.` : null;
302
- }
303
- function normalise(name) {
304
- return name.toLowerCase().replaceAll("-", "_");
305
- }
306
- /** Every (table, column) a projection reads, with join aliases resolved. */
307
- function readColumns(projection) {
308
- const tableOf = /* @__PURE__ */ new Map([[BASE_ALIAS, projection.baseTable]]);
309
- for (const join of projection.joins) tableOf.set(join.key, join.table);
310
- const refs = [];
311
- for (const join of projection.joins) for (const condition of join.on) refs.push(condition.left, condition.right);
312
- for (const binding of Object.values(projection.fieldBindings)) refs.push(binding.from);
313
- const { identity } = projection;
314
- if (identity.kind === "column") refs.push(identity.from);
315
- else if (identity.kind === "composite") refs.push(...identity.parts);
316
- else if (identity.column) refs.push({
317
- table: BASE_ALIAS,
318
- column: identity.column
319
- });
320
- return refs.map((ref) => ({
321
- table: tableOf.get(ref.table) ?? ref.table,
322
- column: ref.column
323
- }));
324
- }
325
- function referencedTables(projection) {
326
- return [projection.baseTable, ...projection.joins.map((join) => join.table)];
327
- }
328
- /** Thrown where a projection is refused outside the route-level checks. */
329
- var ProjectionRefusedError = class extends Error {
330
- reasons;
331
- constructor(reasons) {
332
- super(`projection refused: ${reasons.join("; ")}`);
333
- this.name = "ProjectionRefusedError";
334
- this.reasons = reasons;
335
- }
336
- };
337
- /**
338
- * Only the unconditional Supabase `auth.*` rule: no other auth table, and only
339
- * the allowlisted `auth.users` columns. No policy can widen it, so it needs no
340
- * options and the raw-SQL sources can enforce it on their own.
341
- */
342
- function authExposureErrors(projection) {
343
- const errors = [];
344
- for (const table of referencedTables(projection)) {
345
- const authError = authTableError(table);
346
- if (authError) errors.push(authError);
347
- }
348
- for (const { table, column } of readColumns(projection)) if (authTableKind(table) === "users" && !AUTH_USERS_ALLOWED.includes(column)) errors.push(`Column "${table}.${column}" is not exposed; auth.users only exposes ${AUTH_USERS_COLUMNS.join(", ")}.`);
349
- return [...new Set(errors)];
350
- }
351
- /** Why this projection may not run here; empty when it may. */
352
- function projectionExposureErrors(projection, policy = {}) {
353
- const allowed = new Set((policy.allowSensitive ?? []).map(normalise));
354
- const errors = [];
355
- for (const table of referencedTables(projection)) {
356
- const authError = authTableError(table);
357
- if (authError) errors.push(authError);
358
- if (CREDENTIAL_TABLES.has(normalise(table)) && !allowed.has(normalise(`${table}.*`))) errors.push(`Table "${table}" holds credentials and is never synced.`);
359
- if (policy.tables && !(table in policy.tables)) errors.push(`Table "${table}" is not in this app's exposure.tables allowlist.`);
360
- }
361
- for (const { table, column } of readColumns(projection)) {
362
- const ref = `${table}.${column}`;
363
- if (authTableKind(table) === "users" && !AUTH_USERS_ALLOWED.includes(column)) {
364
- errors.push(`Column "${ref}" is not exposed; auth.users only exposes ${AUTH_USERS_COLUMNS.join(", ")}.`);
365
- continue;
366
- }
367
- if (isSensitiveColumn(column) && !allowed.has(normalise(ref))) errors.push(`Column "${ref}" looks like a credential and is never synced. List it in exposure.allowSensitive if it is safe.`);
368
- const columns = policy.tables?.[table];
369
- if (Array.isArray(columns) && !columns.includes(column)) errors.push(`Column "${ref}" is not in this app's exposure.tables allowlist.`);
370
- }
371
- return [...new Set(errors)];
372
- }
373
- /** Drop credential columns, and columns outside the allowlist, from a raw-row preview. */
374
- function exposableColumns(table, columns, policy = {}) {
375
- const allowed = new Set((policy.allowSensitive ?? []).map(normalise));
376
- const result = /* @__PURE__ */ new Set();
377
- const authKind = authTableKind(table);
378
- if (authKind === "other") return result;
379
- if (CREDENTIAL_TABLES.has(normalise(table)) && !allowed.has(normalise(`${table}.*`)) || policy.tables !== void 0 && !(table in policy.tables)) return result;
380
- const listed = policy.tables?.[table];
381
- for (const column of columns) {
382
- if (authKind === "users" && !AUTH_USERS_ALLOWED.includes(column)) continue;
383
- if (isSensitiveColumn(column) && !allowed.has(normalise(`${table}.${column}`))) continue;
384
- if (Array.isArray(listed) && !listed.includes(column)) continue;
385
- result.add(column);
386
- }
387
- return result;
388
- }
389
- export { AUTH_USERS_META_KEYS as _, ROW_CURSOR_KEY as a, isAnonymousFilter as b, parseWireCursors as c, toWireCursor as d, customPushSource as f, AUTH_USERS_COLUMNS as g, resolveEntitySource as h, projectionExposureErrors as i, sourceTimeFields as l, pushSourceOf as m, authExposureErrors as n, fullSyncSource as o, expectedSourceKey as p, exposableColumns as r, nextCursor as s, ProjectionRefusedError as t, syncSource as u, AUTH_USERS_TABLE as v, authTableKind as y };
382
+ export { markAnonymousColumn as C, isAnonymousFilter as S, AUTH_USERS_META_KEYS as _, isExactCursorTime as a, authTableKind as b, sourceTimeFields as c, customPushSource as d, expectedSourceKey as f, AUTH_USERS_COLUMNS as g, DRIZZLE_META as h, fullSyncSource as i, syncSource as l, resolveEntitySource as m, ROW_EXACT_CURSOR_KEY as n, isValidIsoTime as o, pushSourceOf as p, advanceCursor as r, parseWireCursors as s, ROW_CURSOR_KEY as t, toWireCursor as u, AUTH_USERS_TABLE as v, filtersAnonymous as x, IS_ANONYMOUS_COLUMN as y };
@@ -7,6 +7,13 @@ interface DrizzleSourceMeta {
7
7
  /** Schema-v2 typed column metadata derived from the Drizzle table. */
8
8
  columnsMeta?: DiscoveredColumn[];
9
9
  cursorField: string;
10
+ /**
11
+ * Columns of the pushed rows that do not come from `tableName` (a joined
12
+ * table's, or one the SDK computes), so that table's own column rules,
13
+ * such as the `auth.users` allowlist, do not apply to them. The source's
14
+ * query already decides what they hold.
15
+ */
16
+ derivedColumns?: string[];
10
17
  idField: string;
11
18
  /** Which source builder attached this: `fromDrizzle` (default) or `fromSql`. */
12
19
  kind?: "drizzle" | "sql";
@@ -52,7 +59,14 @@ interface NamespaceIntrospector {
52
59
  * that set `introspector` for the "Namespace reachable" check gains preview
53
60
  * without touching a line.
54
61
  */
55
- runProjection?(projection: ProjectionMapping, opts: {
62
+ runProjection?(projection: ProjectionMapping,
63
+ /**
64
+ * `basePkColumn` is the base table's primary key from local discovery,
65
+ * for a `base_pk` identity that names no column. The same value the
66
+ * sync path resolves, so preview and sync key rows alike.
67
+ */
68
+ opts: {
69
+ basePkColumn?: string;
56
70
  limit: number;
57
71
  }): Promise<Record<string, unknown>[]>;
58
72
  /** Prove a table is genuinely selectable (SELECT ... LIMIT 1). Throws if unreachable/denied. */
@@ -286,8 +300,8 @@ interface ClivlySDKConfig {
286
300
  */
287
301
  path?: string;
288
302
  /**
289
- * Signing secret (`whsec_…`) issued by Clivly under Integrations → Remote
290
- * sync. Required: without it `createClivlyHandler()` refuses every request
303
+ * Signing secret (`whsec_…`) issued by Clivly under Connections → Setup →
304
+ * "Clivly can start a sync". Required: without it `createClivlyHandler()` refuses every request
291
305
  * (403 `signature_required`), including Clivly's own "Run sync". With it,
292
306
  * any request that isn't validly signed is rejected.
293
307
  */
@@ -420,6 +434,11 @@ interface ClivlyConnectResult {
420
434
  workspace?: IntegrationState | null;
421
435
  }
422
436
  interface SyncCursor {
437
+ /**
438
+ * The cursor at the database's precision (`YYYY-MM-DDTHH:MM:SS.ffffffZ`),
439
+ * when the source reads it. `time` is that value cut to the millisecond.
440
+ */
441
+ exact?: string;
423
442
  /** The row's id, breaking ties when timestamps collide. */
424
443
  id: string;
425
444
  /** The row's cursor-field value (typically `updated_at`). */
@@ -434,6 +453,17 @@ interface SyncSource {
434
453
  createdAtField?: string;
435
454
  cursorField: string;
436
455
  entity: string;
456
+ /**
457
+ * Rows ordered by id alone, after `afterId` when given. The daily delete
458
+ * check lists IDs with it when present: a listing paged on the change
459
+ * cursor misses a row whose position moves backwards mid-listing (a
460
+ * deleted profile lowers the Supabase join's `greatest`), and a missed ID
461
+ * is archived. Set by `fromSql` and `fromSqlProjection`.
462
+ */
463
+ fetchIdPage?(args: {
464
+ afterId: string | null;
465
+ limit: number;
466
+ }): Promise<Record<string, unknown>[]>;
437
467
  fetchPage(args: {
438
468
  since: SyncCursor | null;
439
469
  limit: number;
package/vite.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { c as ClivlySDK } from "./types-UR-tT4c1.cjs";
1
+ import { c as ClivlySDK } from "./types-CzL7lUH9.cjs";
2
2
  import { Plugin } from "vite";
3
3
  export interface ClivlyViteOptions {
4
4
  /** Log prefix for Clivly's boot lines. Defaults to "clivly". */
package/vite.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { l as ClivlySDK } from "./namespace-probe--GvxJ06J.mjs";
1
+ import { l as ClivlySDK } from "./namespace-probe-CUR2zG2l.mjs";
2
2
  import { Plugin } from "vite";
3
3
  export interface ClivlyViteOptions {
4
4
  /** Log prefix for Clivly's boot lines. Defaults to "clivly". */
@@ -1,200 +0,0 @@
1
- const require_projection_guard = require("./projection-guard-D8VUhCz7.cjs");
2
- // ../sdk/src/sql/postgres-introspection.ts
3
- /**
4
- * POSTGRES-ONLY introspection SQL. Kept apart from `discover.ts` so a MySQL
5
- * dialect can supply its own strings without touching the assembly logic.
6
- */
7
- const PG_CURRENT_SCHEMA_SQL = "select current_schema() as schema_name";
8
- /** Base tables and their columns, in declaration order. `$1` = text[] schemas. */
9
- const PG_COLUMNS_SQL = `
10
- select c.table_schema as schema_name,
11
- c.table_name as table_name,
12
- c.column_name as column_name,
13
- c.data_type as data_type,
14
- c.udt_name as udt_name,
15
- c.character_maximum_length as char_length,
16
- c.is_nullable as is_nullable
17
- from information_schema.columns c
18
- join information_schema.tables t
19
- on t.table_schema = c.table_schema
20
- and t.table_name = c.table_name
21
- and t.table_type = 'BASE TABLE'
22
- where c.table_schema = any($1::text[])
23
- order by c.table_schema, c.table_name, c.ordinal_position`;
24
- /**
25
- * Every full (non-partial, non-expression) unique index, which covers primary
26
- * keys and unique constraints alike. Columns come back in key order.
27
- */
28
- const PG_UNIQUE_KEYS_SQL = `
29
- select n.nspname as schema_name,
30
- t.relname as table_name,
31
- i.indisprimary as is_primary,
32
- (select array_agg(a.attname::text order by k.ord)
33
- from unnest(i.indkey::int2[]) with ordinality as k(attnum, ord)
34
- join pg_attribute a on a.attrelid = t.oid and a.attnum = k.attnum) as columns
35
- from pg_index i
36
- join pg_class t on t.oid = i.indrelid
37
- join pg_namespace n on n.oid = t.relnamespace
38
- where n.nspname = any($1::text[])
39
- and i.indisunique
40
- and i.indpred is null
41
- and i.indexprs is null
42
- order by n.nspname, t.relname, i.indisprimary desc, i.indexrelid`;
43
- /** Foreign keys, one row per constraint with both column lists in key order. */
44
- const PG_FOREIGN_KEYS_SQL = `
45
- select n.nspname as schema_name,
46
- t.relname as table_name,
47
- fn.nspname as foreign_schema,
48
- ft.relname as foreign_table,
49
- (select array_agg(a.attname::text order by k.ord)
50
- from unnest(c.conkey) with ordinality as k(attnum, ord)
51
- join pg_attribute a on a.attrelid = c.conrelid and a.attnum = k.attnum) as columns,
52
- (select array_agg(a.attname::text order by k.ord)
53
- from unnest(c.confkey) with ordinality as k(attnum, ord)
54
- join pg_attribute a on a.attrelid = c.confrelid and a.attnum = k.attnum) as foreign_columns
55
- from pg_constraint c
56
- join pg_class t on t.oid = c.conrelid
57
- join pg_namespace n on n.oid = t.relnamespace
58
- join pg_class ft on ft.oid = c.confrelid
59
- join pg_namespace fn on fn.oid = ft.relnamespace
60
- where c.contype = 'f'
61
- and n.nspname = any($1::text[])`;
62
- // ../sdk/src/sql/discover.ts
63
- const [AUTH_SCHEMA = "auth", AUTH_USERS_NAME = "users"] = require_projection_guard.AUTH_USERS_TABLE.split(".");
64
- /** The app-ID store Clivly itself writes; never a host business table. */
65
- const APP_ID_TABLE = "crm_clivly_app";
66
- const key = (schema, name) => `${schema}\0${name}`;
67
- const asString = (value) => String(value);
68
- const asStrings = (value) => Array.isArray(value) ? value.map(asString) : [];
69
- const LEADING_UNDERSCORE = /^_/;
70
- /**
71
- * Normalise information_schema's type names to the vocabulary Drizzle's
72
- * `getSQLType()` emits, so core's type checks (e.g. the text-typed composite
73
- * identity guard) treat both discovery paths the same.
74
- */
75
- function columnType(row) {
76
- const dataType = asString(row.data_type);
77
- const udt = asString(row.udt_name);
78
- const length = row.char_length === null || row.char_length === void 0 ? "" : `(${asString(row.char_length)})`;
79
- switch (dataType) {
80
- case "character varying": return `varchar${length}`;
81
- case "character": return `char${length}`;
82
- case "USER-DEFINED": return udt;
83
- case "ARRAY": return `${udt.replace(LEADING_UNDERSCORE, "")}[]`;
84
- default: return dataType;
85
- }
86
- }
87
- function makeScope(defaultSchema, requested, includeAuth) {
88
- const allowedAuth = new Set(require_projection_guard.AUTH_USERS_COLUMNS);
89
- return {
90
- allowedAuth,
91
- defaultSchema,
92
- qualified: ({ schema, name }) => schema === defaultSchema ? name : `${schema}.${name}`,
93
- visible(schema, name) {
94
- if (name === APP_ID_TABLE) return false;
95
- if (schema === AUTH_SCHEMA) return includeAuth && name === AUTH_USERS_NAME;
96
- return requested.includes(schema);
97
- },
98
- columnAllowed: (schema, column) => schema !== AUTH_SCHEMA || allowedAuth.has(column)
99
- };
100
- }
101
- function collectForeignKeys(rows, scope) {
102
- const byColumn = /* @__PURE__ */ new Map();
103
- for (const row of rows) {
104
- const schema = asString(row.schema_name);
105
- const name = asString(row.table_name);
106
- const foreign = {
107
- schema: asString(row.foreign_schema),
108
- name: asString(row.foreign_table)
109
- };
110
- if (!(scope.visible(schema, name) && scope.visible(foreign.schema, foreign.name))) continue;
111
- const foreignColumns = asStrings(row.foreign_columns);
112
- asStrings(row.columns).forEach((column, index) => {
113
- const foreignColumn = foreignColumns[index];
114
- if (foreignColumn && scope.columnAllowed(foreign.schema, foreignColumn)) byColumn.set(`${key(schema, name)}\0${column}`, {
115
- table: scope.qualified(foreign),
116
- column: foreignColumn
117
- });
118
- });
119
- }
120
- return byColumn;
121
- }
122
- function keyId(columns) {
123
- return [...columns].sort().join("\0");
124
- }
125
- function collectUniqueKeys(rows, scope) {
126
- const byTable = /* @__PURE__ */ new Map();
127
- const primary = /* @__PURE__ */ new Set();
128
- for (const row of rows) {
129
- const schema = asString(row.schema_name);
130
- const name = asString(row.table_name);
131
- const columns = asStrings(row.columns);
132
- if (!(scope.visible(schema, name) && columns.length > 0 && columns.every((c) => scope.columnAllowed(schema, c)))) continue;
133
- const tableKey = key(schema, name);
134
- const list = byTable.get(tableKey) ?? [];
135
- if (!list.some((existing) => keyId(existing) === keyId(columns))) list.push(columns);
136
- byTable.set(tableKey, list);
137
- if (row.is_primary === true) for (const column of columns) primary.add(`${tableKey}\0${column}`);
138
- }
139
- return {
140
- byTable,
141
- primary
142
- };
143
- }
144
- /**
145
- * The raw-SQL twin of `discoverFromDrizzle`: reads Postgres catalogs and
146
- * returns the same `DiscoveredSchemaTable[]` shape. Names are unqualified in
147
- * the default schema and `schema.table` elsewhere. `auth.users` is reported
148
- * with only its allowlisted columns; every other `auth.*` table is omitted.
149
- */
150
- async function discoverFromSql(executor, opts = {}) {
151
- const [current] = await executor.query(PG_CURRENT_SCHEMA_SQL);
152
- const defaultSchema = asString(current?.schema_name ?? "public");
153
- const requested = opts.schemas ?? [defaultSchema];
154
- const schemas = [.../* @__PURE__ */ new Set([...requested, AUTH_SCHEMA])];
155
- const [columnRows, uniqueRows, fkRows] = await Promise.all([
156
- executor.query(PG_COLUMNS_SQL, [schemas]),
157
- executor.query(PG_UNIQUE_KEYS_SQL, [schemas]),
158
- executor.query(PG_FOREIGN_KEYS_SQL, [schemas])
159
- ]);
160
- const authExists = columnRows.some((row) => row.schema_name === AUTH_SCHEMA && row.table_name === AUTH_USERS_NAME);
161
- const scope = makeScope(defaultSchema, requested, (opts.includeAuthUsers ?? true) && authExists);
162
- const fkByColumn = collectForeignKeys(fkRows, scope);
163
- const { byTable, primary } = collectUniqueKeys(uniqueRows, scope);
164
- const tables = /* @__PURE__ */ new Map();
165
- for (const row of columnRows) {
166
- const schema = asString(row.schema_name);
167
- const name = asString(row.table_name);
168
- const column = asString(row.column_name);
169
- if (!(scope.visible(schema, name) && scope.columnAllowed(schema, column))) continue;
170
- const tableKey = key(schema, name);
171
- const table = tables.get(tableKey) ?? {
172
- name: scope.qualified({
173
- schema,
174
- name
175
- }),
176
- columns: [],
177
- columnsMeta: [],
178
- uniqueConstraints: byTable.get(tableKey) ?? []
179
- };
180
- tables.set(tableKey, table);
181
- const references = fkByColumn.get(`${tableKey}\0${column}`);
182
- const meta = {
183
- name: column,
184
- type: columnType(row),
185
- nullable: row.is_nullable === "YES",
186
- isPrimaryKey: primary.has(`${tableKey}\0${column}`),
187
- isForeignKey: references !== void 0,
188
- ...references ? { references } : {}
189
- };
190
- table.columns.push(column);
191
- table.columnsMeta?.push(meta);
192
- }
193
- return [...tables.values()];
194
- }
195
- Object.defineProperty(exports, "discoverFromSql", {
196
- enumerable: true,
197
- get: function() {
198
- return discoverFromSql;
199
- }
200
- });