@clivly/sdk 0.7.2 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,66 +1,36 @@
1
1
  # @clivly/sdk
2
2
 
3
- Connect an app to Clivly Cloud. The SDK sends heartbeats, reports schema
4
- discovery data, syncs source rows to Clivly over outbound HTTPS, and can expose
5
- a signed trigger route so Clivly can start a sync from the dashboard.
3
+ Connect your app to Clivly Cloud. The SDK sends a heartbeat, reports your schema
4
+ for entity mapping, and mirrors your contacts and companies into Clivly over
5
+ outbound HTTPS. If you configure `syncTrigger`, Clivly can also call back into
6
+ your app to start a sync from the dashboard.
6
7
 
7
- ## Which package should I install?
8
+ For the end-to-end onboarding flow, start with
9
+ [`docs/guides/connecting-to-clivly-cloud.md`](../../docs/guides/connecting-to-clivly-cloud.md).
10
+ This README stays focused on the SDK surface itself.
8
11
 
9
- For most new integrations, install the consolidated public package:
12
+ ## Install
10
13
 
11
14
  ```bash
12
15
  npm install clivly
13
16
  ```
14
17
 
15
- and import from:
18
+ Clivly's stable packages publish on npm's `latest` tag. Use `@next` only when
19
+ you are intentionally validating a prerelease build.
16
20
 
17
- ```ts
18
- import { createClivlySDK, defineClivlyConfig } from "clivly/sdk";
19
- import { fromDrizzle } from "clivly/drizzle";
20
- ```
21
+ Add `drizzle-orm` when you use `clivly/drizzle`, and
22
+ `vite` when you use the Vite/TanStack Start plugin.
21
23
 
22
- `@clivly/sdk` remains a public package if you prefer a direct dependency on the
23
- SDK package itself:
24
-
25
- ```bash
26
- npm install @clivly/sdk
27
- ```
28
-
29
- with imports from:
24
+ ## Usage
30
25
 
31
26
  ```ts
32
- import { createClivlySDK, defineClivlyConfig } from "@clivly/sdk";
33
- import { fromDrizzle } from "@clivly/sdk/drizzle";
34
- ```
35
-
36
- Stable releases publish on npm's `latest` tag. Use `@next` only when you are
37
- intentionally validating a prerelease build.
38
-
39
- Add `drizzle-orm` when you use the Drizzle helpers, and `vite` when you use the
40
- Vite/TanStack Start plugin.
41
-
42
- ## Surface
43
-
44
- Public exports from this package:
45
-
46
- - `@clivly/sdk`:
47
- `createClivlySDK`, `defineClivlyConfig`, `createChatSessionHandler`,
48
- `ClivlyError`, `ClivlyNetworkError`, `ClivlyRateLimitError`,
49
- `ClivlyAuthError`
50
- - `@clivly/sdk/drizzle`:
51
- Drizzle source helpers such as `fromDrizzle`
52
- - `@clivly/sdk/vite`:
53
- the Vite/TanStack Start lifecycle plugin
54
- - `@clivly/sdk/chat-session`:
55
- chat-session handler helpers when you want that subpath explicitly
56
-
57
- ## Basic usage
58
-
59
- ```ts
60
- import { createClivlySDK, defineClivlyConfig } from "@clivly/sdk";
61
- import { fromDrizzle } from "@clivly/sdk/drizzle";
27
+ import { createClivlySDK, defineClivlyConfig } from "clivly/sdk";
28
+ import { fromDrizzle } from "clivly/drizzle";
62
29
  import { db, participants, accounts } from "./db";
63
30
 
31
+ // Declarative entity config — the non-deprecated source of truth. It maps your
32
+ // host tables/columns onto CRM concepts, and `defineClivlyConfig` validates it
33
+ // at load (warning on any non-canonical field key that would mirror as empty).
64
34
  const entities = defineClivlyConfig({
65
35
  entities: {
66
36
  participants: {
@@ -77,67 +47,62 @@ const entities = defineClivlyConfig({
77
47
  });
78
48
 
79
49
  const clivly = createClivlySDK({
80
- apiKey: process.env.CLIVLY_SECRET_KEY!,
50
+ apiKey: process.env.CLIVLY_SECRET_KEY!, // sk_live_… from Settings → API keys
81
51
  entities,
82
52
  source: {
83
- contacts: fromDrizzle(db, participants, {
84
- entity: "participants",
85
- cursorField: "updatedAt",
86
- }),
87
- companies: fromDrizzle(db, accounts, {
88
- entity: "accounts",
89
- cursorField: "updatedAt",
90
- }),
53
+ contacts: fromDrizzle(db, participants, { entity: "participants", cursorField: "updatedAt" }),
54
+ companies: fromDrizzle(db, accounts, { entity: "accounts", cursorField: "updatedAt" }),
91
55
  },
92
56
  sync: { onBoot: true, intervalMs: 30_000, batchSize: 500 },
93
57
  });
94
58
 
95
- const status = await clivly.connect();
96
- if (!status.ok) {
97
- throw new Error(`Clivly: ${status.reason}`);
98
- }
99
-
100
- await clivly.start();
101
- ```
102
-
103
- `fromDrizzle` builds the keyset-paginated `fetchPage` function the SDK needs.
104
- `cursorField` and `idField` are Drizzle property keys such as `updatedAt`, not
105
- database column names such as `updated_at`. Non-Drizzle apps can provide their
106
- own `fetchPage` implementation.
59
+ const status = await clivly.connect(); // rich result: { ok, status, reason, retryable, org? }
60
+ if (!status.ok) throw new Error(`Clivly: ${status.reason}`);
61
+ await clivly.start(); // heartbeat + backfill + interval delta sync
107
62
 
