clivly 0.24.0 → 0.25.1

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 +269 -17
  25. package/drizzle.d.cts +23 -3
  26. package/drizzle.d.mts +23 -3
  27. package/drizzle.mjs +270 -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
package/supabase.cjs CHANGED
@@ -1,24 +1,25 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_src = require("./src-CZIdwwI2.cjs");
3
- const require_supabase_contact = require("./supabase-contact-BXQ0nnLq.cjs");
4
- const require_from_sql = require("./from-sql-CFgXkCe2.cjs");
5
- const require_sync = require("./sync-CdA9dgZz.cjs");
6
- const require_app_id = require("./app-id-DcQ4u1c8.cjs");
7
- const require_introspector = require("./introspector-DT_Ma59k.cjs");
2
+ const require_auth_webhook = require("./auth-webhook-BihEUc9C.cjs");
3
+ const require_src = require("./src-BQasv4EL.cjs");
4
+ const require_supabase_contact = require("./supabase-contact-0GmBVpiQ.cjs");
5
+ const require_from_sql = require("./from-sql-Dw2ipynp.cjs");
6
+ const require_sync = require("./sync-R0iVlooB.cjs");
7
+ const require_app_id = require("./app-id-C2F25WhK.cjs");
8
+ const require_introspector = require("./introspector-DRmEXDai.cjs");
8
9
  // ../sdk/src/supabase/constants.ts
9
10
  /**
10
11
  * The cadence this function reports as its own heartbeat interval.
11
12
  *
12
13
  * An Edge Function is invoked, not running, so it heartbeats only when Clivly
13
- * pulls it. This is the cloud's idle auto-sync slot: `IDLE_SLOT_MS`
14
- * (15 * 60_000) in `packages/api/src/auto-sync-schedule.ts`, the longest gap
14
+ * pulls it. This is the cloud's longest idle auto-sync step: `HOURLY_SLOT_MS`
15
+ * (60 * 60_000) in `packages/api/src/auto-sync-schedule.ts`, the longest gap
15
16
  * between pulls for a healthy app. `livenessWindows()` in
16
17
  * `packages/core/src/integration-state.ts` treats an app as live for 2.5x its
17
18
  * reported cadence, so the function stays live between pulls. The sdk must not
18
19
  * import packages/api, so the value is repeated here; a pin test (Task 12)
19
20
  * keeps the two in step.
20
21
  */
21
- const SUPABASE_EDGE_HEARTBEAT_MS = 9e5;
22
+ const SUPABASE_EDGE_HEARTBEAT_MS = 36e5;
22
23
  // ../sdk/src/supabase/index.ts
23
24
  const ENTITY_KEY = "users";
24
25
  const ROUTE_PREFIX = "/functions/v1";
@@ -28,6 +29,9 @@ const BAD_GATEWAY = 502;
28
29
  const SERVER_ERROR = 500;
29
30
  const UNAVAILABLE = 503;
30
31
  const NOT_FOUND = 404;
