clivly 0.24.0-next.1 → 0.25.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 (72) hide show
  1. package/README.md +34 -7
  2. package/{app-id-DcQ4u1c8.cjs → app-id-C2F25WhK.cjs} +1 -1
  3. package/{app-id-5cB6yioz.mjs → app-id-CMMadyIC.mjs} +1 -1
  4. package/auth-better-auth.cjs +51 -0
  5. package/auth-better-auth.d.cts +51 -1
  6. package/auth-better-auth.d.mts +51 -1
  7. package/auth-better-auth.mjs +51 -1
  8. package/auth-clerk.cjs +53 -0
  9. package/auth-clerk.d.cts +12 -1
  10. package/auth-clerk.d.mts +12 -1
  11. package/auth-clerk.mjs +53 -1
  12. package/auth-supabase.cjs +10 -0
  13. package/auth-supabase.d.cts +17 -1
  14. package/auth-supabase.d.mts +17 -1
  15. package/auth-supabase.mjs +10 -1
  16. package/auth-webhook-3if7gY6b.mjs +162 -0
  17. package/auth-webhook-BihEUc9C.cjs +197 -0
  18. package/auth-webhook-DKdaCZrW.d.cts +30 -0
  19. package/auth-webhook-DKdaCZrW.d.mts +30 -0
  20. package/auth-workos.cjs +43 -0
  21. package/auth-workos.d.cts +12 -1
  22. package/auth-workos.d.mts +12 -1
  23. package/auth-workos.mjs +43 -1
  24. package/drizzle.cjs +264 -17
  25. package/drizzle.d.cts +23 -3
  26. package/drizzle.d.mts +23 -3
  27. package/drizzle.mjs +265 -19
  28. package/{from-sql-CFgXkCe2.cjs → from-sql-Dw2ipynp.cjs} +7 -1
  29. package/{from-sql-S8dSvU-e.d.cts → from-sql-MyPE5elx.d.cts} +1 -1
  30. package/{from-sql-CpGP7K3J.d.mts → from-sql-YW6LfdVK.d.mts} +1 -1
  31. package/{from-sql-BD7gR4bC.mjs → from-sql-kqs9CbQ-.mjs} +7 -1
  32. package/{index-CIupXz_w.d.cts → index-B4kWWHYm.d.cts} +2 -2
  33. package/{index-BoemTWH4.d.mts → index-CKElWhvq.d.mts} +2 -2
  34. package/index.cjs +3354 -2829
  35. package/index.d.cts +3 -3
  36. package/index.d.mts +3 -3
  37. package/index.mjs +3354 -2829
  38. package/{introspector-5w2x89RD.mjs → introspector-B1S7qmvy.mjs} +4 -4
  39. package/{introspector-DT_Ma59k.cjs → introspector-DRmEXDai.cjs} +4 -4
  40. package/kysely.cjs +163 -2
  41. package/kysely.d.cts +16 -3
  42. package/kysely.d.mts +16 -3
  43. package/kysely.mjs +163 -3
  44. package/{namespace-probe-CUR2zG2l.d.mts → namespace-probe-LKC4OU5X.d.mts} +54 -19
  45. package/package.json +1 -1
  46. package/{projection-guard-DOt_nbGn.mjs → projection-guard-CADdAdzg.mjs} +1 -1
  47. package/{projection-guard-C70l5U24.cjs → projection-guard-yhVTvx37.cjs} +1 -1
  48. package/sdk.cjs +1 -1
  49. package/sdk.d.cts +1 -1
  50. package/sdk.d.mts +1 -1
  51. package/sdk.mjs +1 -1
  52. package/sql.cjs +5 -5
  53. package/sql.d.cts +2 -2
  54. package/sql.d.mts +2 -2
  55. package/sql.mjs +5 -5
  56. package/{src-CZIdwwI2.cjs → src-BQasv4EL.cjs} +368 -38
  57. package/{src-tFhC1Ru2.mjs → src-CAn-zrEl.mjs} +368 -38
  58. package/{supabase-contact-BXQ0nnLq.cjs → supabase-contact-0GmBVpiQ.cjs} +24 -15
  59. package/{supabase-contact-3ke1KKUs.mjs → supabase-contact-D-oDC4Qk.mjs} +24 -15
  60. package/supabase.cjs +39 -9
  61. package/supabase.d.cts +3 -2
  62. package/supabase.d.mts +3 -2
  63. package/supabase.mjs +39 -9
  64. package/{sync-Q0O-2kFI.mjs → sync-CnWT5juF.mjs} +65 -5
  65. package/{sync-CdA9dgZz.cjs → sync-R0iVlooB.cjs} +94 -4
  66. package/track-writes-4yyZbTZX.d.cts +17 -0
  67. package/track-writes-BJSWg8wg.d.mts +17 -0
  68. package/track-writes-BnZAig2Y.mjs +77 -0
  69. package/track-writes-C22_e_W-.cjs +112 -0
  70. package/{types-CzL7lUH9.d.cts → types-BPG4l-oM.d.cts} +53 -18
  71. package/vite.d.cts +1 -1
  72. package/vite.d.mts +1 -1
@@ -1,8 +1,8 @@
1
1
  import { a as compileProjectionPreview } from "./projection-sql-2joBkLz2.mjs";
2
- import { n as authExposureErrors, t as ProjectionRefusedError } from "./projection-guard-DOt_nbGn.mjs";
3
- import { d as postgresDialect } from "./from-sql-BD7gR4bC.mjs";
4
- import { a as discoverFromSql, i as fromSqlProjection } from "./supabase-contact-3ke1KKUs.mjs";
5
- import { b as authTableKind } from "./sync-Q0O-2kFI.mjs";
2
+ import { n as authExposureErrors, t as ProjectionRefusedError } from "./projection-guard-CADdAdzg.mjs";
3
+ import { d as postgresDialect } from "./from-sql-kqs9CbQ-.mjs";
4
+ import { a as discoverFromSql, i as fromSqlProjection } from "./supabase-contact-D-oDC4Qk.mjs";
5
+ import { T as authTableKind } from "./sync-CnWT5juF.mjs";
6
6
  // ../sdk/src/sql/introspector.ts