108
- ## Remote sync trigger
109
-
110
- If you configure `syncTrigger`, Clivly can ask your app to run a sync from the
111
- dashboard:
112
-
113
- ```ts
114
- const clivly = createClivlySDK({
63
+ // Optional: let Clivly's dashboard start a sync in this app.
64
+ const remote = createClivlySDK({
115
65
  apiKey: process.env.CLIVLY_SECRET_KEY!,
116
66
  entities,
117
- source: { /* ... */ },
67
+ source: { /* … */ },
118
68
  syncTrigger: {
119
69
  path: "/api/clivly/tick",
120
70
  url: process.env.CLIVLY_SYNC_TRIGGER_URL,
121
- secret: process.env.CLIVLY_SYNC_TRIGGER_SECRET,
71
+ secret: process.env.CLIVLY_SYNC_TRIGGER_SECRET, // whsec_… from Integrations → Remote sync
122
72
  },
123
73
  });
124
74
 
125
75
  export async function POST(request: Request) {
126
- return clivly.createClivlyHandler()(request);
76
+ return remote.createClivlyHandler()(request);
127
77
  }
128
78
  ```
129
79
 
130
- With `syncTrigger.url` and `syncTrigger.secret` configured, the SDK reports the
131
- trigger URL on each heartbeat and rejects unsigned or badly-signed requests.
132
- Without `syncTrigger`, cloud mode is push-only: Clivly can observe the app but
133
- cannot start a sync from the dashboard.
80
+ `fromDrizzle` generates the keyset-paginated `fetchPage` the SDK needs, inferring the
81
+ tie-breaker id from the table's primary key — pass `idField` to override.
82
+ `cursorField` and `idField` are Drizzle property keys (`updatedAt`), not database
83
+ column names (`updated_at`). Rows are keyed by your source column names; Clivly
84
+ applies the field map you confirmed during onboarding, so re-mapping never needs
85
+ a redeploy. Non-Drizzle hosts can still pass a hand-written `fetchPage` closure
86
+ instead.
87
+
88
+ With `syncTrigger.url` + `syncTrigger.secret` configured, the SDK reports the
89
+ trigger URL on each heartbeat and rejects unsigned or badly-signed trigger
90
+ requests. Without `syncTrigger`, cloud mode is push-only: Clivly can observe
91
+ the app but cannot start a sync from the dashboard.
92
+
93
+ If you rotate a remote-sync secret from Clivly's dashboard after the encryption
94
+ rollout, Clivly stores it encrypted at rest. The server-side deployment must
95
+ have `CLIVLY_TRIGGER_SECRET_WRAPPING_KEY` configured, while your app continues
96
+ to use `CLIVLY_SYNC_TRIGGER_SECRET`. Existing plaintext rows remain valid during
97
+ rollout, and older rows can be backfilled with
98
+ `node ./scripts/backfill-sync-trigger-secrets.mjs --write`.
134
99
 
135
100
  ## Vite / TanStack Start
136
101
 
137
- For long-lived Vite dev servers, wire the SDK lifecycle through the plugin:
102
+ For long-lived Vite dev servers, wire the SDK lifecycle through the Vite plugin:
138
103
 
139
104
  ```ts
140
- import { clivlyVite } from "@clivly/sdk/vite";
105
+ import { clivlyVite } from "clivly/vite";
141
106
  import clivly from "./clivly.config";
142
107
  import { defineConfig } from "vite";
143
108
 
@@ -146,80 +111,115 @@ export default defineConfig({
146
111
  });
147
112
  ```
148
113
 
149
- The plugin calls `connect()` for a startup status line, then `start()` for the
150
- heartbeat and sync loop. It is dev-server only; use `runScheduled()` or
151
- `createClivlyHandler()` for request-scoped runtimes.
114
+ The plugin calls `connect()` for a clear startup status line, then `start()` for
115
+ the heartbeat and sync loop. It is dev-server only; use `runScheduled()` or
116
+ `createClivlyHandler()` for serverless production runtimes.
117
+
118
+ > **Legacy:** the flat `contactEntity` / `contactFields` form is still accepted but
119
+ > **deprecated** — prefer the `entities` config above, which is the same model the
120
+ > mapping table and sync engine share.
152
121
 
153
122
  ## Verify your setup
154
123
 
155
- If your instance lives in `clivly.config.ts`, the CLI can validate the setup:
124
+ Put your instance in `clivly.config.ts` (`export default createClivlySDK({...})`), then:
156
125
 
157
126
  ```bash
158
- npx clivly ping
159
- npx clivly doctor
127
+ npx clivly ping # CLIVLY_SECRET_KEY + API reachability
128
+ npx clivly doctor # env → config → schema → columns → sample fetch → heartbeat
160
129
  ```
161
130
 
162
- In code, `await clivly.doctor()` returns the same structured read-only checks.
131
+ In a monorepo, pass the app config explicitly:
132
+
133
+ ```bash
134
+ npx clivly doctor --config ./apps/web/clivly.config.ts
135
+ ```
136
+
137
+ Or in code: `await clivly.doctor()` returns `{ ok, checks }` — the same six read-only checks.
163
138
 
164
139
  ## Serverless / edge
165
140
 
166
- On request-scoped runtimes such as Cloudflare Workers, Vercel, or Lambda, do
167
- not call `start()`. Use `runScheduled()` or mount `createClivlyHandler()`
168
- instead:
141
+ On request-scoped runtimes (Cloudflare Workers, Vercel, Lambda) there is no long-lived
142
+ process, so `start()`'s `setInterval` keep-alive loop can't persist — it stops ticking after
143
+ the first response. **Don't call `start()` there.** Instead drive one-shot runs from a
144
+ scheduled trigger with `runScheduled()`, or mount `createClivlyHandler()` at a route:
169
145
 
170
146
  ```ts
147
+ // Cloudflare Workers
171
148
  export default {
172
- scheduled: () => clivly.runScheduled(),
173
- fetch: clivly.createClivlyHandler(),
149
+ scheduled: () => clivly.runScheduled(), // cron: one heartbeat + one sync
150
+ fetch: clivly.createClivlyHandler(), // or drive via an uptime ping / external scheduler
174
151
  };
175
152
  ```
176
153
 