32
+ const PUSH_TOKEN_QUERY = "select decrypted_secret from vault.decrypted_secrets where name = 'clivly_push_token'";
33
+ /** How often a token that does not match is looked up again. */
34
+ const PUSH_TOKEN_RECHECK_MS = 6e4;
31
35
  const json = (body, status) => new Response(JSON.stringify(body), {
32
36
  status,
33
37
  headers: { "content-type": "application/json" }
@@ -47,6 +51,7 @@ var SetupFailure = class extends Error {
47
51
  };
48
52
  /**
49
53
  * The Edge Function handler: `POST /clivly/tick` runs a sync Clivly asked for,
54
+ * `POST /clivly/push` pushes one user for the optional `auth.users` trigger,
50
55
  * `GET /clivly/connect` checks the connection, and every other request is a 404
51
56
  * that still heartbeats through `waitUntil`.
52
57
  */
@@ -154,9 +159,34 @@ function createSupabaseClivly(opts) {
154
159
  return failure(error);
155
160
  }
156
161
  };
162
+ let pushToken = null;
163
+ let pushTokenReadAt = Number.NEGATIVE_INFINITY;
164
+ let pushTokenRead = null;
165
+ const readPushToken = async (presented) => {
166
+ const now = Date.now();
167
+ if (presented !== pushToken && now - pushTokenReadAt >= PUSH_TOKEN_RECHECK_MS) {
168
+ pushTokenReadAt = now;
169
+ pushTokenRead = executor.query(PUSH_TOKEN_QUERY).then(([row]) => {
170
+ const secret = row?.decrypted_secret;
171
+ pushToken = typeof secret === "string" ? secret : null;
172
+ }).catch(() => {});
173
+ }
174
+ await pushTokenRead;
175
+ return pushToken;
176
+ };
177
+ const push = require_auth_webhook.createTokenPushHandler({
178
+ clivly: {
179
+ pushById: async (entity, ids) => (await getRuntime()).sdk.pushById(entity, ids),
180
+ pushDelete: async (entity, ids) => (await getRuntime()).sdk.pushDelete(entity, ids)
181
+ },
182
+ entity: ENTITY_KEY,
183
+ token: readPushToken,
184
+ waitUntil: opts.waitUntil
185
+ });
157
186
  return (req) => {
158
187
  const path = routeOf(req);
159
188
  if (path === "/clivly/connect" && req.method === "GET") return connect();
189
+ if (path === "/clivly/push") return secretKey ? push(req) : Promise.resolve(missingKey());
160
190
  heartbeatInBackground();
161
191
  if (path === "/clivly/tick") return tick(req);
162
192
  return Promise.resolve(json({ error: "not_found" }, NOT_FOUND));
package/supabase.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { i as SqlExecutor } from "./from-sql-S8dSvU-e.cjs";
2
- import "./index-CIupXz_w.cjs";
1
+ import { i as SqlExecutor } from "./from-sql-MyPE5elx.cjs";
2
+ import "./index-B4kWWHYm.cjs";
3
3
  export interface SupabaseClivlyOptions {
4
4
  /** Defaults to `auth.users`, joined to `public.profiles` when it qualifies. */
5
5
  contact?: {
@@ -14,6 +14,7 @@ export interface SupabaseClivlyOptions {
14
14
  }
15
15
  /**
16
16
  * The Edge Function handler: `POST /clivly/tick` runs a sync Clivly asked for,
17
+ * `POST /clivly/push` pushes one user for the optional `auth.users` trigger,
17
18
  * `GET /clivly/connect` checks the connection, and every other request is a 404
18
19
  * that still heartbeats through `waitUntil`.
19
20
  */
package/supabase.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { i as SqlExecutor } from "./from-sql-CpGP7K3J.mjs";
2
- import "./index-BoemTWH4.mjs";
1
+ import { i as SqlExecutor } from "./from-sql-YW6LfdVK.mjs";
2
+ import "./index-CKElWhvq.mjs";
3
3
  export interface SupabaseClivlyOptions {
4
4
  /** Defaults to `auth.users`, joined to `public.profiles` when it qualifies. */
5
5
  contact?: {
@@ -14,6 +14,7 @@ export interface SupabaseClivlyOptions {
14
14
  }
15
15
  /**
16
16
  * The Edge Function handler: `POST /clivly/tick` runs a sync Clivly asked for,
17
+ * `POST /clivly/push` pushes one user for the optional `auth.users` trigger,
17
18
  * `GET /clivly/connect` checks the connection, and every other request is a 404
18
19
  * that still heartbeats through `waitUntil`.
19
20
  */
package/supabase.mjs CHANGED
@@ -1,23 +1,24 @@
1
- import { i as memoryCursorStore, n as createClivlySDK } from "./src-tFhC1Ru2.mjs";
2
- import { a as discoverFromSql, r as supabaseContactSource, t as ContactTableMissing } from "./supabase-contact-3ke1KKUs.mjs";
3
- import { t as existsFromSql } from "./from-sql-BD7gR4bC.mjs";
4
- import { x as filtersAnonymous } from "./sync-Q0O-2kFI.mjs";
5
- import { r as sqlAppIdStore } from "./app-id-5cB6yioz.mjs";
6
- import { t as sqlIntrospector } from "./introspector-5w2x89RD.mjs";
1
+ import { n as createTokenPushHandler } from "./auth-webhook-3if7gY6b.mjs";
2
+ import { i as memoryCursorStore, n as createClivlySDK } from "./src-CAn-zrEl.mjs";
3
+ import { a as discoverFromSql, r as supabaseContactSource, t as ContactTableMissing } from "./supabase-contact-D-oDC4Qk.mjs";
4
+ import { t as existsFromSql } from "./from-sql-kqs9CbQ-.mjs";
5
+ import { E as filtersAnonymous } from "./sync-CnWT5juF.mjs";
6
+ import { r as sqlAppIdStore } from "./app-id-CMMadyIC.mjs";
7
+ import { t as sqlIntrospector } from "./introspector-B1S7qmvy.mjs";
7
8
  // ../sdk/src/supabase/constants.ts
8
9
  /**
9
10
  * The cadence this function reports as its own heartbeat interval.
10
11
  *
11
12
  * An Edge Function is invoked, not running, so it heartbeats only when Clivly
12
- * pulls it. This is the cloud's idle auto-sync slot: `IDLE_SLOT_MS`
13
- * (15 * 60_000) in `packages/api/src/auto-sync-schedule.ts`, the longest gap
13
+ * pulls it. This is the cloud's longest idle auto-sync step: `HOURLY_SLOT_MS`
14
+ * (60 * 60_000) in `packages/api/src/auto-sync-schedule.ts`, the longest gap
14
15
  * between pulls for a healthy app. `livenessWindows()` in
15
16
  * `packages/core/src/integration-state.ts` treats an app as live for 2.5x its
16
17
  * reported cadence, so the function stays live between pulls. The sdk must not
17
18
  * import packages/api, so the value is repeated here; a pin test (Task 12)
18
19
  * keeps the two in step.
19
20
  */
20
- const SUPABASE_EDGE_HEARTBEAT_MS = 9e5;
21
+ const SUPABASE_EDGE_HEARTBEAT_MS = 36e5;
21
22
  // ../sdk/src/supabase/index.ts
22
23
  const ENTITY_KEY = "users";
23
24
  const ROUTE_PREFIX = "/functions/v1";
@@ -27,6 +28,9 @@ const BAD_GATEWAY = 502;
27
28
  const SERVER_ERROR = 500;
28
29
  const UNAVAILABLE = 503;
29
30
  const NOT_FOUND = 404;
31
+ const PUSH_TOKEN_QUERY = "select decrypted_secret from vault.decrypted_secrets where name = 'clivly_push_token'";
32
+ /** How often a token that does not match is looked up again. */
33
+ const PUSH_TOKEN_RECHECK_MS = 6e4;
30
34
  const json = (body, status) => new Response(JSON.stringify(body), {
31
35
  status,
32
36
  headers: { "content-type": "application/json" }
@@ -46,6 +50,7 @@ var SetupFailure = class extends Error {
46
50
  };
47
51
  /**
48
52
  * The Edge Function handler: `POST /clivly/tick` runs a sync Clivly asked for,
53
+ * `POST /clivly/push` pushes one user for the optional `auth.users` trigger,
49
54
  * `GET /clivly/connect` checks the connection, and every other request is a 404
50
55
  * that still heartbeats through `waitUntil`.
51
56
  */
@@ -153,9 +158,34 @@ function createSupabaseClivly(opts) {
153
158
  return failure(error);
154
159
  }
155
160
  };
161
+ let pushToken = null;
162
+ let pushTokenReadAt = Number.NEGATIVE_INFINITY;
163
+ let pushTokenRead = null;
164
+ const readPushToken = async (presented) => {
165
+ const now = Date.now();
166
+ if (presented !== pushToken && now - pushTokenReadAt >= PUSH_TOKEN_RECHECK_MS) {
167
+ pushTokenReadAt = now;
168
+ pushTokenRead = executor.query(PUSH_TOKEN_QUERY).then(([row]) => {
169
+ const secret = row?.decrypted_secret;
170
+ pushToken = typeof secret === "string" ? secret : null;
171
+ }).catch(() => {});
172
+ }
173
+ await pushTokenRead;
174
+ return pushToken;
175
+ };
176
+ const push = createTokenPushHandler({
177
+ clivly: {
178
+ pushById: async (entity, ids) => (await getRuntime()).sdk.pushById(entity, ids),
179
+ pushDelete: async (entity, ids) => (await getRuntime()).sdk.pushDelete(entity, ids)
180
+ },
181
+ entity: ENTITY_KEY,
182
+ token: readPushToken,
183
+ waitUntil: opts.waitUntil
184
+ });
156
185
  return (req) => {
157
186
  const path = routeOf(req);
158
187
  if (path === "/clivly/connect" && req.method === "GET") return connect();
188
+ if (path === "/clivly/push") return secretKey ? push(req) : Promise.resolve(missingKey());
159
189
  heartbeatInBackground();
160
190
  if (path === "/clivly/tick") return tick(req);
161
191
  return Promise.resolve(json({ error: "not_found" }, NOT_FOUND));
@@ -53,6 +53,53 @@ function authTableKind(name) {
53
53
  }
54
54
  // ../sdk/src/drizzle-meta.ts
55
55
  const DRIZZLE_META = "__clivly_drizzle_source_meta__";
56
+ // ../sdk/src/fetch-by-ids.ts
57
+ const ownFetchPage = /* @__PURE__ */ new WeakMap();
58
+ /** `source` able to read rows by id, with the same rules as its `fetchPage`. */
59
+ function withFetchByIds(source, read) {
60
+ const fetchByIds = async (ids) => ids.length === 0 ? [] : await read(ids);
61
+ ownFetchPage.set(fetchByIds, source.fetchPage);
62
+ return Object.assign(source, { fetchByIds });
63
+ }
64
+ /**
65
+ * The source's read by id, or undefined when it has none that is safe to use.
66
+ *
67
+ * `{ ...fromDrizzle(...), fetchPage: filtered }` carries the original
68
+ * `fetchByIds` along. Using it would send rows or columns the host's own
69
+ * `fetchPage` deliberately leaves out, so it is refused.
70
+ */
71
+ function fetchByIdsOf(source) {
72
+ const { fetchByIds } = source;
73
+ if (!fetchByIds) return;
74
+ const own = ownFetchPage.get(fetchByIds);
75
+ return own === void 0 || own === source.fetchPage ? fetchByIds.bind(source) : void 0;
76
+ }
77
+ const UPGRADE_GUIDE_URL = "https://clivly.com/docs/guides/upgrade-to-0-25";
78
+ /**
79
+ * Refuse a source whose rows would hold an unrelated `id` column beside a
80
+ * differently named key: copying the key over it would re-key every record
81
+ * already mirrored, and keeping it would mirror by the wrong column.
82
+ */
83
+ function assertNoStrayIdColumn(label, table, columns, idField) {
84
+ if (idField === "id" || !columns.includes("id")) return;
85
+ throw new Error(`${label}: table "${table}" is keyed by "${idField}" but also reads a column named "id". Clivly identifies rows by "id", so ${label === "fromSql" ? `pass { idField: "id" } if that column is unique, or leave "id" out of { columns }` : `pass the "id" column's property key as idField if that column is unique`}. See ${UPGRADE_GUIDE_URL}`);
86
+ }
87
+ /** `row` with `id` set to its key, for a source keyed by another column. */
88
+ function withRowKey(row, idField) {
89
+ if (idField === void 0 || idField === "id") return row;
90
+ const key = row[idField];
91
+ const existing = row["id"];
92
+ if (existing !== void 0 && existing !== key) throw new Error(`[clivly] a row keyed by "${idField}" also has a different "id" field. Clivly keys records by "id", so the source must not return an unrelated "id". See ${UPGRADE_GUIDE_URL}`);
93
+ return {
94
+ ...row,
95
+ ["id"]: key
96
+ };
97
+ }
98
+ /** Every row of a page with `id` set to its key. */
99
+ function withRowKeys(rows, idField) {
100
+ if (idField === void 0 || idField === "id") return rows;
101
+ return rows.map((row) => withRowKey(row, idField));
102
+ }
56
103
  // ../sdk/src/entity-source.ts
57
104
  const CONCEPT_KEYS = {
58
105
  contact: "contacts",
@@ -82,6 +129,19 @@ function resolveEntitySource(config, entityKey) {
82
129
  }
83
130
  return null;
84
131
  }
132
+ /**
133
+ * The same, for a config that declares no entities (the Supabase Edge
134
+ * Function): its contact source, by the name the source itself carries.
135
+ */
136
+ function resolvePushSource(config, entityKey) {
137
+ if (config.entities) return resolveEntitySource(config, entityKey);
138
+ const source = config.source?.contacts;
139
+ return source?.entity === entityKey ? {
140
+ concept: "contact",
141
+ expectedKey: "contacts",
142
+ source
143
+ } : null;
144
+ }
85
145
  /** The `config.source` key an entity's concept requires, present or not. */
86
146
  function expectedSourceKey(concept) {
87
147
  return CONCEPT_KEYS[concept] ?? "custom";
@@ -281,10 +341,10 @@ async function syncSource(args) {
281
341
  let pushed = 0;
282
342
  const resumedFrom = since === null ? null : since.time.toISOString();
283
343
  for (;;) {
284
- const rows = await source.fetchPage({
344
+ const rows = withRowKeys(await source.fetchPage({
285
345
  since: cursor,
286
346
  limit: batchSize
287
- });
347
+ }), source.idField);
288
348
  if (rows.length === 0) break;
289
349
  const capped = maxRows === void 0 ? rows : rows.slice(0, maxRows);
290
350
  const next = advanceCursor(source, capped, cursor);
@@ -338,10 +398,10 @@ async function fullSyncSource(args) {
338
398
  const all = [];
339
399
  let cursor = null;
340
400
  for (;;) {
341
- const rows = await source.fetchPage({
401
+ const rows = withRowKeys(await source.fetchPage({
342
402
  since: cursor,
343
403
  limit: batchSize
344
- });
404
+ }), source.idField);
345
405
  if (rows.length === 0) break;
346
406
  all.push(...rows);
347
407
  const next = advanceCursor(source, rows, cursor);
@@ -379,4 +439,4 @@ async function fullSyncSource(args) {
379
439
  ok
380
440
  };
381
441
  }
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 };
442
+ export { AUTH_USERS_TABLE as C, isAnonymousFilter as D, filtersAnonymous as E, markAnonymousColumn as O, AUTH_USERS_META_KEYS as S, authTableKind as T, withRowKeys as _, isExactCursorTime as a, DRIZZLE_META as b, sourceTimeFields as c, customPushSource as d, expectedSourceKey as f, assertNoStrayIdColumn as g, resolvePushSource 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, fetchByIdsOf as v, IS_ANONYMOUS_COLUMN as w, AUTH_USERS_COLUMNS as x, withFetchByIds as y };
@@ -53,6 +53,53 @@ function authTableKind(name) {
53
53
  }
54
54
  // ../sdk/src/drizzle-meta.ts
55
55
  const DRIZZLE_META = "__clivly_drizzle_source_meta__";
56
+ // ../sdk/src/fetch-by-ids.ts
57
+ const ownFetchPage = /* @__PURE__ */ new WeakMap();
58
+ /** `source` able to read rows by id, with the same rules as its `fetchPage`. */
59
+ function withFetchByIds(source, read) {
60
+ const fetchByIds = async (ids) => ids.length === 0 ? [] : await read(ids);
61
+ ownFetchPage.set(fetchByIds, source.fetchPage);
62
+ return Object.assign(source, { fetchByIds });
63
+ }
64
+ /**
65
+ * The source's read by id, or undefined when it has none that is safe to use.
66
+ *
67
+ * `{ ...fromDrizzle(...), fetchPage: filtered }` carries the original
68
+ * `fetchByIds` along. Using it would send rows or columns the host's own
69
+ * `fetchPage` deliberately leaves out, so it is refused.
70
+ */
71
+ function fetchByIdsOf(source) {
72
+ const { fetchByIds } = source;
73
+ if (!fetchByIds) return;
74
+ const own = ownFetchPage.get(fetchByIds);
75
+ return own === void 0 || own === source.fetchPage ? fetchByIds.bind(source) : void 0;
76
+ }
77
+ const UPGRADE_GUIDE_URL = "https://clivly.com/docs/guides/upgrade-to-0-25";
78
+ /**
79
+ * Refuse a source whose rows would hold an unrelated `id` column beside a
80
+ * differently named key: copying the key over it would re-key every record
81
+ * already mirrored, and keeping it would mirror by the wrong column.
82
+ */
83
+ function assertNoStrayIdColumn(label, table, columns, idField) {
84
+ if (idField === "id" || !columns.includes("id")) return;
85
+ throw new Error(`${label}: table "${table}" is keyed by "${idField}" but also reads a column named "id". Clivly identifies rows by "id", so ${label === "fromSql" ? `pass { idField: "id" } if that column is unique, or leave "id" out of { columns }` : `pass the "id" column's property key as idField if that column is unique`}. See ${UPGRADE_GUIDE_URL}`);
86
+ }
87
+ /** `row` with `id` set to its key, for a source keyed by another column. */
88
+ function withRowKey(row, idField) {
89
+ if (idField === void 0 || idField === "id") return row;
90
+ const key = row[idField];
91
+ const existing = row["id"];
92
+ if (existing !== void 0 && existing !== key) throw new Error(`[clivly] a row keyed by "${idField}" also has a different "id" field. Clivly keys records by "id", so the source must not return an unrelated "id". See ${UPGRADE_GUIDE_URL}`);
93
+ return {
94
+ ...row,
95
+ ["id"]: key
96
+ };
97
+ }
98
+ /** Every row of a page with `id` set to its key. */
99
+ function withRowKeys(rows, idField) {
100
+ if (idField === void 0 || idField === "id") return rows;
101
+ return rows.map((row) => withRowKey(row, idField));
102
+ }
56
103
  // ../sdk/src/entity-source.ts
57
104
  const CONCEPT_KEYS = {
58
105
  contact: "contacts",
@@ -82,6 +129,19 @@ function resolveEntitySource(config, entityKey) {
82
129
  }
83
130
  return null;
84
131
  }
132
+ /**
133
+ * The same, for a config that declares no entities (the Supabase Edge
134
+ * Function): its contact source, by the name the source itself carries.
135
+ */
136
+ function resolvePushSource(config, entityKey) {
137
+ if (config.entities) return resolveEntitySource(config, entityKey);
138
+ const source = config.source?.contacts;
139
+ return source?.entity === entityKey ? {
140
+ concept: "contact",
141
+ expectedKey: "contacts",
142
+ source
143
+ } : null;
144
+ }
85
145
  /** The `config.source` key an entity's concept requires, present or not. */
86
146
  function expectedSourceKey(concept) {
87
147
  return CONCEPT_KEYS[concept] ?? "custom";
@@ -281,10 +341,10 @@ async function syncSource(args) {
281
341
  let pushed = 0;
282
342
  const resumedFrom = since === null ? null : since.time.toISOString();
283
343
  for (;;) {
284
- const rows = await source.fetchPage({
344
+ const rows = withRowKeys(await source.fetchPage({
285
345
  since: cursor,
286
346
  limit: batchSize
287
- });
347
+ }), source.idField);
288
348
  if (rows.length === 0) break;
289
349
  const capped = maxRows === void 0 ? rows : rows.slice(0, maxRows);
290
350
  const next = advanceCursor(source, capped, cursor);
@@ -338,10 +398,10 @@ async function fullSyncSource(args) {
338
398
  const all = [];
339
399
  let cursor = null;
340
400
  for (;;) {
341
- const rows = await source.fetchPage({
401
+ const rows = withRowKeys(await source.fetchPage({
342
402
  since: cursor,
343
403
  limit: batchSize
344
- });
404
+ }), source.idField);
345
405
  if (rows.length === 0) break;
346
406
  all.push(...rows);
347
407
  const next = advanceCursor(source, rows, cursor);
@@ -427,6 +487,12 @@ Object.defineProperty(exports, "advanceCursor", {
427
487
  return advanceCursor;
428
488
  }
429
489
  });
490
+ Object.defineProperty(exports, "assertNoStrayIdColumn", {
491
+ enumerable: true,
492
+ get: function() {
493
+ return assertNoStrayIdColumn;
494
+ }
495
+ });
430
496
  Object.defineProperty(exports, "authTableKind", {
431
497
  enumerable: true,
432
498
  get: function() {
@@ -445,6 +511,12 @@ Object.defineProperty(exports, "expectedSourceKey", {
445
511
  return expectedSourceKey;
446
512
  }
447
513
  });
514
+ Object.defineProperty(exports, "fetchByIdsOf", {
515
+ enumerable: true,
516
+ get: function() {
517
+ return fetchByIdsOf;
518
+ }
519
+ });
448
520
  Object.defineProperty(exports, "filtersAnonymous", {
449
521
  enumerable: true,
450
522
  get: function() {
@@ -499,6 +571,12 @@ Object.defineProperty(exports, "resolveEntitySource", {
499
571
  return resolveEntitySource;
500
572
  }
501
573
  });
574
+ Object.defineProperty(exports, "resolvePushSource", {
575
+ enumerable: true,
576
+ get: function() {
577
+ return resolvePushSource;
578
+ }
579
+ });
502
580
  Object.defineProperty(exports, "sourceTimeFields", {
503
581
  enumerable: true,
504
582
  get: function() {
@@ -517,3 +595,15 @@ Object.defineProperty(exports, "toWireCursor", {
517
595
  return toWireCursor;
518
596
  }
519
597
  });
598
+ Object.defineProperty(exports, "withFetchByIds", {
599
+ enumerable: true,
600
+ get: function() {
601
+ return withFetchByIds;
602
+ }
603
+ });
604
+ Object.defineProperty(exports, "withRowKeys", {
605
+ enumerable: true,
606
+ get: function() {
607
+ return withRowKeys;
608
+ }
609
+ });
@@ -0,0 +1,17 @@
1
+ import { d as ClivlyWriteTracker } from "./types-BPG4l-oM.cjs";
2
+ /** The parts of a Clivly SDK instance tracking uses. */
3
+ interface TrackedSDK {
4
+ catchUp?(): Promise<void>;
5
+ tracker: ClivlyWriteTracker;
6
+ }
7
+ interface TrackOptions {
8
+ /** The SDK to report to. Defaults to the one this app created. */
9
+ clivly?: TrackedSDK;
10
+ /**
11
+ * Keeps the runtime alive after the response. Found by itself on Vercel;
12
+ * pass `waitUntil` from "cloudflare:workers" on Workers. Not needed on a
13
+ * long-lived process.
14
+ */
15
+ waitUntil?: (work: Promise<void>) => void;
16
+ }
17
+ export { TrackOptions as t };
@@ -0,0 +1,17 @@
1
+ import { f as ClivlyWriteTracker } from "./namespace-probe-LKC4OU5X.mjs";
2
+ /** The parts of a Clivly SDK instance tracking uses. */
3
+ interface TrackedSDK {
4
+ catchUp?(): Promise<void>;
5
+ tracker: ClivlyWriteTracker;
6
+ }
7
+ interface TrackOptions {
8
+ /** The SDK to report to. Defaults to the one this app created. */
9
+ clivly?: TrackedSDK;
10
+ /**
11
+ * Keeps the runtime alive after the response. Found by itself on Vercel;
12
+ * pass `waitUntil` from "cloudflare:workers" on Workers. Not needed on a
13
+ * long-lived process.
14
+ */
15
+ waitUntil?: (work: Promise<void>) => void;
16
+ }
17
+ export { TrackOptions as t };
@@ -0,0 +1,77 @@
1
+ // ../sdk/src/track-writes.ts
2
+ /** An id as the wire carries it, or null for anything that is not one. */
3
+ function trackedId(value) {
4
+ if (typeof value === "string" || typeof value === "number") return value;
5
+ return typeof value === "bigint" ? String(value) : null;
6
+ }
7
+ const REGISTRY = Symbol.for("clivly.trackedSDK");
8
+ const VERCEL_CONTEXT = Symbol.for("@vercel/request-context");
9
+ const CATCH_UP_DELAY_MS = 1e3;
10
+ const CATCH_UP_EVERY_MS = 6e4;
11
+ const TRACKED_CLIENTS = Symbol.for("clivly.trackedClients");
12
+ function trackedClients() {
13
+ const known = Reflect.get(globalThis, TRACKED_CLIENTS);
14
+ const clients = known ?? /* @__PURE__ */ new WeakMap();
15
+ if (!known) Reflect.set(globalThis, TRACKED_CLIENTS, clients);
16
+ return clients;
17
+ }
18
+ function markTracked(tracked, raw) {
19
+ trackedClients().set(tracked, raw);
20
+ }
21
+ const isTracked = (client) => trackedClients().has(client);
22
+ /**
23
+ * The client under a tracked one. Everything Clivly runs itself goes through
24
+ * it: Clivly's own reads are not the app using its database.
25
+ */
26
+ function untracked(client) {
27
+ if (typeof client !== "object" || client === null) return client;
28
+ return trackedClients().get(client) ?? client;
29
+ }
30
+ function registerTrackedSDK(sdk) {
31
+ Reflect.set(globalThis, REGISTRY, sdk);
32
+ }
33
+ const runningSDK = () => Reflect.get(globalThis, REGISTRY) ?? null;
34
+ function vercelWaitUntil() {
35
+ const request = Reflect.get(globalThis, VERCEL_CONTEXT)?.get?.();
36
+ return request?.waitUntil ? (work) => request.waitUntil?.(work) : void 0;
37
+ }
38
+ /** Reports to the SDK; nothing here may delay or fail the host's query. */
39
+ function createReporter(options) {
40
+ let catchUpAskedAt = Number.NEGATIVE_INFINITY;
41
+ const keepAlive = (work) => {
42
+ try {
43
+ const waitUntil = options.waitUntil ?? vercelWaitUntil();
44
+ waitUntil?.(work);
45
+ return waitUntil !== void 0;
46
+ } catch {
47
+ return false;
48
+ }
49
+ };
50
+ const askForCatchUp = (sdk) => {
51
+ const now = Date.now();
52
+ if (!sdk.catchUp || now - catchUpAskedAt < CATCH_UP_EVERY_MS) return;
53
+ catchUpAskedAt = now;
54
+ let timer;
55
+ const work = new Promise((resolve) => {
56
+ timer = setTimeout(resolve, CATCH_UP_DELAY_MS);
57
+ }).then(() => sdk.catchUp?.()).catch(() => void 0);
58
+ if (!keepAlive(work)) timer?.unref?.();
59
+ };
60
+ return {
61
+ noteActivity() {
62
+ try {
63
+ const sdk = options.clivly ?? runningSDK();
64
+ if (sdk) {
65
+ sdk.tracker.noteDatabaseActivity();
66
+ askForCatchUp(sdk);
67
+ }
68
+ } catch {}
69
+ },
70
+ report(writes) {
71
+ const sdk = options.clivly ?? runningSDK();
72
+ if (!sdk || writes.length === 0) return;
73
+ keepAlive(Promise.resolve().then(() => sdk.tracker.recordWrites(writes)).catch(() => void 0));
74
+ }
75
+ };
76
+ }
77
+ export { trackedId as a, registerTrackedSDK as i, isTracked as n, untracked as o, markTracked as r, createReporter as t };