7
7
  function assertAuthRule(projection) {
8
8
  const refused = authExposureErrors(projection);
@@ -1,8 +1,8 @@
1
1
  const require_projection_sql = require("./projection-sql-DS5sVTY-.cjs");
2
- const require_projection_guard = require("./projection-guard-C70l5U24.cjs");
3
- const require_from_sql = require("./from-sql-CFgXkCe2.cjs");
4
- const require_supabase_contact = require("./supabase-contact-BXQ0nnLq.cjs");
5
- const require_sync = require("./sync-CdA9dgZz.cjs");
2
+ const require_projection_guard = require("./projection-guard-yhVTvx37.cjs");
3
+ const require_from_sql = require("./from-sql-Dw2ipynp.cjs");
4
+ const require_supabase_contact = require("./supabase-contact-0GmBVpiQ.cjs");
5
+ const require_sync = require("./sync-R0iVlooB.cjs");
6
6
  // ../sdk/src/sql/introspector.ts
7
7
  function assertAuthRule(projection) {
8
8
  const refused = require_projection_guard.authExposureErrors(projection);
package/kysely.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_from_sql = require("./from-sql-CFgXkCe2.cjs");
2
+ const require_track_writes = require("./track-writes-C22_e_W-.cjs");
3
+ const require_from_sql = require("./from-sql-Dw2ipynp.cjs");
3
4
  let kysely = require("kysely");
4
5
  // ../sdk/src/kysely/executor.ts
5
6
  const NOT_POSTGRES_PREFIX = "kyselyExecutor: only Postgres is supported";
@@ -42,7 +43,7 @@ function ensurePostgres(db, raw) {
42
43
  * once per Kysely instance.
43
44
  */
44
45
  function kyselyExecutor(db) {
45
- const raw = db.withoutPlugins();
46
+ const raw = require_track_writes.untracked(db).withoutPlugins();
46
47
  return { async query(text, params) {
47
48
  await ensurePostgres(db, raw);
48
49
  return runRaw(raw, text, params ?? []);
@@ -52,5 +53,165 @@ function kyselyExecutor(db) {
52
53
  function fromKysely(db, opts) {
53
54
  return require_from_sql.fromSql(kyselyExecutor(db), opts);
54
55
  }
56
+ // ../sdk/src/kysely/track-kysely.ts
57
+ const DEFAULT_KEY = "id";
58
+ const PUBLIC_SCHEMA = "public";
59
+ const asNode = (value) => typeof value?.kind === "string" ? value : null;
60
+ const asNodes = (value) => Array.isArray(value) ? value.flatMap((v) => asNode(v) ?? []) : [];
61
+ const nameOf = (identifier) => {
62
+ const name = asNode(identifier)?.name;
63
+ return typeof name === "string" ? name : null;
64
+ };
65
+ /** The table of a plain TableNode; null for an alias or a subquery. */
66
+ function tableOf(value) {
67
+ const table = asNode(value);
68
+ const target = table?.kind === "TableNode" ? asNode(table.table) : null;
69
+ const name = nameOf(target?.identifier);
70
+ const schema = nameOf(target?.schema);
71
+ return name && schema && schema !== PUBLIC_SCHEMA ? `${schema}.${name}` : name;
72
+ }
73
+ /** A column's name, given a ColumnNode or a reference to one. */
74
+ function columnOf(value) {
75
+ const node = asNode(value);
76
+ return node?.kind === "ReferenceNode" ? columnOf(node.column) : nameOf(node?.column);
77
+ }
78
+ const idOfValue = (value) => {
79
+ const node = asNode(value);
80
+ return require_track_writes.trackedId(node?.kind === "ValueNode" ? node.value : value);
81
+ };
82
+ function idsOf(values) {
83
+ const ids = values.map(idOfValue);
84
+ return ids.every((id) => id !== null) ? ids : null;
85
+ }
86
+ const listOf = (value) => {
87
+ const values = asNode(value)?.values;
88
+ return Array.isArray(values) ? values : null;
89
+ };
90
+ function idsOfInsert(node, key) {
91
+ const at = asNodes(node.columns).map(columnOf).indexOf(key);
92
+ const rows = listOf(node.values);
93
+ if (at < 0 || !rows || node.onConflict || node.replace) return null;
94
+ return idsOf(rows.map((row) => listOf(row)?.[at]));
95
+ }
96
+ /** The ids of exactly `key = x` or `key in (x, y)`; null for anything else. */
97
+ function idsOfWhere(where, key) {
98
+ const test = asNode(asNode(where)?.where);
99
+ if (test?.kind !== "BinaryOperationNode" || columnOf(test.leftOperand) !== key) return null;
100
+ const operator = asNode(test.operator)?.operator;
101
+ if (operator === "=") return idsOf([test.rightOperand]);
102
+ const list = operator === "in" ? listOf(test.rightOperand) : null;
103
+ return list && idsOf(list);
104
+ }
105
+ /** Whether `key` comes back under its own name, from the table itself. */
106
+ const returnsKey = (node, key) => asNodes(asNode(node.returning)?.selections).some((selection) => {
107
+ const picked = asNode(selection.selection);
108
+ return picked?.kind === "SelectAllNode" || columnOf(picked) === key;
109
+ });
110
+ function describe(node, keys) {
111
+ const isDelete = node.kind === "DeleteQueryNode";
112
+ const isUpdate = node.kind === "UpdateQueryNode";
113
+ const isInsert = node.kind === "InsertQueryNode";
114
+ let target = node.table;
115
+ if (isInsert) target = node.into;
116
+ else if (isDelete) [target] = asNodes(asNode(node.from)?.froms);
117
+ const table = tableOf(target);
118
+ if (!(table && (isInsert || isUpdate || isDelete))) return null;
119
+ const key = keys[table] ?? DEFAULT_KEY;
120
+ const alone = !(node.joins || node.using || isUpdate && node.from || node.limit || node.top);
121
+ const changesKey = isUpdate && asNodes(node.updates).some((u) => columnOf(u.column) === key);
122
+ let ids = null;
123
+ if (isInsert) ids = idsOfInsert(node, key);
124
+ else if (alone && !changesKey) ids = idsOfWhere(node.where, key);
125
+ return {
126
+ key,
127
+ fromResult: alone && returnsKey(node, key),
128
+ write: {
129
+ table,
130
+ key,
131
+ deleted: isDelete,
132
+ ids: ids ?? [],
133
+ complete: ids !== null
134
+ }
135
+ };
136
+ }
137
+ function withReturnedIds({ fromResult, key, write }, rows) {
138
+ const ids = fromResult && Array.isArray(rows) ? idsOf(rows.map((row) => row[key])) : null;
139
+ return ids ? {
140
+ ...write,
141
+ complete: true,
142
+ ids
143
+ } : write;
144
+ }
145
+ function trackingPlugin(keys, noteActivity, emit) {
146
+ const statements = /* @__PURE__ */ new WeakMap();
147
+ return {
148
+ transformQuery({ node, queryId }) {
149
+ noteActivity();
150
+ try {
151
+ const statement = describe(node, keys);
152
+ if (statement) statements.set(queryId, statement);
153
+ } catch {}
154
+ return node;
155
+ },
156
+ transformResult({ queryId, result }) {
157
+ try {
158
+ const statement = statements.get(queryId);
159
+ if (statement) emit([withReturnedIds(statement, result.rows)]);
160
+ } catch {}
161
+ return Promise.resolve(result);
162
+ }
163
+ };
164
+ }
165
+ const RETRACKED = /* @__PURE__ */ new Set([
166
+ "withPlugin",
167
+ "withoutPlugins",
168
+ "withSchema",
169
+ "withTables"
170
+ ]);
171
+ function trackClient(db, plugin, emit) {
172
+ const queries = db.withPlugin(plugin(emit));
173
+ const trackTransaction = (builder) => new Proxy(builder, { get(target, property) {
174
+ const value = Reflect.get(target, property, target);
175
+ if (typeof value !== "function") return value;
176
+ if (property !== "execute") return (...args) => trackTransaction(value.apply(target, args));
177
+ return async (work) => {
178
+ const held = [];
179
+ const hold = plugin((writes) => held.push(...writes));
180
+ const result = await value.call(target, (tx) => work(tx.withPlugin(hold)));
181
+ emit(held);
182
+ return result;
183
+ };
184
+ } });
185
+ return new Proxy(queries, { get(target, property) {
186
+ if (property === "transaction") return () => trackTransaction(db.transaction());
187
+ if (property === "startTransaction") return db.startTransaction.bind(db);
188
+ if (property === "connection") return () => ({ execute: (work) => db.connection().execute(async (one) => await work(trackClient(one, plugin, emit))) });
189
+ if (RETRACKED.has(property)) {
190
+ const change = Reflect.get(db, property, db);
191
+ return (...args) => trackClient(change.apply(db, args), plugin, emit);
192
+ }
193
+ const value = Reflect.get(target, property, target);
194
+ return typeof value === "function" && property !== "constructor" ? value.bind(target) : value;
195
+ } });
196
+ }
197
+ /**
198
+ * The Kysely twin of `trackDrizzle`: wrap the client once, and every committed
199
+ * insert, update and delete of a mapped table reaches Clivly right away. The
200
+ * SQL, results and errors are the host's own. Raw SQL and controlled
201
+ * transactions (`startTransaction`) are not seen; catch-up or a pull sends
202
+ * those.
203
+ */
204
+ function trackKysely(db, options = {}) {
205
+ if (require_track_writes.isTracked(db)) return db;
206
+ const reporter = require_track_writes.createReporter(options);
207
+ const plugin = (emit) => trackingPlugin(options.keys ?? {}, reporter.noteActivity, emit);
208
+ const tracked = trackClient(db, plugin, (writes) => {
209
+ reporter.noteActivity();
210
+ reporter.report(writes);
211
+ });
212
+ require_track_writes.markTracked(tracked, db);
213
+ return tracked;
214
+ }
55
215
  exports.fromKysely = fromKysely;
56
216
  exports.kyselyExecutor = kyselyExecutor;
217
+ exports.trackKysely = trackKysely;
package/kysely.d.cts CHANGED
@@ -1,5 +1,6 @@
1
- import { i as SqlExecutor, t as FromSqlOptions } from "./from-sql-S8dSvU-e.cjs";
2
- import { b as SyncSource } from "./types-CzL7lUH9.cjs";
1
+ import { i as SqlExecutor, t as FromSqlOptions } from "./from-sql-MyPE5elx.cjs";
2
+ import { x as SyncSource } from "./types-BPG4l-oM.cjs";
3
+ import { t as TrackOptions } from "./track-writes-4yyZbTZX.cjs";
3
4
  import { Kysely } from "kysely";
4
5
  /**
5
6
  * The Kysely methods the adapter uses. Structural on purpose: apps often
@@ -42,4 +43,16 @@ export declare function fromKysely<DB, T extends TableName<DB>>(db: Kysely<DB>,
42
43
  objectType: string;
43
44
  };
44
45
  export declare function fromKysely<DB, T extends TableName<DB>>(db: Kysely<DB>, opts: FromKyselyOptions<DB, T>): SyncSource;
45
- export type { FromKyselyOptions, KyselyQueryRunner };
46
+ interface TrackKyselyOptions extends TrackOptions {
47
+ /** Key columns of tables not keyed by `id`, e.g. `{ accounts: "account_id" }`. */
48
+ keys?: Record<string, string>;
49
+ }
50
+ /**
51
+ * The Kysely twin of `trackDrizzle`: wrap the client once, and every committed
52
+ * insert, update and delete of a mapped table reaches Clivly right away. The
53
+ * SQL, results and errors are the host's own. Raw SQL and controlled
54
+ * transactions (`startTransaction`) are not seen; catch-up or a pull sends
55
+ * those.
56
+ */
57
+ export declare function trackKysely<DB>(db: Kysely<DB>, options?: TrackKyselyOptions): Kysely<DB>;
58
+ export type { FromKyselyOptions, KyselyQueryRunner, TrackKyselyOptions };
package/kysely.d.mts CHANGED
@@ -1,5 +1,6 @@
1
- import { i as SqlExecutor, t as FromSqlOptions } from "./from-sql-CpGP7K3J.mjs";
2
- import { x as SyncSource } from "./namespace-probe-CUR2zG2l.mjs";
1
+ import { i as SqlExecutor, t as FromSqlOptions } from "./from-sql-YW6LfdVK.mjs";
2
+ import { S as SyncSource } from "./namespace-probe-LKC4OU5X.mjs";
3
+ import { t as TrackOptions } from "./track-writes-BJSWg8wg.mjs";
3
4
  import { Kysely } from "kysely";
4
5
  /**
5
6
  * The Kysely methods the adapter uses. Structural on purpose: apps often
@@ -42,4 +43,16 @@ export declare function fromKysely<DB, T extends TableName<DB>>(db: Kysely<DB>,
42
43
  objectType: string;
43
44
  };
44
45
  export declare function fromKysely<DB, T extends TableName<DB>>(db: Kysely<DB>, opts: FromKyselyOptions<DB, T>): SyncSource;
45
- export type { FromKyselyOptions, KyselyQueryRunner };
46
+ interface TrackKyselyOptions extends TrackOptions {
47
+ /** Key columns of tables not keyed by `id`, e.g. `{ accounts: "account_id" }`. */
48
+ keys?: Record<string, string>;
49
+ }
50
+ /**
51
+ * The Kysely twin of `trackDrizzle`: wrap the client once, and every committed
52
+ * insert, update and delete of a mapped table reaches Clivly right away. The
53
+ * SQL, results and errors are the host's own. Raw SQL and controlled
54
+ * transactions (`startTransaction`) are not seen; catch-up or a pull sends
55
+ * those.
56
+ */
57
+ export declare function trackKysely<DB>(db: Kysely<DB>, options?: TrackKyselyOptions): Kysely<DB>;
58
+ export type { FromKyselyOptions, KyselyQueryRunner, TrackKyselyOptions };
package/kysely.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { n as fromSql } from "./from-sql-BD7gR4bC.mjs";
1
+ import { a as trackedId, n as isTracked, o as untracked, r as markTracked, t as createReporter } from "./track-writes-BnZAig2Y.mjs";
2
+ import { n as fromSql } from "./from-sql-kqs9CbQ-.mjs";
2
3
  import { CompiledQuery } from "kysely";
3
4
  // ../sdk/src/kysely/executor.ts
4
5
  const NOT_POSTGRES_PREFIX = "kyselyExecutor: only Postgres is supported";
@@ -41,7 +42,7 @@ function ensurePostgres(db, raw) {
41
42
  * once per Kysely instance.
42
43
  */
43
44
  function kyselyExecutor(db) {
44
- const raw = db.withoutPlugins();
45
+ const raw = untracked(db).withoutPlugins();
45
46
  return { async query(text, params) {
46
47
  await ensurePostgres(db, raw);
47
48
  return runRaw(raw, text, params ?? []);
@@ -51,4 +52,163 @@ function kyselyExecutor(db) {
51
52
  function fromKysely(db, opts) {
52
53
  return fromSql(kyselyExecutor(db), opts);
53
54
  }
54
- export { fromKysely, kyselyExecutor };
55
+ // ../sdk/src/kysely/track-kysely.ts
56
+ const DEFAULT_KEY = "id";
57
+ const PUBLIC_SCHEMA = "public";
58
+ const asNode = (value) => typeof value?.kind === "string" ? value : null;
59
+ const asNodes = (value) => Array.isArray(value) ? value.flatMap((v) => asNode(v) ?? []) : [];
60
+ const nameOf = (identifier) => {
61
+ const name = asNode(identifier)?.name;
62
+ return typeof name === "string" ? name : null;
63
+ };
64
+ /** The table of a plain TableNode; null for an alias or a subquery. */
65
+ function tableOf(value) {
66
+ const table = asNode(value);
67
+ const target = table?.kind === "TableNode" ? asNode(table.table) : null;
68
+ const name = nameOf(target?.identifier);
69
+ const schema = nameOf(target?.schema);
70
+ return name && schema && schema !== PUBLIC_SCHEMA ? `${schema}.${name}` : name;
71
+ }
72
+ /** A column's name, given a ColumnNode or a reference to one. */
73
+ function columnOf(value) {
74
+ const node = asNode(value);
75
+ return node?.kind === "ReferenceNode" ? columnOf(node.column) : nameOf(node?.column);
76
+ }
77
+ const idOfValue = (value) => {
78
+ const node = asNode(value);
79
+ return trackedId(node?.kind === "ValueNode" ? node.value : value);
80
+ };
81
+ function idsOf(values) {
82
+ const ids = values.map(idOfValue);
83
+ return ids.every((id) => id !== null) ? ids : null;
84
+ }
85
+ const listOf = (value) => {
86
+ const values = asNode(value)?.values;
87
+ return Array.isArray(values) ? values : null;
88
+ };
89
+ function idsOfInsert(node, key) {
90
+ const at = asNodes(node.columns).map(columnOf).indexOf(key);
91
+ const rows = listOf(node.values);
92
+ if (at < 0 || !rows || node.onConflict || node.replace) return null;
93
+ return idsOf(rows.map((row) => listOf(row)?.[at]));
94
+ }
95
+ /** The ids of exactly `key = x` or `key in (x, y)`; null for anything else. */
96
+ function idsOfWhere(where, key) {
97
+ const test = asNode(asNode(where)?.where);
98
+ if (test?.kind !== "BinaryOperationNode" || columnOf(test.leftOperand) !== key) return null;
99
+ const operator = asNode(test.operator)?.operator;
100
+ if (operator === "=") return idsOf([test.rightOperand]);
101
+ const list = operator === "in" ? listOf(test.rightOperand) : null;
102
+ return list && idsOf(list);
103
+ }
104
+ /** Whether `key` comes back under its own name, from the table itself. */
105
+ const returnsKey = (node, key) => asNodes(asNode(node.returning)?.selections).some((selection) => {
106
+ const picked = asNode(selection.selection);
107
+ return picked?.kind === "SelectAllNode" || columnOf(picked) === key;
108
+ });
109
+ function describe(node, keys) {
110
+ const isDelete = node.kind === "DeleteQueryNode";
111
+ const isUpdate = node.kind === "UpdateQueryNode";
112
+ const isInsert = node.kind === "InsertQueryNode";
113
+ let target = node.table;
114
+ if (isInsert) target = node.into;
115
+ else if (isDelete) [target] = asNodes(asNode(node.from)?.froms);
116
+ const table = tableOf(target);
117
+ if (!(table && (isInsert || isUpdate || isDelete))) return null;
118
+ const key = keys[table] ?? DEFAULT_KEY;
119
+ const alone = !(node.joins || node.using || isUpdate && node.from || node.limit || node.top);
120
+ const changesKey = isUpdate && asNodes(node.updates).some((u) => columnOf(u.column) === key);
121
+ let ids = null;
122
+ if (isInsert) ids = idsOfInsert(node, key);
123
+ else if (alone && !changesKey) ids = idsOfWhere(node.where, key);
124
+ return {
125
+ key,
126
+ fromResult: alone && returnsKey(node, key),
127
+ write: {
128
+ table,
129
+ key,
130
+ deleted: isDelete,
131
+ ids: ids ?? [],
132
+ complete: ids !== null
133
+ }
134
+ };
135
+ }
136
+ function withReturnedIds({ fromResult, key, write }, rows) {
137
+ const ids = fromResult && Array.isArray(rows) ? idsOf(rows.map((row) => row[key])) : null;
138
+ return ids ? {
139
+ ...write,
140
+ complete: true,
141
+ ids
142
+ } : write;
143
+ }
144
+ function trackingPlugin(keys, noteActivity, emit) {
145
+ const statements = /* @__PURE__ */ new WeakMap();
146
+ return {
147
+ transformQuery({ node, queryId }) {
148
+ noteActivity();
149
+ try {
150
+ const statement = describe(node, keys);
151
+ if (statement) statements.set(queryId, statement);
152
+ } catch {}
153
+ return node;
154
+ },
155
+ transformResult({ queryId, result }) {
156
+ try {
157
+ const statement = statements.get(queryId);
158
+ if (statement) emit([withReturnedIds(statement, result.rows)]);
159
+ } catch {}
160
+ return Promise.resolve(result);
161
+ }
162
+ };
163
+ }
164
+ const RETRACKED = /* @__PURE__ */ new Set([
165
+ "withPlugin",
166
+ "withoutPlugins",
167
+ "withSchema",
168
+ "withTables"
169
+ ]);
170
+ function trackClient(db, plugin, emit) {
171
+ const queries = db.withPlugin(plugin(emit));
172
+ const trackTransaction = (builder) => new Proxy(builder, { get(target, property) {
173
+ const value = Reflect.get(target, property, target);
174
+ if (typeof value !== "function") return value;
175
+ if (property !== "execute") return (...args) => trackTransaction(value.apply(target, args));
176
+ return async (work) => {
177
+ const held = [];
178
+ const hold = plugin((writes) => held.push(...writes));
179
+ const result = await value.call(target, (tx) => work(tx.withPlugin(hold)));
180
+ emit(held);
181
+ return result;
182
+ };
183
+ } });
184
+ return new Proxy(queries, { get(target, property) {
185
+ if (property === "transaction") return () => trackTransaction(db.transaction());
186
+ if (property === "startTransaction") return db.startTransaction.bind(db);
187
+ if (property === "connection") return () => ({ execute: (work) => db.connection().execute(async (one) => await work(trackClient(one, plugin, emit))) });
188
+ if (RETRACKED.has(property)) {
189
+ const change = Reflect.get(db, property, db);
190
+ return (...args) => trackClient(change.apply(db, args), plugin, emit);
191
+ }
192
+ const value = Reflect.get(target, property, target);
193
+ return typeof value === "function" && property !== "constructor" ? value.bind(target) : value;
194
+ } });
195
+ }
196
+ /**
197
+ * The Kysely twin of `trackDrizzle`: wrap the client once, and every committed
198
+ * insert, update and delete of a mapped table reaches Clivly right away. The
199
+ * SQL, results and errors are the host's own. Raw SQL and controlled
200
+ * transactions (`startTransaction`) are not seen; catch-up or a pull sends
201
+ * those.
202
+ */
203
+ function trackKysely(db, options = {}) {
204
+ if (isTracked(db)) return db;
205
+ const reporter = createReporter(options);
206
+ const plugin = (emit) => trackingPlugin(options.keys ?? {}, reporter.noteActivity, emit);
207
+ const tracked = trackClient(db, plugin, (writes) => {
208
+ reporter.noteActivity();
209
+ reporter.report(writes);
210
+ });
211
+ markTracked(tracked, db);
212
+ return tracked;
213
+ }
214
+ export { fromKysely, kyselyExecutor, trackKysely };
@@ -1,5 +1,6 @@
1
- import { R as ProjectionMapping, a as ClivlyEntitiesConfig } from "./entity-config-CXpGowQa.mjs";
2
1
  import { v as IntegrationState } from "./index-DOoX2GgI.mjs";
2
+ import { R as ProjectionMapping, a as ClivlyEntitiesConfig } from "./entity-config-CXpGowQa.mjs";
3
+ import { t as InstantPushOutcome } from "./auth-webhook-DKdaCZrW.mjs";
3
4
  declare const DRIZZLE_META: "__clivly_drizzle_source_meta__";
4
5
  interface DrizzleSourceMeta {
5
6
  /** Drizzle property keys of every column on the source table. */
@@ -199,20 +200,10 @@ interface ClivlySDKConfig {
199
200
  intervalMs?: number;
200
201
  batchSize?: number;
201
202
  /**
202
- * Opt into `pushOne()`/`insertAndPush()` pushing a single changed row to
203
- * Clivly immediately, instead of waiting for the next delta sync. Off by
204
- * default: turning it on changes a write's async failure surface (a push
205
- * can fail independently of the write that triggered it, swallowed and
206
- * left for the next delta sync to catch), which an existing install
207
- * upgrading to a newer `clivly` should opt into deliberately rather than
208
- * inherit silently. Requires a real scheduled delta sync running
209
- * underneath as the safety net for anything the instant push misses (a
210
- * failed push, a raw SQL write, a bulk import) — see
211
- * docs/reviews/2026-09-19-near-real-time-sync-plan.md.
212
- *
213
- * Can also be disabled at runtime without a redeploy via the
214
- * `CLIVLY_INSTANT_PUSH_DISABLED=true` environment variable — the fast
215
- * rollback switch if this misbehaves in production.
203
+ * @deprecated Ignored. Instant push is on for every app. To stop it in an
204
+ * emergency, without a redeploy, set the environment variable
205
+ * `CLIVLY_INSTANT_PUSH_DISABLED=true`. A failed push never fails the write
206
+ * that caused it; the next sync sends the row.
216
207
  */
217
208
  instant?: boolean;
218
209
  /**
@@ -403,6 +394,12 @@ interface SyncSource {
403
394
  createdAtField?: string;
404
395
  cursorField: string;
405
396
  entity: string;
397
+ /**
398
+ * The rows with these ids, exactly as `fetchPage` would return them. Lets
399
+ * `pushById` send a row the moment an auth hook reports it. Set by every
400
+ * built-in source; optional on a hand-written one.
401
+ */
402
+ fetchByIds?(ids: readonly (string | number)[]): Promise<Record<string, unknown>[]>;
406
403
  /**
407
404
  * Rows ordered by id alone, after `afterId` when given. The daily delete
408
405
  * check lists IDs with it when present: a listing paged on the change
@@ -541,7 +538,32 @@ type ClivlyConsentResult = {
541
538
  /** HTTP status; null when Clivly could not be reached. */
542
539
  status: number | null;
543
540
  };
541
+ /** Writes one statement made to one host table. See `tracker.recordWrites`. */
542
+ interface TrackedWrite {
543
+ /** Whether `ids` is every row the statement touched. */
544
+ complete: boolean;
545
+ deleted: boolean;
546
+ ids: readonly (string | number)[];
547
+ /** The column `ids` come from. */
548
+ key: string;
549
+ /** The table, schema-qualified outside the default schema. */
550
+ table: string;
551
+ }
552
+ /** What `trackDrizzle` / `trackKysely` report to. */
553
+ interface ClivlyWriteTracker {
554
+ /** Says the host just used its database, so reading it wakes nothing. */
555
+ noteDatabaseActivity(): void;
556
+ /** Push committed writes to mapped tables. Never throws. */
557
+ recordWrites(writes: readonly TrackedWrite[]): Promise<void>;
558
+ }
544
559
  interface ClivlySDK {
560
+ /**
561
+ * Send what instant push missed: failed pushes now, and at most every 15
562
+ * minutes a delta of every source. Does nothing unless the app used its
563
+ * database in the last minute, so it never wakes one that is asleep. Never
564
+ * reads a whole table, and never throws.
565
+ */
566
+ catchUp(): Promise<void>;
545
567
  /**
546
568
  * Send a single heartbeat and report the outcome richly: `ok`, the HTTP
547
569
  * `status` (null on network failure), a coarse `reason`, whether it's
@@ -637,19 +659,26 @@ interface ClivlySDK {
637
659
  * own state.
638
660
  */
639
661
  ping(): Promise<ClivlyConnectResult>;
662
+ /**
663
+ * Re-read these rows through the entity's source and push them now. For
664
+ * hooks that know only an id (a sign-up). Same contract as `pushOne`. An id
665
+ * the source does not return (filtered out, or not committed yet) is left
666
+ * to the next sync. Resolves to what became of it.
667
+ */
668
+ pushById(entityKey: string, ids: readonly (string | number)[]): Promise<InstantPushOutcome>;
640
669
  /**
641
670
  * Tell Clivly that rows of `entityKey` were deleted, by id, so their CRM
642
671
  * records are archived within a second instead of at the daily delete
643
672
  * check. Clivly archives, never deletes. Same contract as `pushOne`:
644
- * requires `sync.instant`, never throws, never moves the delta cursor.
673
+ * never throws, never moves the delta cursor.
645
674
  * `deleteAndPush` (from `clivly/drizzle`) does the delete and this together.
646
675
  */
647
676
  pushDelete(entityKey: string, ids: readonly (string | number)[]): Promise<void>;
648
677
  /**
649
678
  * Push one row to Clivly immediately, instead of waiting for the next delta
650
679
  * sync — the "instant" half of near-real-time sync (see
651
- * docs/reviews/2026-09-19-near-real-time-sync-plan.md). No-ops unless
652
- * `sync.instant` is set and `CLIVLY_INSTANT_PUSH_DISABLED` is unset.
680
+ * docs/reviews/2026-09-19-near-real-time-sync-plan.md). On for every app;
681
+ * no-ops only while `CLIVLY_INSTANT_PUSH_DISABLED` is set.
653
682
  *
654
683
  * `entityKey` is a key of `config.entities.entities` (the same key
655
684
  * `clivly.config.ts` declares the entity under), not a table name — an
@@ -716,6 +745,12 @@ interface ClivlySDK {
716
745
  mode?: SyncMode;
717
746
  runId?: string;
718
747
  }): Promise<void>;
748
+ readonly tracker: ClivlyWriteTracker;
749
+ /**
750
+ * Wrap a request handler so `catchUp` runs after each response. Pass the
751
+ * runtime's context (anything with `waitUntil`) as any argument.
752
+ */
753
+ withCatchUp<A extends unknown[], R>(handler: (...args: A) => R | Promise<R>): (...args: A) => Promise<R>;
719
754
  }
720
755
  interface NamespaceIntrospector {
721
756
  /** All base table names in the reachable schema. */
@@ -767,4 +802,4 @@ interface NamespaceIntrospector {
767
802
  /** Prove a table is genuinely selectable (SELECT ... LIMIT 1). Throws if unreachable/denied. */
768
803
  sampleSelect(table: string): Promise<void>;
769
804
  }
770
- export { ExposurePolicy as C, SyncTriggerDescription as S, EnsureSchemaResult as _, ClivlyConnectReason as a, RemoteProjectionsDescription as b, ClivlyConsentResult as c, ClivlyUser as d, CreateChatSessionHandlerOptions as f, DoctorReport as g, DoctorCheck as h, ChatWidgetVisitor as i, ClivlySDK as l, DiscoveredTable as m, AppIdStore as n, ClivlyConnectResult as o, CursorStore as p, ChatSessionRequestBody as r, ClivlyConsentInput as s, NamespaceIntrospector as t, ClivlySDKConfig as u, EnsuredMappingResult as v, SyncSource as x, EnsuredObjectTypeResult as y };
805
+ export { SyncTriggerDescription as C, SyncSource as S, DoctorReport as _, ClivlyConnectReason as a, EnsuredObjectTypeResult as b, ClivlyConsentResult as c, ClivlyUser as d, ClivlyWriteTracker as f, DoctorCheck as g, DiscoveredTable as h, ChatWidgetVisitor as i, ClivlySDK as l, CursorStore as m, AppIdStore as n, ClivlyConnectResult as o, CreateChatSessionHandlerOptions as p, ChatSessionRequestBody as r, ClivlyConsentInput as s, NamespaceIntrospector as t, ClivlySDKConfig as u, EnsureSchemaResult as v, ExposurePolicy as w, RemoteProjectionsDescription as x, EnsuredMappingResult as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clivly",
3
- "version": "0.24.0-next.1",
3
+ "version": "0.25.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Clivly CLI — scaffold a CRM into your app (clivly init).",
@@ -1,5 +1,5 @@
1
1
  import { a as isSensitiveColumn } from "./entity-heuristics-DAxqagJA.mjs";
2
- import { b as authTableKind, g as AUTH_USERS_COLUMNS } from "./sync-Q0O-2kFI.mjs";
2
+ import { T as authTableKind, x as AUTH_USERS_COLUMNS } from "./sync-CnWT5juF.mjs";
3
3
  // ../sdk/src/projection-guard.ts
4
4
  /**
5
5
  * Tables auth libraries keep live credentials in. Whole-table: their secrets
@@ -1,5 +1,5 @@
1
1
  const require_entity_heuristics = require("./entity-heuristics-DNmrcd0b.cjs");
2
- const require_sync = require("./sync-CdA9dgZz.cjs");
2
+ const require_sync = require("./sync-R0iVlooB.cjs");
3
3
  // ../sdk/src/projection-guard.ts
4
4
  /**
5
5
  * Tables auth libraries keep live credentials in. Whole-table: their secrets
package/sdk.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_entity_config = require("./entity-config-BP8Cc_nC.cjs");
3
- const require_src = require("./src-CZIdwwI2.cjs");
3
+ const require_src = require("./src-BQasv4EL.cjs");
4
4
  const require_sdk = require("./sdk-Bzkr24NW.cjs");
5
5
  exports.CURSOR_KEY_PREFIX = require_src.CURSOR_KEY_PREFIX;
6
6
  exports.ClivlyAuthError = require_sdk.ClivlyAuthError;
package/sdk.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { S as ExposurePolicy, _ as EnsuredMappingResult, a as ClivlyConnectResult, c as ClivlySDK, d as CreateChatSessionHandlerOptions, f as CursorStore, g as EnsureSchemaResult, h as DoctorReport, i as ClivlyConnectReason, l as ClivlySDKConfig, m as DoctorCheck, n as ChatSessionRequestBody, o as ClivlyConsentInput, p as DiscoveredTable, r as ChatWidgetVisitor, s as ClivlyConsentResult, t as AppIdStore, u as ClivlyUser, v as EnsuredObjectTypeResult, x as SyncTriggerDescription, y as RemoteProjectionsDescription } from "./types-CzL7lUH9.cjs";
1
+ import { C as ExposurePolicy, S as SyncTriggerDescription, _ as EnsureSchemaResult, a as ClivlyConnectResult, b as RemoteProjectionsDescription, c as ClivlySDK, f as CreateChatSessionHandlerOptions, g as DoctorReport, h as DoctorCheck, i as ClivlyConnectReason, l as ClivlySDKConfig, m as DiscoveredTable, n as ChatSessionRequestBody, o as ClivlyConsentInput, p as CursorStore, r as ChatWidgetVisitor, s as ClivlyConsentResult, t as AppIdStore, u as ClivlyUser, v as EnsuredMappingResult, y as EnsuredObjectTypeResult } from "./types-BPG4l-oM.cjs";
2
2
  import { C as customObjectDeclarations, M as validateEntitiesConfig, a as ClivlyEntitiesConfig, f as CustomObjectDeclaration, l as ConfigValidationError, m as DiscoveredSchemaTable, u as ConfigValidationResult, w as defineClivlyConfig } from "./entity-config-CXpGowQa.cjs";
3
3
  export declare function isPlaceholderUrl(value: string): boolean;
4
4
  export declare function createChatSessionHandler({ allowedOrigins, apiKey, apiUrl, fetchImpl, resolveUser, resolveVisitorIp }: CreateChatSessionHandlerOptions): (request: Request) => Promise<Response>;
package/sdk.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as ExposurePolicy, S as SyncTriggerDescription, _ as EnsureSchemaResult, a as ClivlyConnectReason, b as RemoteProjectionsDescription, c as ClivlyConsentResult, d as ClivlyUser, f as CreateChatSessionHandlerOptions, g as DoctorReport, h as DoctorCheck, i as ChatWidgetVisitor, l as ClivlySDK, m as DiscoveredTable, n as AppIdStore, o as ClivlyConnectResult, p as CursorStore, r as ChatSessionRequestBody, s as ClivlyConsentInput, u as ClivlySDKConfig, v as EnsuredMappingResult, y as EnsuredObjectTypeResult } from "./namespace-probe-CUR2zG2l.mjs";
1
+ import { C as SyncTriggerDescription, _ as DoctorReport, a as ClivlyConnectReason, b as EnsuredObjectTypeResult, c as ClivlyConsentResult, d as ClivlyUser, g as DoctorCheck, h as DiscoveredTable, i as ChatWidgetVisitor, l as ClivlySDK, m as CursorStore, n as AppIdStore, o as ClivlyConnectResult, p as CreateChatSessionHandlerOptions, r as ChatSessionRequestBody, s as ClivlyConsentInput, u as ClivlySDKConfig, v as EnsureSchemaResult, w as ExposurePolicy, x as RemoteProjectionsDescription, y as EnsuredMappingResult } from "./namespace-probe-LKC4OU5X.mjs";
2
2
  import { C as customObjectDeclarations, M as validateEntitiesConfig, a as ClivlyEntitiesConfig, f as CustomObjectDeclaration, l as ConfigValidationError, m as DiscoveredSchemaTable, u as ConfigValidationResult, w as defineClivlyConfig } from "./entity-config-CXpGowQa.mjs";
3
3
  export declare function isPlaceholderUrl(value: string): boolean;
4
4
  export declare function createChatSessionHandler({ allowedOrigins, apiKey, apiUrl, fetchImpl, resolveUser, resolveVisitorIp }: CreateChatSessionHandlerOptions): (request: Request) => Promise<Response>;
package/sdk.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  import { c as defineClivlyConfig, g as validateEntitiesConfig, s as customObjectDeclarations } from "./entity-config-CI5CGfaN.mjs";
2
- import { a as readProcessEnv, i as memoryCursorStore, n as createClivlySDK, o as isPlaceholderUrl, r as kvCursorStore, t as CURSOR_KEY_PREFIX } from "./src-tFhC1Ru2.mjs";
2
+ import { a as readProcessEnv, i as memoryCursorStore, n as createClivlySDK, o as isPlaceholderUrl, r as kvCursorStore, t as CURSOR_KEY_PREFIX } from "./src-CAn-zrEl.mjs";
3
3
  import { a as createChatSessionHandler, i as ClivlyRateLimitError, n as ClivlyError, r as ClivlyNetworkError, t as ClivlyAuthError } from "./sdk-D2WwGBzk.mjs";
4
4
  export { CURSOR_KEY_PREFIX, ClivlyAuthError, ClivlyError, ClivlyNetworkError, ClivlyRateLimitError, createChatSessionHandler, createClivlySDK, customObjectDeclarations, defineClivlyConfig, isPlaceholderUrl, kvCursorStore, memoryCursorStore, readProcessEnv, validateEntitiesConfig };
package/sql.cjs CHANGED
@@ -1,10 +1,10 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_from_sql = require("./from-sql-CFgXkCe2.cjs");
3
- const require_app_id = require("./app-id-DcQ4u1c8.cjs");
4
- const require_supabase_contact = require("./supabase-contact-BXQ0nnLq.cjs");
5
- const require_sync = require("./sync-CdA9dgZz.cjs");
2
+ const require_from_sql = require("./from-sql-Dw2ipynp.cjs");
3
+ const require_app_id = require("./app-id-C2F25WhK.cjs");
4
+ const require_supabase_contact = require("./supabase-contact-0GmBVpiQ.cjs");
5
+ const require_sync = require("./sync-R0iVlooB.cjs");
6
6
  const require_executor = require("./executor-CU-jRgpC.cjs");
7
- const require_introspector = require("./introspector-DT_Ma59k.cjs");
7
+ const require_introspector = require("./introspector-DRmEXDai.cjs");
8
8
  exports.ContactTableMissing = require_supabase_contact.ContactTableMissing;
9
9
  exports.SUPABASE_CONTACT_NAME_COLUMN = require_supabase_contact.SUPABASE_CONTACT_NAME_COLUMN;
10
10
  exports.connectPostgresJs = require_executor.connectPostgresJs;