177
- `runScheduled()` throws on a failed push so cron jobs surface failures.
178
- `createClivlyHandler()` returns `200` on success and `500` on a failed run.
154
+ `runScheduled()` throws if a sync push fails (so a cron run is marked failed);
155
+ `createClivlyHandler()` returns `200` when the triggered run finishes successfully,
156
+ `500` otherwise. If the run carries a Clivly-issued run id, the SDK also reports
157
+ the final outcome back to Clivly so the dashboard reflects `running` vs
158
+ `succeeded` vs `failed` truthfully. `start()` emits a warning if it detects a
159
+ serverless runtime. Verify a connection from the terminal any time with
160
+ `npx clivly ping`.
179
161
 
180
162
  ### Persisting the delta cursor
181
163
 
182
- By default the delta cursor lives in memory. For serverless runtimes, pass a
183
- persistent `cursorStore`:
164
+ Delta sync tracks a per-entity cursor so each run only pages rows changed since the last one.
165
+ By default that cursor lives in memory — fine for a long-lived process, but **lost on every
166
+ serverless cold start**, so a fresh isolate would re-page the whole entity. Pass a
167
+ `cursorStore` backed by your own KV/DB to persist it:
184
168
 
185
169
  ```ts
186
170
  const clivly = createClivlySDK({
187
171
  apiKey: process.env.CLIVLY_SECRET_KEY!,
188
172
  entities,
189
- source: { /* ... */ },
173
+ source: { /* … */ },
190
174
  cursorStore: {
175
+ // `SyncCursor` is { id: string; time: Date } — serialize `time` (e.g. ISO string).
191
176
  get: async (entity) => {
192
177
  const raw = await kv.get(`clivly:cursor:${entity}`);
193
178
  return raw ? { id: raw.id, time: new Date(raw.time) } : null;
194
179
  },
195
180
  set: (entity, cursor) =>
196
- kv.put(
197
- `clivly:cursor:${entity}`,
198
- cursor ? { id: cursor.id, time: cursor.time.toISOString() } : null
199
- ),
181
+ kv.put(`clivly:cursor:${entity}`, cursor && { id: cursor.id, time: cursor.time.toISOString() }),
200
182
  },
201
183
  });
202
184
  ```
203
185
 
204
- Delta sync is at-least-once. Without a persisted cursor after a cold start,
205
- rows may be re-sent; they are not silently skipped.
186
+ Delta sync is **at-least-once**: after a cold start with no persisted cursor, rows since the
187
+ last push may be re-sent (the server dedupes by id) — it never silently skips rows. Use
188
+ `sync({ mode: "full" })` when you need the server to reconcile deletions (archive-on-leave).
206
189
 
207
- ## Known limitations
190
+ ## Many-to-many company membership
208
191
 
209
- - `start()` is for long-lived runtimes only.
210
- - `fromDrizzle` is the first-class generated source path today.
211
- - The legacy flat `contactEntity` / `contactFields` config is still accepted but
212
- deprecated in favor of `defineClivlyConfig({ entities: ... })`.
192
+ If a mapping links contacts to companies through a join table
193
+ (`via: { through: … }`), that entity's source must return **one row per
194
+ membership**, each row carrying the join table's foreign-key column.
213
195
 
214
- ## More docs
196
+ ```ts
197
+ // Ada belongs to two organizations: two rows, differing only in org_id.
198
+ { id: "u1", full_name: "Ada", email: "ada@acme.test", org_id: "acme" }
199
+ { id: "u1", full_name: "Ada", email: "ada@acme.test", org_id: "globex" }
200
+ ```
215
201
 
216
- - Cloud onboarding guide:
217
- [Connecting to Clivly Cloud](https://github.com/amani-joseph/clivly.com/blob/master/docs/guides/connecting-to-clivly-cloud.md)
218
- - CLI reference:
219
- [packages/cli/README.md](https://github.com/amani-joseph/clivly.com/blob/master/packages/cli/README.md)
220
- - Release notes:
221
- [CHANGELOG.md](https://github.com/amani-joseph/clivly.com/blob/master/CHANGELOG.md)
202
+ This mirrors what the embedded model produces with `LEFT JOIN <join table>`, and
203
+ it is what lets Clivly keep one CRM row per membership instead of collapsing the
204
+ person onto whichever company happened to come first.
222
205
 
223
- ## License
206
+ A person with no membership may omit the column entirely or send it as `null` —
207
+ both are accepted. But if **no** pushed row carries the column, the push is
208
+ rejected with `400 invalid_config`: silently keeping one membership would be
209
+ worse than failing, because the row counts look correct either way.
210
+
211
+ ## Known limitations
212
+
213
+ - `start()` is for long-lived runtimes only. On serverless/edge, use
214
+ `runScheduled()` or `createClivlyHandler()`.
215
+ - `fromDrizzle` is the first-class generated source path today. Non-Drizzle hosts
216
+ should provide a hand-written `fetchPage`.
217
+ - The flat `contactEntity` / `contactFields` config still works but is deprecated
218
+ in favor of `defineClivlyConfig({ entities: ... })`.
219
+
220
+ ## More docs
224
221
 
225
- MIT
222
+ - Onboarding guide:
223
+ [`docs/guides/connecting-to-clivly-cloud.md`](../../docs/guides/connecting-to-clivly-cloud.md)
224
+ - CLI docs: [`../cli/README.md`](../cli/README.md)
225
+ - Release notes: [`../../CHANGELOG.md`](../../CHANGELOG.md)
@@ -1,4 +1,4 @@
1
- import { c as CreateChatSessionHandlerOptions } from "./types-DTaz5mLi.cjs";
1
+ import { c as CreateChatSessionHandlerOptions } from "./types-DPSn54S6.cjs";
2
2
  //#region src/chat-session.d.ts
3
3
  declare function createChatSessionHandler({ allowedOrigins, apiKey, apiUrl, fetchImpl, resolveUser }: CreateChatSessionHandlerOptions): (request: Request) => Promise<Response>;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { c as CreateChatSessionHandlerOptions } from "./types-DTaz5mLi.mjs";
1
+ import { c as CreateChatSessionHandlerOptions } from "./types-DPSn54S6.mjs";
2
2
  //#region src/chat-session.d.ts
3
3
  declare function createChatSessionHandler({ allowedOrigins, apiKey, apiUrl, fetchImpl, resolveUser }: CreateChatSessionHandlerOptions): (request: Request) => Promise<Response>;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { m as NamespaceIntrospector, p as SyncSource } from "./types-DTaz5mLi.cjs";
1
+ import { m as NamespaceIntrospector, p as SyncSource } from "./types-DPSn54S6.cjs";
2
2
  import { Table } from "drizzle-orm";
3
3
  import { discoverFromDrizzle } from "@clivly/core/drizzle";
4
4
  //#region src/drizzle.d.ts
@@ -1,4 +1,4 @@
1
- import { m as NamespaceIntrospector, p as SyncSource } from "./types-DTaz5mLi.mjs";
1
+ import { m as NamespaceIntrospector, p as SyncSource } from "./types-DPSn54S6.mjs";
2
2
  import { Table } from "drizzle-orm";
3
3
  import { discoverFromDrizzle } from "@clivly/core/drizzle";
4
4
  //#region src/drizzle.d.ts
package/dist/index.cjs CHANGED
@@ -279,6 +279,46 @@ function errorMessage(error) {
279
279
  }
280
280
  //#endregion
281
281
  //#region src/doctor.ts
282
+ const TEMPORAL_CURSOR_TYPES = [
283
+ "timestamp",
284
+ "timestamptz",
285
+ "datetime",
286
+ "date",
287
+ "time"
288
+ ];
289
+ /**
290
+ * Warn when the sync cursor cannot observe an update.
291
+ *
292
+ * `clivly init` falls back to the primary key when a table has no
293
+ * `updated_at`-like column, and emits a TODO saying "confirm it is monotonic".
294
+ * A serial `id` *is* monotonic, so the note reads as satisfied — but monotonic
295
+ * is only half the requirement. An `id` never changes, so every insert mirrors
296
+ * and **no edit ever does**: a contact who changes their email keeps the old one
297
+ * in the CRM forever, with nothing anywhere reporting a problem.
298
+ *
299
+ * A code comment could not enforce this; a real integrator shipped exactly this
300
+ * configuration to production. This is the check that says so out loud.
301
+ */
302
+ function cursorMonotonicityCheck(source) {
303
+ const meta = source[require_drizzle_meta.DRIZZLE_META];
304
+ if (!meta?.columnsMeta) return null;
305
+ const index = meta.columnKeys.indexOf(meta.cursorField);
306
+ const type = meta.columnsMeta[index]?.type?.toLowerCase();
307
+ if (!type) return null;
308
+ const temporal = TEMPORAL_CURSOR_TYPES.some((t) => type.startsWith(t));
309
+ const name = `Cursor tracks updates (${source.entity})`;
310
+ if (temporal) return {
311
+ name,
312
+ ok: true,
313
+ detail: `"${source.entity}" pages on ${meta.cursorField} (${type}) — edits re-sync.`
314
+ };
315
+ return {
316
+ name,
317
+ ok: true,
318
+ warn: true,
319
+ detail: `"${source.entity}" pages on ${meta.cursorField} (${type}), which does not change when a row is edited — inserts will sync, edits will not. Add an updated_at column to "${meta.tableName ?? source.entity}" and set it as the cursor, or accept insert-only mirroring.`
320
+ };
321
+ }
282
322
  function configuredSources(config) {
283
323
  const sources = [];
284
324
  if (config.source?.contacts) sources.push(config.source.contacts);
@@ -307,32 +347,12 @@ async function mappingDryRunChecks(config) {
307
347
  return checks;
308
348
  }
309
349
  /**
310
- * Run the read-only setup checks and return a structured report. Every check
311
- * captures its own error into `detail` rather than throwing, so one failure never
312
- * hides the rest. `ok` is the AND of all non-skipped checks.
350
+ * Confirm each drizzle source actually has the cursor and id columns the sync
351
+ * pages on. Hand-written sources have no column metadata, so they are skipped
352
+ * rather than failed.
313
353
  */
314
- async function runDoctor(args) {
315
- const { config, connect } = args;
354
+ function cursorColumnChecks(sources) {
316
355
  const checks = [];
317
- const sources = configuredSources(config);
318
- const hasKey = Boolean(config.apiKey);
319
- checks.push({
320
- name: "API key present",
321
- ok: hasKey,
322
- detail: hasKey ? "CLIVLY_API_KEY is set." : "apiKey is empty — set CLIVLY_API_KEY."
323
- });
324
- const entityCount = config.entities ? Object.keys(config.entities.entities).length : 0;
325
- checks.push({
326
- name: "Entities configured",
327
- ok: entityCount > 0,
328
- detail: entityCount > 0 ? `${entityCount} entit${entityCount === 1 ? "y" : "ies"} configured.` : "No `entities` config — pass defineClivlyConfig(...) as `entities`."
329
- });
330
- checks.push({
331
- name: "Sources configured",
332
- ok: sources.length > 0,
333
- detail: sources.length > 0 ? `${sources.length} source(s) to mirror.` : "No `source.contacts` — nothing to sync."
334
- });
335
- checks.push(checkConceptCoverage(config));
336
356
  for (const source of sources) {
337
357
  const meta = source[require_drizzle_meta.DRIZZLE_META];
338
358
  if (!meta) {
@@ -352,6 +372,14 @@ async function runDoctor(args) {
352
372
  detail: missing.length === 0 ? `"${source.entity}": ${meta.cursorField} + ${idField} present.` : `"${source.entity}" missing column(s): ${missing.join(", ")}.`
353
373
  });
354
374
  }
375
+ return checks;
376
+ }
377
+ /**
378
+ * Read one row from each source to prove the query works and that rows actually
379
+ * carry the cursor key. Fetch errors are captured as failures, never thrown.
380
+ */
381
+ async function sampleFetchChecks(sources) {
382
+ const checks = [];
355
383
  for (const source of sources) try {
356
384
  const rows = await source.fetchPage({
357
385
  since: null,
@@ -371,10 +399,45 @@ async function runDoctor(args) {
371
399
  detail: describeFetchError(source.entity, error)
372
400
  });
373
401
  }
402
+ return checks;
403
+ }
404
+ /**
405
+ * Run the read-only setup checks and return a structured report. Every check
406
+ * captures its own error into `detail` rather than throwing, so one failure never
407
+ * hides the rest. `ok` is the AND of all non-skipped checks.
408
+ */
409
+ async function runDoctor(args) {
410
+ const { config, probe } = args;
411
+ const checks = [];
412
+ const sources = configuredSources(config);
413
+ const hasKey = Boolean(config.apiKey);
414
+ checks.push({
415
+ name: "API key present",
416
+ ok: hasKey,
417
+ detail: hasKey ? "CLIVLY_API_KEY is set." : "apiKey is empty — set CLIVLY_API_KEY."
418
+ });
419
+ const entityCount = config.entities ? Object.keys(config.entities.entities).length : 0;
420
+ checks.push({
421
+ name: "Entities configured",
422
+ ok: entityCount > 0,
423
+ detail: entityCount > 0 ? `${entityCount} entit${entityCount === 1 ? "y" : "ies"} configured.` : "No `entities` config — pass defineClivlyConfig(...) as `entities`."
424
+ });
425
+ checks.push({
426
+ name: "Sources configured",
427
+ ok: sources.length > 0,
428
+ detail: sources.length > 0 ? `${sources.length} source(s) to mirror.` : "No `source.contacts` — nothing to sync."
429
+ });
430
+ checks.push(checkConceptCoverage(config));
431
+ checks.push(...cursorColumnChecks(sources));
432
+ for (const source of sources) {
433
+ const check = cursorMonotonicityCheck(source);
434
+ if (check) checks.push(check);
435
+ }
436
+ checks.push(...await sampleFetchChecks(sources));
374
437
  checks.push(...await mappingDryRunChecks(config));
375
- const result = await connect();
438
+ const result = await probe();
376
439
  checks.push({
377
- name: "Heartbeat",
440
+ name: "Clivly reachable",
378
441
  ok: result.ok,
379
442
  detail: result.ok ? `Reached Clivly — org "${result.org?.name ?? "(unnamed)"}".` : `Could not connect (${result.reason}).`
380
443
  });
@@ -724,6 +787,7 @@ const UNAUTHORIZED_STATUS = 401;
724
787
  const FORBIDDEN_STATUS = 403;
725
788
  const CLIENT_ERROR_FLOOR = 400;
726
789
  const SERVICE_UNAVAILABLE_STATUS = 503;
790
+ const NOT_FOUND_STATUS = 404;
727
791
  function connectReason(status) {
728
792
  if (status === UNAUTHORIZED_STATUS) return "invalid_api_key";
729
793
  if (status === FORBIDDEN_STATUS) return "forbidden";
@@ -732,6 +796,10 @@ function connectReason(status) {
732
796
  if (status >= CLIENT_ERROR_FLOOR) return "client_error";
733
797
  return "server_error";
734
798
  }
799
+ function pingReason(status) {
800
+ if (status === NOT_FOUND_STATUS) return "server_too_old";
801
+ return connectReason(status);
802
+ }
735
803
  async function resolveOrg(response) {
736
804
  try {
737
805
  return (await response.json())?.org;
@@ -963,9 +1031,38 @@ function createClivlySDK(config) {
963
1031
  retryable: isRetryableStatus(response.status)
964
1032
  };
965
1033
  };
1034
+ const ping = async () => {
1035
+ const response = await fetcher(`${apiUrl}/clivly/sdk/ping`, {
1036
+ method: "GET",
1037
+ headers: { authorization: `Bearer ${config.apiKey}` }
1038
+ });
1039
+ if (response === null) return {
1040
+ ok: false,
1041
+ status: null,
1042
+ reason: "network_error",
1043
+ retryable: true
1044
+ };
1045
+ if (response.ok) {
1046
+ const body = await response.json().catch(() => ({}));
1047
+ return {
1048
+ ok: true,
1049
+ status: response.status,
1050
+ reason: "ok",
1051
+ retryable: false,
1052
+ org: body?.org,
1053
+ ..."appLastSeenAt" in body ? { appLastSeenAt: body.appLastSeenAt ?? null } : {}
1054
+ };
1055
+ }
1056
+ return {
1057
+ ok: false,
1058
+ status: response.status,
1059
+ reason: pingReason(response.status),
1060
+ retryable: isRetryableStatus(response.status)
1061
+ };
1062
+ };
966
1063
  const doctor = () => runDoctor({
967
1064
  config,
968
- connect
1065
+ probe: ping
969
1066
  });
970
1067
  const runScheduled = async (options) => {
971
1068
  await heartbeat();
@@ -1058,6 +1155,7 @@ function createClivlySDK(config) {
1058
1155
  stop,
1059
1156
  heartbeat,
1060
1157
  connect,
1158
+ ping,
1061
1159
  doctor,
1062
1160
  runScheduled,
1063
1161
  createClivlyHandler,
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ClivlySDK, c as CreateChatSessionHandlerOptions, d as DoctorCheck, f as DoctorReport, i as ClivlyConnectResult, l as CursorStore, n as ChatWidgetVisitor, o as ClivlySDKConfig, r as ClivlyConnectReason, s as ClivlyUser, t as ChatSessionRequestBody, u as DiscoveredTable } from "./types-DTaz5mLi.cjs";
1
+ import { a as ClivlySDK, c as CreateChatSessionHandlerOptions, d as DoctorCheck, f as DoctorReport, i as ClivlyConnectResult, l as CursorStore, n as ChatWidgetVisitor, o as ClivlySDKConfig, r as ClivlyConnectReason, s as ClivlyUser, t as ChatSessionRequestBody, u as DiscoveredTable } from "./types-DPSn54S6.cjs";
2
2
  import { createChatSessionHandler } from "./chat-session.cjs";
3
3
  import { ClivlyEntitiesConfig, defineClivlyConfig } from "@clivly/core/entity-config";
4
4
  //#region src/errors.d.ts
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ClivlySDK, c as CreateChatSessionHandlerOptions, d as DoctorCheck, f as DoctorReport, i as ClivlyConnectResult, l as CursorStore, n as ChatWidgetVisitor, o as ClivlySDKConfig, r as ClivlyConnectReason, s as ClivlyUser, t as ChatSessionRequestBody, u as DiscoveredTable } from "./types-DTaz5mLi.mjs";
1
+ import { a as ClivlySDK, c as CreateChatSessionHandlerOptions, d as DoctorCheck, f as DoctorReport, i as ClivlyConnectResult, l as CursorStore, n as ChatWidgetVisitor, o as ClivlySDKConfig, r as ClivlyConnectReason, s as ClivlyUser, t as ChatSessionRequestBody, u as DiscoveredTable } from "./types-DPSn54S6.mjs";
2
2
  import { createChatSessionHandler } from "./chat-session.mjs";
3
3
  import { ClivlyEntitiesConfig, defineClivlyConfig } from "@clivly/core/entity-config";
4
4
  //#region src/errors.d.ts
package/dist/index.mjs CHANGED
@@ -278,6 +278,46 @@ function errorMessage(error) {
278
278
  }
279
279
  //#endregion
280
280
  //#region src/doctor.ts
281
+ const TEMPORAL_CURSOR_TYPES = [
282
+ "timestamp",
283
+ "timestamptz",
284
+ "datetime",
285
+ "date",
286
+ "time"
287
+ ];
288
+ /**
289
+ * Warn when the sync cursor cannot observe an update.
290
+ *
291
+ * `clivly init` falls back to the primary key when a table has no
292
+ * `updated_at`-like column, and emits a TODO saying "confirm it is monotonic".
293
+ * A serial `id` *is* monotonic, so the note reads as satisfied — but monotonic
294
+ * is only half the requirement. An `id` never changes, so every insert mirrors
295
+ * and **no edit ever does**: a contact who changes their email keeps the old one
296
+ * in the CRM forever, with nothing anywhere reporting a problem.
297
+ *
298
+ * A code comment could not enforce this; a real integrator shipped exactly this
299
+ * configuration to production. This is the check that says so out loud.
300
+ */
301
+ function cursorMonotonicityCheck(source) {
302
+ const meta = source[DRIZZLE_META];
303
+ if (!meta?.columnsMeta) return null;
304
+ const index = meta.columnKeys.indexOf(meta.cursorField);
305
+ const type = meta.columnsMeta[index]?.type?.toLowerCase();
306
+ if (!type) return null;
307
+ const temporal = TEMPORAL_CURSOR_TYPES.some((t) => type.startsWith(t));
308
+ const name = `Cursor tracks updates (${source.entity})`;
309
+ if (temporal) return {
310
+ name,
311
+ ok: true,
312
+ detail: `"${source.entity}" pages on ${meta.cursorField} (${type}) — edits re-sync.`
313
+ };
314
+ return {
315
+ name,
316
+ ok: true,
317
+ warn: true,
318
+ detail: `"${source.entity}" pages on ${meta.cursorField} (${type}), which does not change when a row is edited — inserts will sync, edits will not. Add an updated_at column to "${meta.tableName ?? source.entity}" and set it as the cursor, or accept insert-only mirroring.`
319
+ };
320
+ }
281
321
  function configuredSources(config) {
282
322
  const sources = [];
283
323
  if (config.source?.contacts) sources.push(config.source.contacts);
@@ -306,32 +346,12 @@ async function mappingDryRunChecks(config) {
306
346
  return checks;
307
347
  }
308
348
  /**
309
- * Run the read-only setup checks and return a structured report. Every check
310
- * captures its own error into `detail` rather than throwing, so one failure never
311
- * hides the rest. `ok` is the AND of all non-skipped checks.
349
+ * Confirm each drizzle source actually has the cursor and id columns the sync
350
+ * pages on. Hand-written sources have no column metadata, so they are skipped
351
+ * rather than failed.
312
352
  */
313
- async function runDoctor(args) {
314
- const { config, connect } = args;
353
+ function cursorColumnChecks(sources) {
315
354
  const checks = [];
316
- const sources = configuredSources(config);
317
- const hasKey = Boolean(config.apiKey);
318
- checks.push({
319
- name: "API key present",
320
- ok: hasKey,
321
- detail: hasKey ? "CLIVLY_API_KEY is set." : "apiKey is empty — set CLIVLY_API_KEY."
322
- });
323
- const entityCount = config.entities ? Object.keys(config.entities.entities).length : 0;
324
- checks.push({
325
- name: "Entities configured",
326
- ok: entityCount > 0,
327
- detail: entityCount > 0 ? `${entityCount} entit${entityCount === 1 ? "y" : "ies"} configured.` : "No `entities` config — pass defineClivlyConfig(...) as `entities`."
328
- });
329
- checks.push({
330
- name: "Sources configured",
331
- ok: sources.length > 0,
332
- detail: sources.length > 0 ? `${sources.length} source(s) to mirror.` : "No `source.contacts` — nothing to sync."
333
- });
334
- checks.push(checkConceptCoverage(config));
335
355
  for (const source of sources) {
336
356
  const meta = source[DRIZZLE_META];
337
357
  if (!meta) {
@@ -351,6 +371,14 @@ async function runDoctor(args) {
351
371
  detail: missing.length === 0 ? `"${source.entity}": ${meta.cursorField} + ${idField} present.` : `"${source.entity}" missing column(s): ${missing.join(", ")}.`
352
372
  });
353
373
  }
374
+ return checks;
375
+ }
376
+ /**
377
+ * Read one row from each source to prove the query works and that rows actually
378
+ * carry the cursor key. Fetch errors are captured as failures, never thrown.
379
+ */
380
+ async function sampleFetchChecks(sources) {
381
+ const checks = [];
354
382
  for (const source of sources) try {
355
383
  const rows = await source.fetchPage({
356
384
  since: null,
@@ -370,10 +398,45 @@ async function runDoctor(args) {
370
398
  detail: describeFetchError(source.entity, error)
371
399
  });
372
400
  }
401
+ return checks;
402
+ }
403
+ /**
404
+ * Run the read-only setup checks and return a structured report. Every check
405
+ * captures its own error into `detail` rather than throwing, so one failure never
406
+ * hides the rest. `ok` is the AND of all non-skipped checks.
407
+ */
408
+ async function runDoctor(args) {
409
+ const { config, probe } = args;
410
+ const checks = [];
411
+ const sources = configuredSources(config);
412
+ const hasKey = Boolean(config.apiKey);
413
+ checks.push({
414
+ name: "API key present",
415
+ ok: hasKey,
416
+ detail: hasKey ? "CLIVLY_API_KEY is set." : "apiKey is empty — set CLIVLY_API_KEY."
417
+ });
418
+ const entityCount = config.entities ? Object.keys(config.entities.entities).length : 0;
419
+ checks.push({
420
+ name: "Entities configured",
421
+ ok: entityCount > 0,
422
+ detail: entityCount > 0 ? `${entityCount} entit${entityCount === 1 ? "y" : "ies"} configured.` : "No `entities` config — pass defineClivlyConfig(...) as `entities`."
423
+ });
424
+ checks.push({
425
+ name: "Sources configured",
426
+ ok: sources.length > 0,
427
+ detail: sources.length > 0 ? `${sources.length} source(s) to mirror.` : "No `source.contacts` — nothing to sync."
428
+ });
429
+ checks.push(checkConceptCoverage(config));
430
+ checks.push(...cursorColumnChecks(sources));
431
+ for (const source of sources) {
432
+ const check = cursorMonotonicityCheck(source);
433
+ if (check) checks.push(check);
434
+ }
435
+ checks.push(...await sampleFetchChecks(sources));
373
436
  checks.push(...await mappingDryRunChecks(config));
374
- const result = await connect();
437
+ const result = await probe();
375
438
  checks.push({
376
- name: "Heartbeat",
439
+ name: "Clivly reachable",
377
440
  ok: result.ok,
378
441
  detail: result.ok ? `Reached Clivly — org "${result.org?.name ?? "(unnamed)"}".` : `Could not connect (${result.reason}).`
379
442
  });
@@ -723,6 +786,7 @@ const UNAUTHORIZED_STATUS = 401;
723
786
  const FORBIDDEN_STATUS = 403;
724
787
  const CLIENT_ERROR_FLOOR = 400;
725
788
  const SERVICE_UNAVAILABLE_STATUS = 503;
789
+ const NOT_FOUND_STATUS = 404;
726
790
  function connectReason(status) {
727
791
  if (status === UNAUTHORIZED_STATUS) return "invalid_api_key";
728
792
  if (status === FORBIDDEN_STATUS) return "forbidden";
@@ -731,6 +795,10 @@ function connectReason(status) {
731
795
  if (status >= CLIENT_ERROR_FLOOR) return "client_error";
732
796
  return "server_error";
733
797
  }
798
+ function pingReason(status) {
799
+ if (status === NOT_FOUND_STATUS) return "server_too_old";
800
+ return connectReason(status);
801
+ }
734
802
  async function resolveOrg(response) {
735
803
  try {
736
804
  return (await response.json())?.org;
@@ -962,9 +1030,38 @@ function createClivlySDK(config) {
962
1030
  retryable: isRetryableStatus(response.status)
963
1031
  };
964
1032
  };
1033
+ const ping = async () => {
1034
+ const response = await fetcher(`${apiUrl}/clivly/sdk/ping`, {
1035
+ method: "GET",
1036
+ headers: { authorization: `Bearer ${config.apiKey}` }
1037
+ });
1038
+ if (response === null) return {
1039
+ ok: false,
1040
+ status: null,
1041
+ reason: "network_error",
1042
+ retryable: true
1043
+ };
1044
+ if (response.ok) {
1045
+ const body = await response.json().catch(() => ({}));
1046
+ return {
1047
+ ok: true,
1048
+ status: response.status,
1049
+ reason: "ok",
1050
+ retryable: false,
1051
+ org: body?.org,
1052
+ ..."appLastSeenAt" in body ? { appLastSeenAt: body.appLastSeenAt ?? null } : {}
1053
+ };
1054
+ }
1055
+ return {
1056
+ ok: false,
1057
+ status: response.status,
1058
+ reason: pingReason(response.status),
1059
+ retryable: isRetryableStatus(response.status)
1060
+ };
1061
+ };
965
1062
  const doctor = () => runDoctor({
966
1063
  config,
967
- connect
1064
+ probe: ping
968
1065
  });
969
1066
  const runScheduled = async (options) => {
970
1067
  await heartbeat();
@@ -1057,6 +1154,7 @@ function createClivlySDK(config) {
1057
1154
  stop,
1058
1155
  heartbeat,
1059
1156
  connect,
1157
+ ping,
1060
1158
  doctor,
1061
1159
  runScheduled,
1062
1160
  createClivlyHandler,
@@ -225,14 +225,33 @@ interface DoctorCheck {
225
225
  ok: boolean;
226
226
  /** True when the check could not run (e.g. a hand-written source). */
227
227
  skipped?: boolean;
228
+ /**
229
+ * True when the setup works but carries a risk worth stating.
230
+ *
231
+ * Distinct from `ok: false`, which means "this is broken, fix it before you
232
+ * rely on it". A warning is for a configuration that will run and sync, yet
233
+ * behaves in a way the developer probably did not intend — the cursor check
234
+ * below is the motivating case: syncing from an `id` column succeeds, mirrors
235
+ * every insert, and silently never re-syncs an edited row.
236
+ *
237
+ * Warnings do not fail `doctor`. Reporting them as failures would train
238
+ * people to ignore a red ladder on a working setup, which is worse than not
239
+ * reporting them at all.
240
+ */
241
+ warn?: boolean;
228
242
  }
229
243
  interface DoctorReport {
230
244
  checks: DoctorCheck[];
231
245
  /** AND of every non-skipped check's `ok`. */
232
246
  ok: boolean;
233
247
  }
234
- type ClivlyConnectReason = "ok" | "invalid_api_key" | "forbidden" | "rate_limited" | "server_error" | "client_error" | "network_error";
248
+ type ClivlyConnectReason = "ok" | "invalid_api_key" | "forbidden" | "rate_limited" | "server_error" | "client_error" | "server_too_old" | "network_error";
235
249
  interface ClivlyConnectResult {
250
+ /**
251
+ * When the org's app last heartbeated, or null if it never has. Set only by
252
+ * `ping()` — `connect()` IS a heartbeat, so the question is meaningless there.
253
+ */
254
+ appLastSeenAt?: string | null;
236
255
  ok: boolean;
237
256
  /** Org resolved from a successful heartbeat, when the server returns it. */
238
257
  org?: {
@@ -310,6 +329,14 @@ interface ClivlySDK {
310
329
  * loop and back-compat; use `connect()` when you need the failure reason.
311
330
  */
312
331
  heartbeat(): Promise<boolean>;
332
+ /**
333
+ * Read-only diagnostic probe. Proves the API key is valid and Clivly is
334
+ * reachable, and resolves the org — without reporting anything about the
335
+ * host app. Use this for `clivly status` and other diagnostics; use
336
+ * `connect()` only from the running app, which is entitled to report its
337
+ * own state.
338
+ */
339
+ ping(): Promise<ClivlyConnectResult>;
313
340
  /**
314
341
  * One-shot heartbeat + a single sync, with no keep-alive timers. The correct
315
342
  * entry point on serverless/edge (Workers, Vercel, Lambda), where `start()`'s
@@ -225,14 +225,33 @@ interface DoctorCheck {
225
225
  ok: boolean;
226
226
  /** True when the check could not run (e.g. a hand-written source). */
227
227
  skipped?: boolean;
228
+ /**
229
+ * True when the setup works but carries a risk worth stating.
230
+ *
231
+ * Distinct from `ok: false`, which means "this is broken, fix it before you
232
+ * rely on it". A warning is for a configuration that will run and sync, yet
233
+ * behaves in a way the developer probably did not intend — the cursor check
234
+ * below is the motivating case: syncing from an `id` column succeeds, mirrors
235
+ * every insert, and silently never re-syncs an edited row.
236
+ *
237
+ * Warnings do not fail `doctor`. Reporting them as failures would train
238
+ * people to ignore a red ladder on a working setup, which is worse than not
239
+ * reporting them at all.
240
+ */
241
+ warn?: boolean;
228
242
  }
229
243
  interface DoctorReport {
230
244
  checks: DoctorCheck[];
231
245
  /** AND of every non-skipped check's `ok`. */
232
246
  ok: boolean;
233
247
  }
234
- type ClivlyConnectReason = "ok" | "invalid_api_key" | "forbidden" | "rate_limited" | "server_error" | "client_error" | "network_error";
248
+ type ClivlyConnectReason = "ok" | "invalid_api_key" | "forbidden" | "rate_limited" | "server_error" | "client_error" | "server_too_old" | "network_error";
235
249
  interface ClivlyConnectResult {
250
+ /**
251
+ * When the org's app last heartbeated, or null if it never has. Set only by
252
+ * `ping()` — `connect()` IS a heartbeat, so the question is meaningless there.
253
+ */
254
+ appLastSeenAt?: string | null;
236
255
  ok: boolean;
237
256
  /** Org resolved from a successful heartbeat, when the server returns it. */
238
257
  org?: {
@@ -310,6 +329,14 @@ interface ClivlySDK {
310
329
  * loop and back-compat; use `connect()` when you need the failure reason.
311
330
  */
312
331
  heartbeat(): Promise<boolean>;
332
+ /**
333
+ * Read-only diagnostic probe. Proves the API key is valid and Clivly is
334
+ * reachable, and resolves the org — without reporting anything about the
335
+ * host app. Use this for `clivly status` and other diagnostics; use
336
+ * `connect()` only from the running app, which is entitled to report its
337
+ * own state.
338
+ */
339
+ ping(): Promise<ClivlyConnectResult>;
313
340
  /**
314
341
  * One-shot heartbeat + a single sync, with no keep-alive timers. The correct
315
342
  * entry point on serverless/edge (Workers, Vercel, Lambda), where `start()`'s
package/dist/vite.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ClivlySDK } from "./types-DTaz5mLi.cjs";
1
+ import { a as ClivlySDK } from "./types-DPSn54S6.cjs";
2
2
  import { Plugin } from "vite";
3
3
  //#region src/vite.d.ts
4
4
  interface ClivlyViteOptions {
package/dist/vite.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ClivlySDK } from "./types-DTaz5mLi.mjs";
1
+ import { a as ClivlySDK } from "./types-DPSn54S6.mjs";
2
2
  import { Plugin } from "vite";
3
3
  //#region src/vite.d.ts
4
4
  interface ClivlyViteOptions {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clivly/sdk",
3
- "version": "0.7.2",
3
+ "version": "0.7.3",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Clivly SDK — connect your app to Clivly Cloud (heartbeat, discovery, auth bridge).",
@@ -55,7 +55,7 @@
55
55
  "access": "public"
56
56
  },
57
57
  "dependencies": {
58
- "@clivly/core": "0.7.2"
58
+ "@clivly/core": "0.7.3"
59
59
  },
60
60
  "peerDependencies": {
61
61
  "drizzle-orm": ">=0.30 || >=1.0.0-rc.0",