clivly 0.23.1 → 0.24.0-next.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 (117) hide show
  1. package/README.md +42 -2
  2. package/{adapter-B4v4dwgD.d.mts → adapter--YV7du3i.d.cts} +1 -1
  3. package/{adapter-BK3gsby5.d.cts → adapter-DD3K3dCW.d.mts} +1 -1
  4. package/app-id-5cB6yioz.mjs +53 -0
  5. package/app-id-DcQ4u1c8.cjs +70 -0
  6. package/{auth-adapter-BIa-ZyVV.d.mts → auth-adapter-C17dzlzF.d.cts} +1 -1
  7. package/{auth-adapter-DwtMJb7D.d.cts → auth-adapter-CizFv7oU.d.mts} +1 -1
  8. package/auth-better-auth.d.cts +1 -1
  9. package/auth-better-auth.d.mts +1 -1
  10. package/auth-clerk.d.cts +1 -1
  11. package/auth-clerk.d.mts +1 -1
  12. package/auth-supabase.cjs +121 -0
  13. package/auth-supabase.d.cts +23 -0
  14. package/auth-supabase.d.mts +23 -0
  15. package/auth-supabase.mjs +119 -0
  16. package/auth-workos.d.cts +1 -1
  17. package/auth-workos.d.mts +1 -1
  18. package/core-adapter.d.cts +1 -1
  19. package/core-adapter.d.mts +1 -1
  20. package/core-auth-adapter.d.cts +1 -1
  21. package/core-auth-adapter.d.mts +1 -1
  22. package/core-mapping-score.d.cts +1 -0
  23. package/core-sync-engine.cjs +1 -1
  24. package/core-sync-engine.mjs +1 -1
  25. package/core-types.cjs +5 -1
  26. package/core-types.d.cts +2 -2
  27. package/core-types.d.mts +2 -2
  28. package/core-types.mjs +1 -1
  29. package/core-view-compiler.cjs +1 -1
  30. package/core-view-compiler.mjs +1 -1
  31. package/core.cjs +9 -5
  32. package/core.d.cts +6 -6
  33. package/core.d.mts +6 -6
  34. package/core.mjs +6 -6
  35. package/drizzle.cjs +121 -14
  36. package/drizzle.d.cts +8 -2
  37. package/drizzle.d.mts +8 -2
  38. package/drizzle.mjs +126 -19
  39. package/executor-CJEWurjZ.mjs +23 -0
  40. package/executor-CU-jRgpC.cjs +40 -0
  41. package/from-sql-BD7gR4bC.mjs +282 -0
  42. package/from-sql-CFgXkCe2.cjs +347 -0
  43. package/from-sql-CpGP7K3J.d.mts +70 -0
  44. package/from-sql-S8dSvU-e.d.cts +70 -0
  45. package/index-BoemTWH4.d.mts +134 -0
  46. package/index-CIupXz_w.d.cts +134 -0
  47. package/{index-Bh7o2J7K.d.mts → index-DOoX2GgI.d.mts} +3 -3
  48. package/{index-DRRTE5IJ.d.cts → index-uFDiQEjj.d.cts} +231 -5
  49. package/index.cjs +1079 -36
  50. package/index.d.cts +36 -0
  51. package/index.d.mts +35 -0
  52. package/index.mjs +1077 -34
  53. package/{internal-CdfVkh4O.d.mts → internal-D_2q2BOB.d.mts} +1 -1
  54. package/internal-adapter.d.cts +1 -1
  55. package/internal-adapter.d.mts +1 -1
  56. package/internal-auth-adapter.d.cts +1 -1
  57. package/internal-auth-adapter.d.mts +1 -1
  58. package/internal-sync-engine.cjs +1 -1
  59. package/internal-sync-engine.mjs +1 -1
  60. package/internal-types.cjs +5 -1
  61. package/internal-types.d.cts +2 -2
  62. package/internal-types.d.mts +2 -2
  63. package/internal-types.mjs +1 -1
  64. package/internal-view-compiler.cjs +1 -1
  65. package/internal-view-compiler.mjs +1 -1
  66. package/internal.cjs +9 -5
  67. package/internal.d.cts +5 -6
  68. package/internal.d.mts +6 -6
  69. package/internal.mjs +6 -6
  70. package/introspector-5w2x89RD.mjs +55 -0
  71. package/introspector-DT_Ma59k.cjs +60 -0
  72. package/kysely.cjs +56 -0
  73. package/kysely.d.cts +45 -0
  74. package/kysely.d.mts +45 -0
  75. package/kysely.mjs +54 -0
  76. package/{namespace-probe-JuHriruA.d.mts → namespace-probe-CUR2zG2l.d.mts} +41 -4
  77. package/package.json +45 -1
  78. package/projection-guard-C70l5U24.cjs +170 -0
  79. package/projection-guard-DOt_nbGn.mjs +147 -0
  80. package/{projection-sql-DQQdjw9I.mjs → projection-sql-2joBkLz2.mjs} +13 -3
  81. package/{projection-sql-BkrHR2ea.cjs → projection-sql-DS5sVTY-.cjs} +18 -2
  82. package/sdk-Bzkr24NW.cjs +207 -0
  83. package/sdk-D2WwGBzk.mjs +178 -0
  84. package/sdk.cjs +8 -6
  85. package/sdk.d.cts +7 -1
  86. package/sdk.d.mts +7 -1
  87. package/sdk.mjs +3 -2
  88. package/sql.cjs +20 -0
  89. package/sql.d.cts +3 -0
  90. package/sql.d.mts +3 -0
  91. package/sql.mjs +7 -0
  92. package/{sdk-BOarpe5I.cjs → src-CZIdwwI2.cjs} +203 -583
  93. package/{sdk-BkMDOfCk.mjs → src-tFhC1Ru2.mjs} +175 -531
  94. package/supabase-contact-3ke1KKUs.mjs +595 -0
  95. package/supabase-contact-BXQ0nnLq.cjs +624 -0
  96. package/supabase.cjs +165 -0
  97. package/supabase.d.cts +20 -0
  98. package/supabase.d.mts +20 -0
  99. package/supabase.mjs +164 -0
  100. package/sync-CdA9dgZz.cjs +519 -0
  101. package/sync-Q0O-2kFI.mjs +382 -0
  102. package/{sync-engine-yFLEyId3.mjs → sync-engine-D0mJUeqP.mjs} +1 -1
  103. package/{sync-engine-DNSoZeo0.cjs → sync-engine-hU041kXO.cjs} +1 -1
  104. package/{namespace-probe-CcL6Wj8E.d.cts → types-CzL7lUH9.d.cts} +84 -47
  105. package/types-KMH5D5Lg.mjs +32 -0
  106. package/{types-BBfwsDxe.d.cts → types-f-Vcv-pl.d.cts} +18 -2
  107. package/{types-BBfwsDxe.d.mts → types-f-Vcv-pl.d.mts} +18 -2
  108. package/types-kR1kUlmz.cjs +67 -0
  109. package/{view-compiler-CSHSqZl7.mjs → view-compiler-BhKiezRH.mjs} +1 -1
  110. package/{view-compiler-NqiortOA.cjs → view-compiler-DgZadq1F.cjs} +1 -1
  111. package/vite.d.cts +1 -1
  112. package/vite.d.mts +1 -1
  113. package/drizzle-meta-BPnRLpsB.cjs +0 -8
  114. package/drizzle-meta-D00lFvAk.mjs +0 -3
  115. package/internal-D7qVRIFb.d.cts +0 -228
  116. package/types-8KSw2AWg.mjs +0 -8
  117. package/types-B8m39L1s.cjs +0 -19
package/index.mjs CHANGED
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
+ import { a as discoverFromSql, n as SUPABASE_CONTACT_NAME_COLUMN } from "./supabase-contact-3ke1KKUs.mjs";
3
+ import { n as pgExecutor, r as postgresJsExecutor } from "./executor-CJEWurjZ.mjs";
2
4
  import { t as CANONICAL_FIELDS } from "./entity-config-CI5CGfaN.mjs";
3
5
  import { d as suggestCursorField, i as isFrameworkTable, l as scoreFieldMap, n as hasDefiningColumn, o as matchesConcept, p as toFieldMap, s as requiredFieldsFor, u as scoreRelationships } from "./entity-heuristics-DAxqagJA.mjs";
4
6
  import "./mapping-score-CS-MTDL9.mjs";
5
- import { n as createClivlySDK, u as isPlaceholderUrl } from "./sdk-BkMDOfCk.mjs";
7
+ import { n as createClivlySDK, o as isPlaceholderUrl } from "./src-tFhC1Ru2.mjs";
6
8
  import { createRequire } from "node:module";
7
9
  import { spawn } from "node:child_process";
8
10
  import { accessSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, watch, writeFileSync } from "node:fs";
@@ -13,7 +15,7 @@ import { createJiti } from "jiti";
13
15
  import { fileURLToPath, pathToFileURL } from "node:url";
14
16
  import { Socket } from "node:net";
15
17
  // ../core/src/env-file.ts
16
- const ENV_FILES = {
18
+ const ENV_FILES$1 = {
17
19
  next: ".env.local",
18
20
  "tanstack-start": ".env",
19
21
  sveltekit: ".env",
@@ -23,7 +25,7 @@ const ENV_FILES = {
23
25
  };
24
26
  /** The conventional env file for a framework. `.env` when we do not know. */
25
27
  function envFileFor(framework) {
26
- return ENV_FILES[normalizeFramework(framework)] ?? ".env";
28
+ return ENV_FILES$1[normalizeFramework(framework)] ?? ".env";
27
29
  }
28
30
  const ALIASES = {
29
31
  next: "next",
@@ -174,8 +176,28 @@ async function loadCliConfig(cwd) {
174
176
  // src/dashboard-locations.ts
175
177
  /** Secret + publishable keys. The Connect dialog mints them and shows the secret once. */
176
178
  const CREDENTIALS_LOCATION = "Clivly dashboard → Connect app (or Settings → API keys)";
177
- /** The signing secret Clivly Cloud uses on sync-trigger callbacks. */
178
- const SYNC_SECRET_LOCATION = "Clivly dashboard → Integrations → Remote sync";
179
+ /**
180
+ * The signing secret Clivly Cloud uses on sync-trigger callbacks. It is minted
181
+ * on the Setup tab, in the step labelled by `INTEGRATION_STEP_LABELS.trigger`
182
+ * (Generate secret), which unlocks after the app's first heartbeat.
183
+ */
184
+ const SYNC_SECRET_LOCATION = "Clivly dashboard → Connections → Setup → \"Clivly can start a sync\"";
185
+ /**
186
+ * The last step of the Supabase deploy-first list: the first sync, started
187
+ * from the Setup ladder's sync stage. Step 4 already sent the developer to
188
+ * Connections → Setup, so this names the same screen and the button's label
189
+ * (`apps/web/src/lib/setup-stages.ts`, pinned by its test). Later syncs run
190
+ * on Clivly's schedule or from "Run sync" on Connections → What syncs.
191
+ */
192
+ const FIRST_SYNC_LOCATION = "Start the first sync: Clivly dashboard → Connections → Setup → \"Run the first sync\"";
193
+ /**
194
+ * Where a workspace maps host tables onto CRM objects: the Connections page's
195
+ * "What syncs" tab (`apps/web/src/lib/integrations-tabs.ts`). Earlier text
196
+ * called it "Integrations → Mapping" or "Integrations → Data model"; neither
197
+ * names a screen. The SDK and the cloud spell the same location out, since
198
+ * they cannot import the CLI.
199
+ */
200
+ const MAPPING_LOCATION = "Clivly dashboard → Connections → What syncs";
179
201
  /** Chat widget records and their allowed origins. */
180
202
  const WIDGET_LOCATION = "Clivly dashboard → Settings → Chat widget";
181
203
  // src/detect.ts
@@ -769,11 +791,11 @@ async function runDev(options) {
769
791
  }
770
792
  // src/dev-override.ts
771
793
  const TRIGGER_URL_PATH = "/clivly/sdk/trigger-url";
772
- const HTTP_UNAUTHORIZED = 401;
773
- const HTTP_NOT_FOUND = 404;
794
+ const HTTP_UNAUTHORIZED$1 = 401;
795
+ const HTTP_NOT_FOUND$1 = 404;
774
796
  function kindForStatus(status) {
775
- if (status === HTTP_UNAUTHORIZED) return "unauthorized";
776
- if (status === HTTP_NOT_FOUND) return "not_enabled";
797
+ if (status === HTTP_UNAUTHORIZED$1) return "unauthorized";
798
+ if (status === HTTP_NOT_FOUND$1) return "not_enabled";
777
799
  return "unexpected_response";
778
800
  }
779
801
  function failureFor(status) {
@@ -1354,6 +1376,8 @@ Usage:
1354
1376
  Deprecated aliases — each runs part of \`clivly status\` and still works:
1355
1377
  clivly ping credential + reachability
1356
1378
  clivly connect the above, plus config and trigger URL
1379
+ clivly connect --supabase check a Supabase Edge Function is live and has
1380
+ contacts to sync (--project-url <url> to override)
1357
1381
  clivly doctor config, setup checks and edge safety
1358
1382
 
1359
1383
  Prefer \`clivly status\`: it runs the whole ladder and tells you which step you
@@ -1368,7 +1392,7 @@ Usage:
1368
1392
  clivly init [--force] [--dry-run] [--diff] [--yes] [--no-login] [--no-browser]
1369
1393
  [--schema <path|package>] [--db-import <specifier>]
1370
1394
  [--auth-import <specifier>] [--contact-table <table>]
1371
- [--company-table <table>] [--framework <name>]
1395
+ [--company-table <table>] [--framework <name>] [--no-orm]
1372
1396
 
1373
1397
  Scaffolds clivly.config.ts, the Clivly route files, and .env placeholders.
1374
1398
  Detects your framework, ORM, auth adapter and app layout from the project.
@@ -1387,6 +1411,9 @@ Options:
1387
1411
  --auth-import <s> Module specifier exporting your auth instance
1388
1412
  --contact-table <t> Table to map as contacts
1389
1413
  --company-table <t> Table to map as companies
1414
+ --no-orm Read the schema from the live database (DATABASE_URL)
1415
+ instead of an ORM schema. Implied for Supabase apps
1416
+ with no ORM; an SPA gets a Supabase Edge Function
1390
1417
  `,
1391
1418
  add: `clivly add widget — scaffold the chat-session route
1392
1419
 
@@ -1468,7 +1495,7 @@ function isHelpRequest(argv) {
1468
1495
  }
1469
1496
  function helpFor(command) {
1470
1497
  if (!command) return ROOT_HELP;
1471
- return COMMAND_HELP[command] ?? "clivly — embed a CRM in your app\n\nUsage:\n clivly init [options] Scaffold Clivly (config, routes, env file) for your app\n clivly add widget [options] Scaffold the chat-session route\n clivly status [options] Check your setup, step by step\n clivly push-schema [options] Push schema, custom objects and mappings to Clivly\n clivly dev [options] Tunnel localhost so remote sync can reach you\n clivly login [options] Pair this machine and write credentials to your env file\n clivly --version Print the installed clivly version\n\nDeprecated aliases — each runs part of `clivly status` and still works:\n clivly ping credential + reachability\n clivly connect the above, plus config and trigger URL\n clivly doctor config, setup checks and edge safety\n\nPrefer `clivly status`: it runs the whole ladder and tells you which step you\nare on. The aliases are kept because output and docs have recommended them.\n\nRun `clivly <command> --help` for details on a command.\n";
1498
+ return COMMAND_HELP[command] ?? "clivly — embed a CRM in your app\n\nUsage:\n clivly init [options] Scaffold Clivly (config, routes, env file) for your app\n clivly add widget [options] Scaffold the chat-session route\n clivly status [options] Check your setup, step by step\n clivly push-schema [options] Push schema, custom objects and mappings to Clivly\n clivly dev [options] Tunnel localhost so remote sync can reach you\n clivly login [options] Pair this machine and write credentials to your env file\n clivly --version Print the installed clivly version\n\nDeprecated aliases — each runs part of `clivly status` and still works:\n clivly ping credential + reachability\n clivly connect the above, plus config and trigger URL\n clivly connect --supabase check a Supabase Edge Function is live and has\n contacts to sync (--project-url <url> to override)\n clivly doctor config, setup checks and edge safety\n\nPrefer `clivly status`: it runs the whole ladder and tells you which step you\nare on. The aliases are kept because output and docs have recommended them.\n\nRun `clivly <command> --help` for details on a command.\n";
1472
1499
  }
1473
1500
  // src/install.ts
1474
1501
  const defaultRun = (command, args, cwd) => new Promise((resolvePromise, reject) => {
@@ -1638,6 +1665,313 @@ function loadEnv(cwd, env = process.env, options = {}) {
1638
1665
  files
1639
1666
  };
1640
1667
  }
1668
+ // src/live-schema.ts
1669
+ /** `supabase link` writes the ref here; the CLI's `--linked` reads it. */
1670
+ const SUPABASE_PROJECT_REF = "supabase/.temp/project-ref";
1671
+ function supabaseProjectState(present, fileExists, cwd) {
1672
+ if (!present) return "absent";
1673
+ return fileExists(join(cwd, SUPABASE_PROJECT_REF)) ? "linked" : "unlinked";
1674
+ }
1675
+ const SUPABASE_LINK_HINT = " To read the schema through the Supabase CLI, link this project first: `npx supabase link`, then re-run.\n";
1676
+ const CONNECTION_KEYS = ["DATABASE_URL", "SUPABASE_DB_URL"];
1677
+ const CONNECTION_ENV_FILES = [".env.local", ".env"];
1678
+ /**
1679
+ * `db query` against the linked project, machine-readable, non-interactive.
1680
+ * `--linked` is accepted by every CLI that has `db query` (v3 keeps it as a
1681
+ * hidden alias of a bare `--remote`), `--output json` prints the rows, and
1682
+ * `--yes` answers the hosted-database confirmation a script cannot.
1683
+ */
1684
+ const SUPABASE_CLI_QUERY_ARGS = [
1685
+ "db",
1686
+ "query",
1687
+ "--linked",
1688
+ "--output",
1689
+ "json",
1690
+ "--yes"
1691
+ ];
1692
+ const CLI_TIMEOUT_MS = 6e4;
1693
+ /**
1694
+ * The first `npx --yes supabase` may install the npm package, whose postinstall
1695
+ * downloads the CLI binary (tens of MB), so it gets longer than a query.
1696
+ */
1697
+ const NPX_FIRST_RUN_TIMEOUT_MS = 3e5;
1698
+ const CONNECT_TIMEOUT_SECONDS = 10;
1699
+ const MS_PER_SECOND = 1e3;
1700
+ /** The connection string and where it came from, or null when none is set. */
1701
+ function resolveConnectionString(env, readFile, cwd) {
1702
+ for (const key of CONNECTION_KEYS) {
1703
+ const value = env[key]?.trim();
1704
+ if (value) return {
1705
+ label: key,
1706
+ value
1707
+ };
1708
+ }
1709
+ for (const name of CONNECTION_ENV_FILES) {
1710
+ const contents = readFile(join(cwd, name));
1711
+ if (contents === null) continue;
1712
+ const parsed = parseEnv(contents);
1713
+ for (const key of CONNECTION_KEYS) {
1714
+ const value = parsed[key]?.trim();
1715
+ if (value) return {
1716
+ label: key,
1717
+ value
1718
+ };
1719
+ }
1720
+ }
1721
+ return null;
1722
+ }
1723
+ const JSON_START = /[[{]/;
1724
+ const POSTGRES_ARRAY = /^\{(.*)\}$/s;
1725
+ function normaliseValue(value) {
1726
+ if (typeof value !== "string") return value;
1727
+ const match = POSTGRES_ARRAY.exec(value);
1728
+ if (!match) return value;
1729
+ const inner = match[1] ?? "";
1730
+ return inner === "" ? [] : inner.split(",").map((part) => part.replaceAll("\"", ""));
1731
+ }
1732
+ /** The rows `supabase db query --output json` printed, in either shape. */
1733
+ function parseSupabaseCliRows(stdout) {
1734
+ const start = stdout.search(JSON_START);
1735
+ if (start === -1) throw new Error("supabase db query printed no JSON");
1736
+ const parsed = JSON.parse(stdout.slice(start));
1737
+ const rows = Array.isArray(parsed) || parsed === null || typeof parsed !== "object" || !("rows" in parsed) ? parsed : parsed.rows;
1738
+ if (!Array.isArray(rows)) throw new Error("supabase db query printed no rows");
1739
+ return rows.map((row) => Object.fromEntries(Object.entries(row).map(([k, v]) => [k, normaliseValue(v)])));
1740
+ }
1741
+ const quoteLiteral = (value) => `'${value.replaceAll("'", "''")}'`;
1742
+ function literalFor(param) {
1743
+ if (Array.isArray(param)) return `ARRAY[${param.map((p) => quoteLiteral(String(p))).join(", ")}]`;
1744
+ if (param === null || param === void 0) return "null";
1745
+ return quoteLiteral(String(param));
1746
+ }
1747
+ const PARAM_REF = /\$(\d+)/g;
1748
+ const WHITESPACE_RUN = /\s+/g;
1749
+ /**
1750
+ * An executor over `supabase db query`. The CLI takes one SQL string and no
1751
+ * bind parameters, so parameters are inlined as quoted literals. Only the
1752
+ * catalog queries discovery issues go through here, and their one parameter
1753
+ * is the list of schema names.
1754
+ *
1755
+ * The SQL is collapsed onto one line first. On Windows the npx fallback runs
1756
+ * the bin through cmd.exe (npm's run-script uses a shell), and cmd.exe ends a
1757
+ * command at the first newline. The catalog SQL has no multi-line string
1758
+ * literals, and collapsing happens before the parameters are inlined, so a
1759
+ * schema name keeps its exact spelling.
1760
+ */
1761
+ function supabaseCliExecutor(run) {
1762
+ return { async query(text, params) {
1763
+ const oneLine = text.replace(WHITESPACE_RUN, " ").trim();
1764
+ const sql = params ? oneLine.replace(PARAM_REF, (_, n) => literalFor(params[Number(n) - 1])) : oneLine;
1765
+ const result = await run([...SUPABASE_CLI_QUERY_ARGS, sql]);
1766
+ if (result.code !== 0) throw new SupabaseCliFailed(result.code);
1767
+ return parseSupabaseCliRows(result.stdout);
1768
+ } };
1769
+ }
1770
+ var SupabaseCliFailed = class extends Error {
1771
+ code;
1772
+ constructor(code) {
1773
+ super(`supabase exited with ${code}`);
1774
+ this.code = code;
1775
+ }
1776
+ };
1777
+ async function discoverOrNull(executor) {
1778
+ const tables = await discoverFromSql(executor);
1779
+ return tables.length === 0 ? null : tables;
1780
+ }
1781
+ async function fromConnectionString(opts, out) {
1782
+ const label = opts.connectionLabel ?? "DATABASE_URL";
1783
+ let connection = null;
1784
+ try {
1785
+ connection = await (opts.connect ?? missingDriver)(opts.connectionString);
1786
+ return await discoverOrNull(connection.executor);
1787
+ } catch (error) {
1788
+ opts.onFailure?.(error instanceof DriverMissing ? "driver_missing" : "connect_failed");
1789
+ out(error instanceof DriverMissing ? ` Couldn't read the schema from ${label}: install \`postgres\` or \`pg\` in this app so init can connect.\n` : ` Couldn't read the schema from ${label}.\n`);
1790
+ return null;
1791
+ } finally {
1792
+ await connection?.close().catch(() => void 0);
1793
+ }
1794
+ }
1795
+ async function fromSupabaseCli(run, out, onFailure) {
1796
+ try {
1797
+ return await discoverOrNull(supabaseCliExecutor(run));
1798
+ } catch (error) {
1799
+ if (!(error instanceof SupabaseCliFailed && error.code === 127)) {
1800
+ onFailure?.("cli_failed");
1801
+ out(" Couldn't read the schema through the Supabase CLI (is this project linked? `supabase link`).\n");
1802
+ }
1803
+ return null;
1804
+ }
1805
+ }
1806
+ async function readLiveSchema(opts) {
1807
+ const out = opts.out ?? (() => void 0);
1808
+ if (opts.connectionString) {
1809
+ const tables = await fromConnectionString({
1810
+ ...opts,
1811
+ connectionString: opts.connectionString
1812
+ }, out);
1813
+ if (tables) return tables;
1814
+ }
1815
+ if (opts.supabaseProject === "unlinked") {
1816
+ out(SUPABASE_LINK_HINT);
1817
+ return null;
1818
+ }
1819
+ if (opts.runSupabaseCli && opts.supabaseProject !== "absent") return fromSupabaseCli(opts.runSupabaseCli, out, opts.onFailure);
1820
+ return null;
1821
+ }
1822
+ var DriverMissing = class extends Error {};
1823
+ function missingDriver() {
1824
+ return Promise.reject(new DriverMissing());
1825
+ }
1826
+ async function importFromHost(cwd, name) {
1827
+ try {
1828
+ const resolved = createRequire(join(cwd, "package.json")).resolve(name);
1829
+ const mod = await import(pathToFileURL(resolved).href);
1830
+ return mod.default ?? mod;
1831
+ } catch {
1832
+ return null;
1833
+ }
1834
+ }
1835
+ /**
1836
+ * Opens the database with the driver the host app already has — `postgres`
1837
+ * first, then `pg`. The CLI ships neither, so an app with no driver gets the
1838
+ * "install one" message and falls through to the next source.
1839
+ */
1840
+ function defaultConnect$1(cwd) {
1841
+ return async (url) => {
1842
+ const postgres = await importFromHost(cwd, "postgres");
1843
+ if (typeof postgres === "function") {
1844
+ const sql = postgres(url, {
1845
+ prepare: false,
1846
+ max: 1,
1847
+ connect_timeout: CONNECT_TIMEOUT_SECONDS
1848
+ });
1849
+ return {
1850
+ executor: postgresJsExecutor(sql),
1851
+ close: () => sql.end()
1852
+ };
1853
+ }
1854
+ const pg = await importFromHost(cwd, "pg");
1855
+ if (pg?.Client) {
1856
+ const client = new pg.Client({
1857
+ connectionString: url,
1858
+ connectionTimeoutMillis: CONNECT_TIMEOUT_SECONDS * MS_PER_SECOND
1859
+ });
1860
+ await client.connect();
1861
+ return {
1862
+ executor: pgExecutor(client),
1863
+ close: () => client.end()
1864
+ };
1865
+ }
1866
+ throw new DriverMissing();
1867
+ };
1868
+ }
1869
+ function spawnCli(command, args, cwd, timeoutMs) {
1870
+ return new Promise((resolve) => {
1871
+ let stdout = "";
1872
+ let settled = false;
1873
+ const finish = (code) => {
1874
+ if (!settled) {
1875
+ settled = true;
1876
+ clearTimeout(timer);
1877
+ resolve({
1878
+ code,
1879
+ stdout
1880
+ });
1881
+ }
1882
+ };
1883
+ let child;
1884
+ const timer = setTimeout(() => {
1885
+ child?.kill();
1886
+ finish(1);
1887
+ }, timeoutMs);
1888
+ try {
1889
+ child = spawn(command, args, {
1890
+ cwd,
1891
+ stdio: [
1892
+ "ignore",
1893
+ "pipe",
1894
+ "ignore"
1895
+ ]
1896
+ });
1897
+ } catch (error) {
1898
+ const code = error.code;
1899
+ finish(code === "ENOENT" ? 127 : 1);
1900
+ return;
1901
+ }
1902
+ child.stdout?.on("data", (chunk) => {
1903
+ stdout += chunk.toString("utf8");
1904
+ });
1905
+ child.on("error", (error) => {
1906
+ finish(error.code === "ENOENT" ? 127 : 1);
1907
+ });
1908
+ child.on("close", (code) => finish(code ?? 1));
1909
+ });
1910
+ }
1911
+ /**
1912
+ * How to run `npx --yes supabase …` without a shell at the first hop. Windows
1913
+ * ships npx as `npx.cmd`, which Node refuses to spawn without a shell, so
1914
+ * there the npx script runs on Node itself from the npm bundled next to it.
1915
+ * (npx still runs the bin through a shell internally, which is why the SQL
1916
+ * is collapsed onto one line.) Returns null when that script isn't there, as
1917
+ * under bun or a Node install that keeps npm elsewhere: npx is then as good
1918
+ * as missing.
1919
+ */
1920
+ function npxSupabaseCommand(args, platform = process.platform, execPath = process.execPath, fileExists = existsSync) {
1921
+ const npxArgs = [
1922
+ "--yes",
1923
+ "supabase",
1924
+ ...args
1925
+ ];
1926
+ if (platform === "win32") {
1927
+ const npxCli = join(dirname(execPath), "node_modules", "npm", "bin", "npx-cli.js");
1928
+ if (!fileExists(npxCli)) return null;
1929
+ return {
1930
+ command: execPath,
1931
+ args: [npxCli, ...npxArgs]
1932
+ };
1933
+ }
1934
+ return {
1935
+ command: "npx",
1936
+ args: npxArgs
1937
+ };
1938
+ }
1939
+ /**
1940
+ * Runs `supabase` with an args array (no shell), in the app directory. When
1941
+ * that binary is missing (ENOENT) it retries as `npx --yes supabase`, since
1942
+ * many apps (Lovable ones included) only reach the CLI through npx.
1943
+ * SUPABASE_CLI_MISSING is reported only when both are missing.
1944
+ *
1945
+ * The route that answered is remembered, so the later discovery queries skip
1946
+ * the ENOENT probe, and only the first npx run gets the long install timeout.
1947
+ */
1948
+ function defaultRunSupabaseCli(cwd, run = spawnCli, npxCommand = npxSupabaseCommand) {
1949
+ let route;
1950
+ let npxHasRun = false;
1951
+ const missing = {
1952
+ code: 127,
1953
+ stdout: ""
1954
+ };
1955
+ const runNpx = async (args) => {
1956
+ const viaNpx = npxCommand(args);
1957
+ if (!viaNpx) return missing;
1958
+ const timeout = npxHasRun ? CLI_TIMEOUT_MS : NPX_FIRST_RUN_TIMEOUT_MS;
1959
+ npxHasRun = true;
1960
+ return await run(viaNpx.command, viaNpx.args, cwd, timeout);
1961
+ };
1962
+ return async (args) => {
1963
+ if (route === "missing") return missing;
1964
+ if (route === "npx") return await runNpx(args);
1965
+ const direct = await run("supabase", args, cwd, CLI_TIMEOUT_MS);
1966
+ if (direct.code !== 127) {
1967
+ route = "supabase";
1968
+ return direct;
1969
+ }
1970
+ const viaNpx = await runNpx(args);
1971
+ route = viaNpx.code === 127 ? "missing" : "npx";
1972
+ return viaNpx;
1973
+ };
1974
+ }
1641
1975
  // src/secret-key-env.ts
1642
1976
  const SECRET_KEY_ENV = "CLIVLY_SECRET_KEY";
1643
1977
  const LEGACY_SECRET_KEY_ENV = "CLIVLY_API_KEY";
@@ -2275,7 +2609,7 @@ function renderEntity(key, entity) {
2275
2609
  fields: ${renderFields(entity.fields)}${renderRelationships(entity)},
2276
2610
  }`;
2277
2611
  }
2278
- function renderSource(role, entity, dbExpr) {
2612
+ function renderSource$1(role, entity, dbExpr) {
2279
2613
  const opts = entity.idField === null ? `{ entity: "${entity.tableName}", cursorField: "${entity.cursorField}" }` : `{ entity: "${entity.tableName}", cursorField: "${entity.cursorField}", idField: "${entity.idField}" }`;
2280
2614
  return ` ${role}: fromDrizzle(${dbExpr}, schema.${entity.moduleKey}, ${opts})`;
2281
2615
  }
@@ -2328,8 +2662,8 @@ function renderInitConfig(plan) {
2328
2662
  const dbExpr = renderDbExpr(plan);
2329
2663
  const entities = [renderEntity(plan.contact.moduleKey, plan.contact)];
2330
2664
  if (plan.company) entities.push(renderEntity(plan.company.moduleKey, plan.company));
2331
- const sources = [renderSource("contacts", plan.contact, dbExpr)];
2332
- if (plan.company) sources.push(renderSource("companies", plan.company, dbExpr));
2665
+ const sources = [renderSource$1("contacts", plan.contact, dbExpr)];
2666
+ if (plan.company) sources.push(renderSource$1("companies", plan.company, dbExpr));
2333
2667
  return `${renderTodoHeader(plan.todos)}${renderImports(plan)}
2334
2668
 
2335
2669
  const entities = defineClivlyConfig({
@@ -2424,6 +2758,57 @@ function workosWiring() {
2424
2758
  ${RESOLVE_USER}`
2425
2759
  };
2426
2760
  }
2761
+ /**
2762
+ * Each env var a wiring reads, with the other names it accepts: "A (or B / C)
2763
+ * and D". What init prints, so it names everything the route falls back to.
2764
+ */
2765
+ function describeEnvKeys(wiring) {
2766
+ return wiring.envKeys.map((key) => {
2767
+ const others = wiring.envFallbacks?.[key] ?? [];
2768
+ return others.length > 0 ? `${key} (or ${others.join(" / ")})` : key;
2769
+ }).join(" and ");
2770
+ }
2771
+ const SUPABASE_URL_KEY = "SUPABASE_URL";
2772
+ const SUPABASE_ANON_KEY = "SUPABASE_ANON_KEY";
2773
+ const SUPABASE_ENV_FALLBACKS = {
2774
+ [SUPABASE_URL_KEY]: ["NEXT_PUBLIC_SUPABASE_URL", "VITE_SUPABASE_URL"],
2775
+ [SUPABASE_ANON_KEY]: [
2776
+ "NEXT_PUBLIC_SUPABASE_ANON_KEY",
2777
+ "VITE_SUPABASE_ANON_KEY",
2778
+ "SUPABASE_PUBLISHABLE_KEY",
2779
+ "NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY",
2780
+ "VITE_SUPABASE_PUBLISHABLE_KEY"
2781
+ ]
2782
+ };
2783
+ const envChain = (key) => [key, ...SUPABASE_ENV_FALLBACKS[key] ?? []].map((name) => `process.env.${name}`).join(" || ");
2784
+ function supabaseWiring() {
2785
+ const envKeys = [SUPABASE_URL_KEY, SUPABASE_ANON_KEY];
2786
+ const needs = describeEnvKeys({
2787
+ envFallbacks: SUPABASE_ENV_FALLBACKS,
2788
+ envKeys
2789
+ });
2790
+ return {
2791
+ complete: true,
2792
+ envFallbacks: SUPABASE_ENV_FALLBACKS,
2793
+ envKeys,
2794
+ hostImport: null,
2795
+ imports: ["import { createSupabaseAuthAdapter } from \"clivly/auth/supabase\";"],
2796
+ packages: [],
2797
+ body: `const supabaseUrl = ${envChain(SUPABASE_URL_KEY)};
2798
+ const supabaseAnonKey = ${envChain(SUPABASE_ANON_KEY)};
2799
+ const adapter =
2800
+ supabaseUrl && supabaseAnonKey
2801
+ ? createSupabaseAuthAdapter({ supabaseUrl, anonKey: supabaseAnonKey })
2802
+ : {
2803
+ getUser(_req: Request): never {
2804
+ throw new Error(
2805
+ "Clivly: the auth/verify route needs your Supabase project URL and anon key. Set ${needs}."
2806
+ );
2807
+ },
2808
+ };
2809
+ ${RESOLVE_USER}`
2810
+ };
2811
+ }
2427
2812
  function hostImportFor(instance) {
2428
2813
  if (instance === null) return {
2429
2814
  binding: "auth",
@@ -2451,6 +2836,7 @@ function renderAuthWiring(auth, authInstance = null) {
2451
2836
  case "clerk": return clerkWiring();
2452
2837
  case "workos": return workosWiring();
2453
2838
  case "better-auth": return betterAuthWiring(authInstance);
2839
+ case "supabase": return supabaseWiring();
2454
2840
  default: return STUB;
2455
2841
  }
2456
2842
  }
@@ -2753,7 +3139,7 @@ function planFiles(args) {
2753
3139
  const mutations = [];
2754
3140
  const bootPath = bootHookPath(args.framework, args.layout);
2755
3141
  const render = (path) => {
2756
- if (path === "clivly.config.ts") return renderInitConfig(args.plan);
3142
+ if (path === "clivly.config.ts") return (args.renderConfig ?? renderInitConfig)(args.plan);
2757
3143
  if (bootPath !== null && path === bootPath) return renderBootHook(args.framework, args.layout);
2758
3144
  const kind = path.includes("verify") ? "verify" : "tick";
2759
3145
  return renderRouteFile(args.framework, kind, args.authWiring, args.layout, parseTsconfig(args.readFile(join(args.cwd, "tsconfig.json")) ?? "")?.paths);
@@ -2775,10 +3161,16 @@ function envAction(addedCount, existingLength) {
2775
3161
  function planEnv(args) {
2776
3162
  const existing = args.readEnv(args.cwd);
2777
3163
  const addedKeys = CLIVLY_ENV_KEYS.filter((entry) => !hasKey(existing, entry.key)).map((entry) => entry.key);
3164
+ let contents = appendEnvKeys(existing, CLIVLY_ENV_KEYS);
3165
+ for (const { block, key } of args.commentedEnv ?? []) if (!(hasKey(existing, key) || contents.includes(block))) {
3166
+ const lead = contents.length === 0 || contents.endsWith("\n") ? "" : "\n";
3167
+ contents = `${contents}${lead}${block}\n`;
3168
+ addedKeys.push(key);
3169
+ }
2778
3170
  return {
2779
3171
  path: ".env",
2780
3172
  addedKeys,
2781
- contents: appendEnvKeys(existing, CLIVLY_ENV_KEYS),
3173
+ contents,
2782
3174
  action: envAction(addedKeys.length, existing.length)
2783
3175
  };
2784
3176
  }
@@ -3019,7 +3411,7 @@ function reportSchema(report, out) {
3019
3411
  if (skipped.length > 0) {
3020
3412
  out(` ↩︎ Kept the dashboard's version of ${countOf(skipped.length, "entity", "entities")}: ${skipped.map((m) => m.entityKey).join(", ")}.\n`);
3021
3413
  out(" The dashboard owns these mappings, so clivly.config did not change them.\n");
3022
- out(" To let your config own one, delete it in Integrations → Mapping, then push again.\n");
3414
+ out(` To let your config own one, delete it in ${MAPPING_LOCATION}, then push again.\n`);
3023
3415
  }
3024
3416
  const settled = report.mappings.length - skipped.length;
3025
3417
  if (settled > 0 && created.length === 0 && updated.length === 0) out(` ✅ ${countOf(settled, "mapping")} already match your config.\n`);
@@ -3063,7 +3455,7 @@ async function runPushSchema(options) {
3063
3455
  out(" ⚠️ Could not declare the objects and mappings in your config.\n");
3064
3456
  out(" Run `clivly status`, then `clivly push-schema` again.\n");
3065
3457
  } else reportSchema(report, out);
3066
- out(" Open Integrations → Mapping to review them.\n");
3458
+ out(` Open ${MAPPING_LOCATION} to review them.\n`);
3067
3459
  return 0;
3068
3460
  }
3069
3461
  const ensured = await sdk.ensureCustomObjects?.();
@@ -3074,9 +3466,321 @@ async function runPushSchema(options) {
3074
3466
  const created = ensured.filter((o) => o.created);
3075
3467
  out(created.length > 0 ? ` ✅ Created ${created.length} custom object(s): ${created.map((o) => o.slug).join(", ")}.\n` : ` ✅ ${ensured.length} custom object(s) already present.\n`);
3076
3468
  }
3077
- out(" Open Integrations → Mapping to map your tables.\n");
3469
+ out(` Open ${MAPPING_LOCATION} to map your tables.\n`);
3078
3470
  return 0;
3079
3471
  }
3472
+ // src/render-sql-config.ts
3473
+ const AUTH_USERS = "auth.users";
3474
+ const EMAIL_COLUMNS = /* @__PURE__ */ new Set(["email", "email_address"]);
3475
+ const NON_IDENTIFIER = /[^A-Za-z0-9_$]/g;
3476
+ const NO_CURSOR_TODO = /^No updated_at-like column on "([^"]+)"/;
3477
+ /** An entity key for a table: its bare name, made a valid identifier. */
3478
+ function entityKeyFor(name, taken) {
3479
+ const bare = name.slice(name.lastIndexOf(".") + 1).replace(NON_IDENTIFIER, "_");
3480
+ const key = taken.has(bare) ? name.replace(NON_IDENTIFIER, "_") : bare;
3481
+ taken.add(key);
3482
+ return key;
3483
+ }
3484
+ function toDiscoveredSchema(tables) {
3485
+ const taken = /* @__PURE__ */ new Set();
3486
+ return {
3487
+ importPath: "your database",
3488
+ db: null,
3489
+ tables: tables.map((table) => ({
3490
+ tableName: table.name,
3491
+ moduleKey: entityKeyFor(table.name, taken),
3492
+ columns: (table.columnsMeta ?? table.columns.map((name) => ({ name }))).map((column) => {
3493
+ const meta = column;
3494
+ return {
3495
+ key: meta.name,
3496
+ dbName: meta.name,
3497
+ isPrimary: meta.isPrimaryKey ?? false,
3498
+ ...meta.type === void 0 ? {} : { type: meta.type },
3499
+ ...meta.nullable === void 0 ? {} : { nullable: meta.nullable },
3500
+ ...meta.references ? { references: meta.references } : {}
3501
+ };
3502
+ }),
3503
+ ...table.uniqueConstraints ? { uniqueConstraints: table.uniqueConstraints } : {}
3504
+ }))
3505
+ };
3506
+ }
3507
+ /**
3508
+ * The contact table for a live schema: Supabase Auth's `auth.users` when it is
3509
+ * there, else the Drizzle path's heuristic pick, else the first table with an
3510
+ * email column. Undefined when nothing qualifies.
3511
+ */
3512
+ function chooseSqlContactTable(tables) {
3513
+ if (tables.some((table) => table.name === AUTH_USERS)) return AUTH_USERS;
3514
+ const heuristic = planInit(toDiscoveredSchema(tables)).contact?.tableName;
3515
+ if (heuristic) return heuristic;
3516
+ return tables.find((table) => table.columns.some((column) => EMAIL_COLUMNS.has(column.toLowerCase())))?.name;
3517
+ }
3518
+ /** `planInit` over a live schema, with the SQL contact-table default applied. */
3519
+ function planSqlInit(tables, overrides = {}) {
3520
+ const plan = planInit(toDiscoveredSchema(tables), {
3521
+ contactTable: overrides.contactTable ?? chooseSqlContactTable(tables),
3522
+ companyTable: overrides.companyTable
3523
+ });
3524
+ const todos = plan.todos.map((todo) => {
3525
+ const table = NO_CURSOR_TODO.exec(todo)?.[1];
3526
+ return table === void 0 ? todo : `No updated_at column on "${table}" — Clivly re-reads the whole table on each sync.`;
3527
+ });
3528
+ return {
3529
+ ...plan,
3530
+ todos
3531
+ };
3532
+ }
3533
+ function cursorOption(entity, plan) {
3534
+ if (plan.todos.some((todo) => todo.includes(`"${entity.tableName}"`) && todo.startsWith("No updated_at column")) || entity.cursorField === "updated_at") return "";
3535
+ return `, cursorField: ${JSON.stringify(entity.cursorField)}`;
3536
+ }
3537
+ function renderSource(role, entity, plan) {
3538
+ const table = JSON.stringify(entity.tableName);
3539
+ const id = entity.idField === null ? "" : `, idField: ${JSON.stringify(entity.idField)}`;
3540
+ return ` ${role}: fromSql(executor, { entity: ${table}, table: ${table}, meta: table(${table})${cursorOption(entity, plan)}${id} })`;
3541
+ }
3542
+ const isSupabaseContact = (plan) => plan.contact.tableName === AUTH_USERS;
3543
+ function contactEntityPlan(plan) {
3544
+ if (!isSupabaseContact(plan) || plan.contact.fields.name) return plan.contact;
3545
+ return {
3546
+ ...plan.contact,
3547
+ fields: {
3548
+ name: SUPABASE_CONTACT_NAME_COLUMN,
3549
+ ...plan.contact.fields
3550
+ }
3551
+ };
3552
+ }
3553
+ const renderSqlImports = (names) => `import {\n${names.map((n) => ` ${n},`).join("\n")}\n} from "clivly/sql";`;
3554
+ function renderDriver(driver, supabaseContact, usesFromSql) {
3555
+ const contact = supabaseContact ? ["supabaseContactSource"] : [];
3556
+ const fromSql = usesFromSql ? ["fromSql"] : [];
3557
+ const sdkImport = `import { type ClivlySDK, createClivlySDK, defineClivlyConfig } from "clivly/sdk";`;
3558
+ if (driver === "pg") return {
3559
+ imports: `import pg from "pg";
3560
+ ${sdkImport}
3561
+ ${renderSqlImports([
3562
+ "discoverFromSql",
3563
+ ...fromSql,
3564
+ "pgExecutor",
3565
+ "type SqlExecutor",
3566
+ "sqlAppIdStore",
3567
+ "sqlIntrospector",
3568
+ ...contact
3569
+ ])}`,
3570
+ connect: "pgExecutor(new pg.Pool({ connectionString: databaseUrl }))"
3571
+ };
3572
+ return {
3573
+ imports: `import postgres from "postgres";
3574
+ ${sdkImport}
3575
+ ${renderSqlImports([
3576
+ "connectPostgresJs",
3577
+ "discoverFromSql",
3578
+ ...fromSql,
3579
+ "type SqlExecutor",
3580
+ "sqlAppIdStore",
3581
+ "sqlIntrospector",
3582
+ ...contact
3583
+ ])}`,
3584
+ connect: "connectPostgresJs(databaseUrl, postgres)"
3585
+ };
3586
+ }
3587
+ const TABLE_HELPER = `
3588
+ const table = (name: string) => {
3589
+ const meta = schema.find((t) => t.name === name);
3590
+ if (!meta) {
3591
+ throw new Error(\`clivly.config.ts: table "\${name}" is not in your database.\`);
3592
+ }
3593
+ return meta;
3594
+ };
3595
+ `;
3596
+ function renderSqlConfig(plan) {
3597
+ const supabaseContact = isSupabaseContact(plan);
3598
+ const usesFromSql = !supabaseContact || Boolean(plan.company);
3599
+ const { imports, connect } = renderDriver(plan.driver, supabaseContact, usesFromSql);
3600
+ const entities = [renderEntity(plan.contact.moduleKey, contactEntityPlan(plan))];
3601
+ const sources = [supabaseContact ? " contacts: contact.source" : renderSource("contacts", plan.contact, plan)];
3602
+ if (plan.company) {
3603
+ entities.push(renderEntity(plan.company.moduleKey, plan.company));
3604
+ sources.push(renderSource("companies", plan.company, plan));
3605
+ }
3606
+ return `${renderTodoHeader(plan.todos)}${imports}
3607
+
3608
+ // Your database, read with SELECT only. Clivly's one write is its own one-row
3609
+ // \`crm_clivly_app\` table, which keeps the ID Clivly issues this app.
3610
+ const databaseUrl = process.env.DATABASE_URL || process.env.SUPABASE_DB_URL;
3611
+ const executor = databaseUrl ? ${connect} : null;
3612
+
3613
+ // Every table in your database, read once at boot, so the Clivly dashboard can
3614
+ // offer them all when you add a mapping — not just the sources below.
3615
+ const schema = executor ? await discoverFromSql(executor) : [];
3616
+ ${usesFromSql ? TABLE_HELPER : ""}
3617
+ const entities = defineClivlyConfig({
3618
+ entities: {
3619
+ ${entities.join(",\n")},
3620
+ },
3621
+ });
3622
+
3623
+ // Clivly over the live database. Built only once there is a connection string.
3624
+ function connectedClivly(executor: SqlExecutor): ClivlySDK {${supabaseContact ? `
3625
+ // Supabase Auth's users, joined to public.profiles when its id references
3626
+ // auth.users: the same contact source the Edge Function uses, so every row
3627
+ // carries a flat \`full_name\` (the profile's, else the sign-up metadata's).
3628
+ const contact = supabaseContactSource(executor, schema);` : ""}
3629
+ return createClivlySDK({
3630
+ apiKey: process.env.CLIVLY_SECRET_KEY ?? process.env.CLIVLY_API_KEY!,
3631
+ entities,
3632
+ schema: ${supabaseContact ? "contact.schema" : "schema"},
3633
+ // Lets derived objects authored in the dashboard run against this database.
3634
+ introspector: sqlIntrospector(executor),
3635
+ appIdStore: sqlAppIdStore(executor),
3636
+ source: {
3637
+ // Keyed by CRM concept — contacts/companies/deals/custom.
3638
+ // NOT by your entity key. The entity's own \`source:\` above is a table name.
3639
+ ${sources.join(",\n")},
3640
+ },
3641
+ syncTrigger: {
3642
+ // Where Clivly Cloud calls to start a sync — your mounted tick route.
3643
+ // \`path\` lets the SDK build its public URL from the hosting platform's
3644
+ // environment; \`url\` overrides that when you need to.
3645
+ path: "${CLIVLY_TICK_PATH}",
3646
+ url: process.env.CLIVLY_SYNC_TRIGGER_URL,
3647
+ secret: process.env.CLIVLY_SYNC_TRIGGER_SECRET,
3648
+ },
3649
+ // Changes arrive with Clivly's scheduled sync; there is no instant push
3650
+ // without an ORM write helper.
3651
+ });
3652
+ }
3653
+
3654
+ const MISSING_DATABASE_URL =
3655
+ "[clivly] Not connecting: set DATABASE_URL (or SUPABASE_DB_URL) to your Postgres connection string, then restart the app.";
3656
+
3657
+ // No connection string (a build step, or a deploy missing the variable): no
3658
+ // SDK is built, so nothing reaches Clivly — no heartbeat, no partial schema.
3659
+ // Each member answers as the real SDK does when it cannot deliver, and the
3660
+ // first call logs the error once. \`satisfies\` keeps it in step with the SDK.
3661
+ function clivlyWithoutDatabase(): ClivlySDK {
3662
+ let logged = false;
3663
+ const warnOnce = () => {
3664
+ if (!logged) {
3665
+ logged = true;
3666
+ console.error(MISSING_DATABASE_URL);
3667
+ }
3668
+ };
3669
+ const notConnected = async () => {
3670
+ warnOnce();
3671
+ return { ok: false, reason: "client_error", retryable: false, status: null } as const;
3672
+ };
3673
+ const refuse = async (): Promise<never> => {
3674
+ warnOnce();
3675
+ throw new Error(MISSING_DATABASE_URL);
3676
+ };
3677
+ const unavailable = () => async (_req: Request) => {
3678
+ warnOnce();
3679
+ return Response.json({ ok: false, error: MISSING_DATABASE_URL }, { status: 503 });
3680
+ };
3681
+ return {
3682
+ connect: notConnected,
3683
+ ping: notConnected,
3684
+ heartbeat: async () => {
3685
+ warnOnce();
3686
+ return false;
3687
+ },
3688
+ doctor: async () => {
3689
+ warnOnce();
3690
+ return {
3691
+ ok: false,
3692
+ checks: [{ name: "Database connection string", ok: false, detail: MISSING_DATABASE_URL }],
3693
+ };
3694
+ },
3695
+ ensureSchema: async () => {
3696
+ warnOnce();
3697
+ return null;
3698
+ },
3699
+ ensureCustomObjects: async () => {
3700
+ warnOnce();
3701
+ return null;
3702
+ },
3703
+ describeSyncTrigger: () => ({
3704
+ configured: process.env.CLIVLY_SYNC_TRIGGER_URL,
3705
+ hasSecret: Boolean(process.env.CLIVLY_SYNC_TRIGGER_SECRET),
3706
+ resolved: undefined,
3707
+ }),
3708
+ describeRemoteProjections: () => ({
3709
+ capable: false,
3710
+ failed: 0,
3711
+ invalid: 0,
3712
+ ok: 0,
3713
+ ran: false,
3714
+ skipped: 0,
3715
+ }),
3716
+ createClivlyHandler: unavailable,
3717
+ createAuthVerifyHandler: unavailable,
3718
+ recordConsent: async () => {
3719
+ warnOnce();
3720
+ return { ok: false, error: MISSING_DATABASE_URL, status: null };
3721
+ },
3722
+ pushOne: async () => warnOnce(),
3723
+ pushDelete: async () => warnOnce(),
3724
+ start: async () => warnOnce(),
3725
+ stop: async () => undefined,
3726
+ sync: refuse,
3727
+ runScheduled: refuse,
3728
+ } satisfies ClivlySDK;
3729
+ }
3730
+
3731
+ export default executor ? connectedClivly(executor) : clivlyWithoutDatabase();
3732
+ `;
3733
+ }
3734
+ // src/render-supabase.ts
3735
+ const SUPABASE_FUNCTION_INDEX = "supabase/functions/clivly/index.ts";
3736
+ const SUPABASE_DENO_JSON = "supabase/functions/clivly/deno.json";
3737
+ const SUPABASE_CONFIG_TOML = "supabase/config.toml";
3738
+ /** The runtime default `createSupabaseClivly` picks when `contact` is omitted. */
3739
+ const DEFAULT_CONTACT_TABLE = "auth.users";
3740
+ const CLIVLY_FUNCTION_BLOCK = "[functions.clivly]\nverify_jwt = false\n";
3741
+ const CLIVLY_FUNCTION_HEADER = /^[ \t]*\[functions\.clivly\][ \t]*(#.*)?$/m;
3742
+ const DENO_JSON = `${JSON.stringify({ imports: {} }, null, 2)}\n`;
3743
+ function hasClivlyFunctionBlock(toml) {
3744
+ return CLIVLY_FUNCTION_HEADER.test(toml);
3745
+ }
3746
+ const TABLE_HEADER = /^[ \t]*\[/m;
3747
+ const VERIFY_JWT_TRUE = /^[ \t]*verify_jwt[ \t]*=[ \t]*true\b/m;
3748
+ /** True when an existing `[functions.clivly]` block turns the JWT check on. */
3749
+ function clivlyBlockVerifiesJwt(toml) {
3750
+ const header = CLIVLY_FUNCTION_HEADER.exec(toml);
3751
+ if (!header) return false;
3752
+ const rest = toml.slice(header.index + header[0].length);
3753
+ const next = rest.search(TABLE_HEADER);
3754
+ return VERIFY_JWT_TRUE.test(next === -1 ? rest : rest.slice(0, next));
3755
+ }
3756
+ function renderConfigToml(existing) {
3757
+ if (!existing) return CLIVLY_FUNCTION_BLOCK;
3758
+ if (hasClivlyFunctionBlock(existing)) return existing;
3759
+ return `${existing}${existing.endsWith("\n") ? "\n" : "\n\n"}${CLIVLY_FUNCTION_BLOCK}`;
3760
+ }
3761
+ function renderIndex(plan) {
3762
+ const pkg = `clivly@${plan.version}`;
3763
+ return `import postgres from "npm:postgres@3";
3764
+ import { connectPostgresJs } from "npm:${pkg}/sql";
3765
+ import { createSupabaseClivly } from "npm:${pkg}/supabase";
3766
+
3767
+ const env = Deno.env.toObject();
3768
+ const handler = createSupabaseClivly({
3769
+ env,
3770
+ executor: connectPostgresJs(env.SUPABASE_DB_URL, postgres),
3771
+ waitUntil: (p) => EdgeRuntime.waitUntil(p),
3772
+ ${plan.contactTable && plan.contactTable !== DEFAULT_CONTACT_TABLE ? ` contact: { table: ${JSON.stringify(plan.contactTable)} },\n` : ""}});
3773
+
3774
+ Deno.serve(handler);
3775
+ `;
3776
+ }
3777
+ function renderSupabaseFunction(plan) {
3778
+ return { files: {
3779
+ [SUPABASE_FUNCTION_INDEX]: renderIndex(plan),
3780
+ [SUPABASE_DENO_JSON]: DENO_JSON,
3781
+ [SUPABASE_CONFIG_TOML]: renderConfigToml(plan.existingConfigToml)
3782
+ } };
3783
+ }
3080
3784
  // src/resolve-schema-path.ts
3081
3785
  const COMMON_PATHS = [
3082
3786
  "src/db/schema.ts",
@@ -3758,7 +4462,7 @@ const triggerUrlStage = {
3758
4462
  });
3759
4463
  }
3760
4464
  };
3761
- const TRIGGER_SECRET_HINT = "Run `clivly login` to write CLIVLY_SECRET_KEY and CLIVLY_SYNC_TRIGGER_SECRET together, or copy the signing secret from Integrations → Remote sync. Every environment the app runs in needs both.";
4465
+ const TRIGGER_SECRET_HINT = `Run \`clivly login\` to write CLIVLY_SECRET_KEY and CLIVLY_SYNC_TRIGGER_SECRET together, or generate the signing secret at ${SYNC_SECRET_LOCATION}. Every environment the app runs in needs both.`;
3762
4466
  /**
3763
4467
  * Whether the trigger route can verify Clivly's requests.
3764
4468
  *
@@ -4029,6 +4733,128 @@ async function runStatus(options) {
4029
4733
  if (code !== 0 && results.some((result) => result.state === "pending")) out("\nSetup is incomplete — finish the steps above and re-run.\n");
4030
4734
  return code;
4031
4735
  }
4736
+ // src/supabase-detect.ts
4737
+ const SUPABASE_DEPS = ["@supabase/supabase-js", "@supabase/ssr"];
4738
+ const CONFIG_TOML = "supabase/config.toml";
4739
+ const LOVABLE_CLIENT = "src/integrations/supabase/client.ts";
4740
+ const ENV_FILES = [
4741
+ ".env",
4742
+ ".env.local",
4743
+ ".env.development",
4744
+ ".env.development.local"
4745
+ ];
4746
+ const URL_KEYS = [
4747
+ "VITE_SUPABASE_URL",
4748
+ "NEXT_PUBLIC_SUPABASE_URL",
4749
+ "SUPABASE_URL"
4750
+ ];
4751
+ const PROJECT_URL_LITERAL = /https:\/\/[a-z0-9]+\.supabase\.co\b/i;
4752
+ function defaultReadFile$1(path) {
4753
+ return existsSync(path) ? readFileSync(path, "utf8") : null;
4754
+ }
4755
+ function urlFromEnvFiles(cwd, readFile) {
4756
+ const merged = {};
4757
+ for (const name of ENV_FILES) {
4758
+ const contents = readFile(join(cwd, name));
4759
+ if (contents !== null) Object.assign(merged, parseEnv(contents));
4760
+ }
4761
+ for (const key of URL_KEYS) {
4762
+ const value = merged[key]?.trim();
4763
+ if (value) return value;
4764
+ }
4765
+ return null;
4766
+ }
4767
+ function detectSupabase(deps, fileExists, cwd, readFile = defaultReadFile$1) {
4768
+ const clientPath = join(cwd, LOVABLE_CLIENT);
4769
+ const hasClient = fileExists(clientPath);
4770
+ const present = SUPABASE_DEPS.some((dep) => dep in deps) || fileExists(join(cwd, CONFIG_TOML)) || hasClient;
4771
+ if (!present) return {
4772
+ present: false,
4773
+ projectUrl: null
4774
+ };
4775
+ const fromEnv = urlFromEnvFiles(cwd, readFile);
4776
+ if (fromEnv) return {
4777
+ present,
4778
+ projectUrl: fromEnv
4779
+ };
4780
+ return {
4781
+ present,
4782
+ projectUrl: (hasClient ? PROJECT_URL_LITERAL.exec(readFile(clientPath) ?? "")?.[0] : void 0) ?? null
4783
+ };
4784
+ }
4785
+ // src/supabase-connect.ts
4786
+ const FAILURE = 1;
4787
+ const SUCCESS = 0;
4788
+ const HTTP_UNAUTHORIZED = 401;
4789
+ const HTTP_FORBIDDEN = 403;
4790
+ const HTTP_NOT_FOUND = 404;
4791
+ const HTTP_UNAVAILABLE = 503;
4792
+ const TRAILING_SLASHES = /\/+$/;
4793
+ const SECRET_KEY_HELP = "CLIVLY_SECRET_KEY is not set on the function. Add it in the Supabase dashboard (Edge Functions → Secrets), or in Lovable's Secrets panel, then run this again.\n";
4794
+ const NOT_DEPLOYED_HELP = "The clivly function is not deployed yet. Deploy it, then run this again:\n npx supabase functions deploy clivly\n";
4795
+ const VERIFY_JWT_HELP = "The clivly function refused the request. The most likely cause is JWT verification being on. Set it off in supabase/config.toml and redeploy:\n [functions.clivly]\n verify_jwt = false\n";
4796
+ const unreachableHelp = (base) => `Couldn't reach ${base}. Check the project URL (or pass --project-url) and your connection, then run this again.\n`;
4797
+ const REDEPLOY_HELP = "The deployed clivly function is out of date. Update `clivly` and redeploy it, then run this again:\n npx supabase functions deploy clivly\n";
4798
+ const ZERO_ROWS_HELP = "The function is live, but 0 contacts would sync, so nothing is syncing yet.\nThat can be normal for a brand-new app with no sign-ups (anonymous users are not counted). Sign up a test user and run this again.\nThe function did reach Clivly, so you can carry on with the trigger secret (step 4) now.\n";
4799
+ async function readBody(response) {
4800
+ try {
4801
+ const parsed = await response.json();
4802
+ return parsed && typeof parsed === "object" ? parsed : {};
4803
+ } catch {
4804
+ return {};
4805
+ }
4806
+ }
4807
+ function failureText(status, body) {
4808
+ if (status === HTTP_NOT_FOUND) return NOT_DEPLOYED_HELP;
4809
+ if (status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN) return VERIFY_JWT_HELP;
4810
+ if (status === HTTP_UNAVAILABLE && body.reason === "missing_secret_key") return SECRET_KEY_HELP;
4811
+ return null;
4812
+ }
4813
+ async function runSupabaseConnect(deps) {
4814
+ const { out } = deps;
4815
+ const base = deps.projectUrl.replace(TRAILING_SLASHES, "");
4816
+ let response;
4817
+ try {
4818
+ response = await deps.fetch(`${base}/functions/v1/clivly/connect`, { method: "GET" });
4819
+ } catch {
4820
+ out(unreachableHelp(base));
4821
+ return { code: FAILURE };
4822
+ }
4823
+ const body = await readBody(response);
4824
+ if (response.ok && body.ok === true) {
4825
+ if (body.hasContacts === false) {
4826
+ out(ZERO_ROWS_HELP);
4827
+ return { code: FAILURE };
4828
+ }
4829
+ if (body.hasContacts !== true) {
4830
+ out(REDEPLOY_HELP);
4831
+ return { code: FAILURE };
4832
+ }
4833
+ out("Connected to Clivly.\n");
4834
+ return { code: SUCCESS };
4835
+ }
4836
+ const help = failureText(response.status, body);
4837
+ if (help) {
4838
+ out(help);
4839
+ return { code: FAILURE };
4840
+ }
4841
+ out(`The clivly function reported a problem (${typeof body.reason === "string" ? body.reason : "unknown"}).\n`);
4842
+ return { code: FAILURE };
4843
+ }
4844
+ /** The project URL from `--project-url`, else the app's own Supabase config. */
4845
+ function resolveSupabaseProjectUrl(cwd, override) {
4846
+ if (override) return override;
4847
+ let deps = {};
4848
+ const pkgPath = join(cwd, "package.json");
4849
+ if (existsSync(pkgPath)) try {
4850
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
4851
+ deps = {
4852
+ ...pkg.dependencies,
4853
+ ...pkg.devDependencies
4854
+ };
4855
+ } catch {}
4856
+ return detectSupabase(deps, existsSync, cwd).projectUrl;
4857
+ }
4032
4858
  // src/index.ts
4033
4859
  const ENV_FILE_CANDIDATES = [
4034
4860
  ".env",
@@ -4280,7 +5106,10 @@ function resolveInitDeps(options) {
4280
5106
  })),
4281
5107
  framework: "unknown",
4282
5108
  layout: "app",
4283
- authWiring: renderAuthWiring("unknown")
5109
+ authWiring: renderAuthWiring("unknown"),
5110
+ renderConfig: void 0,
5111
+ commentedEnv: [],
5112
+ extraPackages: []
4284
5113
  };
4285
5114
  }
4286
5115
  /**
@@ -4293,7 +5122,42 @@ function resolveInitDeps(options) {
4293
5122
  function renderDetectionLines(detection) {
4294
5123
  const from = (source) => source ? ` (from ${source})` : "";
4295
5124
  const frameworkNote = detection.frameworkForced ? " (--framework)" : from(detection.sources.framework);
4296
- return ` Framework: ${FRAMEWORK_LABELS[detection.framework]}${frameworkNote}\n ORM: ${detection.orm}${from(detection.sources.orm)}\n Auth: ${detection.auth}${from(detection.sources.auth)}${detection.authWired ? " (wired)" : ""}\n`;
5125
+ return ` Framework: ${FRAMEWORK_LABELS[detection.framework]}${frameworkNote}\n ORM: ${detection.orm}${from(detection.sources.orm)}\n` + (detection.authNote === void 0 ? ` Auth: ${detection.auth}${from(detection.sources.auth)}${detection.authWired ? " (wired)" : ""}\n` : ` Auth: ${detection.authNote}\n`);
5126
+ }
5127
+ /**
5128
+ * Supabase Auth is never inferred from dependencies (supabase-js is often
5129
+ * there for storage alone, and the Drizzle path must not change). A Supabase
5130
+ * app on the no-ORM path with no other auth library opts into it here.
5131
+ */
5132
+ function effectiveAuth(detected, noOrm) {
5133
+ return detected === "unknown" && noOrm?.noOrm.supabase.present ? "supabase" : detected;
5134
+ }
5135
+ function authNoteFor(noOrm, framework) {
5136
+ return noOrm && framework === "unknown" ? "not needed for the Edge Function" : void 0;
5137
+ }
5138
+ function noOrmTarget(options, deps, appDeps, orm) {
5139
+ if (orm !== "unknown" || options.schemaFlag) return null;
5140
+ const supabase = detectSupabase(appDeps, deps.fileExists, options.cwd, deps.readFile);
5141
+ return supabase.present || options.noOrm ? { noOrm: {
5142
+ appDeps,
5143
+ supabase
5144
+ } } : null;
5145
+ }
5146
+ const NO_SUPABASE_URL_HELP = "Couldn't find your Supabase project URL. Pass it: npx clivly connect --supabase --project-url https://<project-ref>.supabase.co\n";
5147
+ async function connectSupabase(argv) {
5148
+ const projectUrl = resolveSupabaseProjectUrl(process.cwd(), flagValue(argv, "--project-url"));
5149
+ if (!projectUrl) {
5150
+ process.stdout.write(NO_SUPABASE_URL_HELP);
5151
+ return 1;
5152
+ }
5153
+ const { code } = await runSupabaseConnect({
5154
+ projectUrl,
5155
+ fetch,
5156
+ out: (text) => {
5157
+ process.stdout.write(text);
5158
+ }
5159
+ });
5160
+ return code;
4297
5161
  }
4298
5162
  async function acquireSchema(options, deps) {
4299
5163
  const { out } = deps;
@@ -4308,7 +5172,9 @@ async function acquireSchema(options, deps) {
4308
5172
  }));
4309
5173
  const detected = detectAcrossWorkspace(appDeps, workspacePackages);
4310
5174
  const framework = options.frameworkFlag ?? detected.framework;
4311
- const { auth, orm, sources } = detected;
5175
+ const { orm, sources } = detected;
5176
+ const noOrm = noOrmTarget(options, deps, appDeps, orm);
5177
+ const auth = effectiveAuth(detected.auth, noOrm);
4312
5178
  deps.framework = framework;
4313
5179
  const layout = deps.resolveAppLayout(options.cwd, deps.fileExists);
4314
5180
  deps.layout = layout;
@@ -4316,6 +5182,7 @@ async function acquireSchema(options, deps) {
4316
5182
  deps.authWiring = renderAuthWiring(auth, auth === "better-auth" ? authInstanceFromFlag(options.authImportFlag) ?? await deps.probeAuth(options.cwd) : null);
4317
5183
  out(renderDetectionLines({
4318
5184
  auth,
5185
+ authNote: authNoteFor(noOrm, framework),
4319
5186
  authWired: deps.authWiring.complete,
4320
5187
  framework,
4321
5188
  frameworkForced: options.frameworkFlag !== void 0,
@@ -4327,6 +5194,7 @@ async function acquireSchema(options, deps) {
4327
5194
  if (frameworkCaution) out(`\n${frameworkCaution}`);
4328
5195
  if (auth === "better-auth" && !deps.authWiring.complete) out("\n ⚠️ Could not locate your better-auth instance.\n The verify route will import a placeholder path that does not\n resolve. Point it at the real module with:\n\n clivly init --force --auth-import <specifier>\n\n Accepts an alias ($lib/server/auth, @/lib/auth), a package name,\n or a project-relative path (src/lib/server/auth).\n");
4329
5196
  out("\n");
5197
+ if (noOrm) return noOrm;
4330
5198
  if (orm !== "drizzle" && !options.schemaFlag) {
4331
5199
  out(`clivly init currently generates config for Drizzle only. Detected ORM: ${orm}\n`);
4332
5200
  out(workspaceHint("orm", workspacePackages.length));
@@ -4377,11 +5245,13 @@ function mutationsFor(options, deps, plan) {
4377
5245
  authWiring: deps.authWiring,
4378
5246
  plan,
4379
5247
  readFile: deps.readFile,
4380
- readEnv: deps.readEnv
5248
+ readEnv: deps.readEnv,
5249
+ renderConfig: deps.renderConfig,
5250
+ commentedEnv: deps.commentedEnv
4381
5251
  });
4382
5252
  }
4383
- function applyMutations(options, deps, mutations) {
4384
- for (const file of mutations.files) {
5253
+ function applyFiles(options, deps, files) {
5254
+ for (const file of files) {
4385
5255
  if (file.action === "unchanged") {
4386
5256
  deps.out(` · ${file.path} already up to date\n`);
4387
5257
  continue;
@@ -4393,6 +5263,9 @@ function applyMutations(options, deps, mutations) {
4393
5263
  deps.writeConfig(join(options.cwd, file.path), file.contents);
4394
5264
  deps.out(` ✓ ${file.path}\n`);
4395
5265
  }
5266
+ }
5267
+ function applyMutations(options, deps, mutations) {
5268
+ applyFiles(options, deps, mutations.files);
4396
5269
  if (mutations.env.action === "skip") deps.out(" • .env already has every CLIVLY_* key — skipped\n");
4397
5270
  else {
4398
5271
  deps.writeEnv(options.cwd, mutations.env.contents);
@@ -4472,7 +5345,11 @@ function resolveRuntimeInstallSpec(deps, env = process.env) {
4472
5345
  async function scaffold(options, deps, plan) {
4473
5346
  const { out } = deps;
4474
5347
  const pm = deps.detectPackageManager(options.cwd);
4475
- const packages = [resolveRuntimeInstallSpec(deps), ...deps.authWiring.packages];
5348
+ const packages = [
5349
+ resolveRuntimeInstallSpec(deps),
5350
+ ...deps.authWiring.packages,
5351
+ ...deps.extraPackages
5352
+ ];
4476
5353
  const mutations = mutationsFor(options, deps, plan);
4477
5354
  const shadowing = shadowedAppDirError(options.cwd, deps.framework, mutations.files.map((file) => file.path), deps.fileExists);
4478
5355
  if (shadowing) {
@@ -4511,6 +5388,166 @@ async function scaffold(options, deps, plan) {
4511
5388
  printNextSteps(out, deps.authWiring.complete, loginRan, envFileFor(initFramework), initFramework === "sveltekit" && deps.authWiring.hostImport !== null);
4512
5389
  return 0;
4513
5390
  }
5391
+ const DATABASE_URL_PLACEHOLDER = {
5392
+ key: "DATABASE_URL",
5393
+ block: "# Postgres connection string clivly.config.ts reads its schema and rows with\n# (Supabase: Project Settings → Database → Connection string). Uncomment and set:\n# DATABASE_URL=postgresql://postgres:[YOUR-PASSWORD]@db.<project-ref>.supabase.co:5432/postgres"
5394
+ };
5395
+ const SUPABASE_SECRETS_LOCATION = "Supabase dashboard → Edge Functions → Secrets (on Lovable: the Secrets panel)";
5396
+ function sqlDriverFor(appDeps) {
5397
+ if ("postgres" in appDeps) return {
5398
+ driver: "postgres",
5399
+ install: []
5400
+ };
5401
+ if ("pg" in appDeps) return {
5402
+ driver: "pg",
5403
+ install: []
5404
+ };
5405
+ return {
5406
+ driver: "postgres",
5407
+ install: ["postgres"]
5408
+ };
5409
+ }
5410
+ /**
5411
+ * `clivly init` for an app with no ORM: read the live schema (connection
5412
+ * string, then the linked Supabase CLI), then write either the server config
5413
+ * and route files or, for an SPA or when no schema could be read, the Supabase
5414
+ * Edge Function in its deploy-first form.
5415
+ */
5416
+ async function runNoOrmInit(options, deps, target) {
5417
+ const { out } = deps;
5418
+ const { supabase } = target;
5419
+ if (supabase.present) out(` Supabase: detected${supabase.projectUrl ? ` (${supabase.projectUrl})` : ""}\n\n`);
5420
+ if (!supabase.present && deps.framework === "unknown") {
5421
+ out("clivly init doesn't recognise your framework yet (looked for Next.js, TanStack Start, SvelteKit, Remix, Nuxt). Without one, --no-orm needs a Supabase project to host the Edge Function.\n");
5422
+ return 1;
5423
+ }
5424
+ const connection = resolveConnectionString(options.processEnv ?? process.env, deps.readFile, options.cwd);
5425
+ const read = options.readLiveSchema ?? ((opts) => readLiveSchema({
5426
+ ...opts,
5427
+ connect: defaultConnect$1(options.cwd),
5428
+ runSupabaseCli: defaultRunSupabaseCli(options.cwd)
5429
+ }));
5430
+ const failures = /* @__PURE__ */ new Set();
5431
+ const tables = await read({
5432
+ connectionString: connection?.value,
5433
+ connectionLabel: connection?.label,
5434
+ onFailure: (reason) => failures.add(reason),
5435
+ out,
5436
+ supabaseProject: supabaseProjectState(supabase.present, deps.fileExists, options.cwd)
5437
+ });
5438
+ if (tables) out(` Schema: live database (${tables.length} tables)\n\n`);
5439
+ const source = {
5440
+ connectionLabel: connection?.label ?? null,
5441
+ driverMissing: failures.has("driver_missing")
5442
+ };
5443
+ if (tables && deps.framework !== "unknown") return scaffoldSqlServer(options, deps, target.appDeps, tables, source);
5444
+ if (!supabase.present) {
5445
+ out(source.driverMissing ? "Couldn't read your schema: install `postgres` or `pg` in this app, then re-run `clivly init --no-orm`.\n" : "Couldn't read your schema. Set DATABASE_URL to your Postgres connection string and re-run `clivly init --no-orm`.\n");
5446
+ return 1;
5447
+ }
5448
+ return writeSupabaseFunction(options, deps, tables, source);
5449
+ }
5450
+ async function scaffoldSqlServer(options, deps, appDeps, tables, source) {
5451
+ const plan = planSqlInit(tables, {
5452
+ contactTable: options.contactTableFlag,
5453
+ companyTable: options.companyTableFlag
5454
+ });
5455
+ const { contact } = plan;
5456
+ if (!contact) {
5457
+ printNoContactGuidance(deps.out, plan, options);
5458
+ return options.dryRun ? 0 : 1;
5459
+ }
5460
+ const { driver, install } = sqlDriverFor(appDeps);
5461
+ deps.renderConfig = (renderable) => renderSqlConfig({
5462
+ ...renderable,
5463
+ driver
5464
+ });
5465
+ deps.commentedEnv = source.connectionLabel === null ? [DATABASE_URL_PLACEHOLDER] : [];
5466
+ deps.extraPackages = install;
5467
+ const renderable = {
5468
+ ...plan,
5469
+ contact
5470
+ };
5471
+ printPlan(deps.out, renderable);
5472
+ const code = await scaffold(options, deps, renderable);
5473
+ if (code === 0 && !options.dryRun && !options.diff) printSqlServerSteps(deps, source);
5474
+ return code;
5475
+ }
5476
+ function printSqlServerSteps(deps, source) {
5477
+ if (source.connectionLabel === null) deps.out("\n ! Set DATABASE_URL (your Supabase connection string) before starting the app —\n clivly.config.ts reads its schema and rows with it.\n");
5478
+ if (deps.authWiring.envKeys.length > 0) deps.out(`\n The auth/verify route reads ${describeEnvKeys(deps.authWiring)} from the environment.\n`);
5479
+ }
5480
+ function supabaseFunctionMutations(options, deps, contactTable, version, existingToml) {
5481
+ const tomlPath = SUPABASE_CONFIG_TOML;
5482
+ const { files } = renderSupabaseFunction({
5483
+ contactTable,
5484
+ existingConfigToml: existingToml,
5485
+ version
5486
+ });
5487
+ return Object.entries(files).map(([path, contents]) => {
5488
+ if (path !== tomlPath) return {
5489
+ path,
5490
+ contents,
5491
+ action: fileAction(deps.readFile(join(options.cwd, path)), contents, options.force)
5492
+ };
5493
+ let action = "patch";
5494
+ if (existingToml === null) action = "create";
5495
+ else if (existingToml === contents) action = "unchanged";
5496
+ return {
5497
+ path,
5498
+ contents,
5499
+ action
5500
+ };
5501
+ });
5502
+ }
5503
+ function writeSupabaseFunction(options, deps, tables, source) {
5504
+ const { out } = deps;
5505
+ const version = deps.readOwnVersion();
5506
+ if (!version) {
5507
+ out("Couldn't read this CLI's version, so the Edge Function can't pin `npm:clivly@<version>`. Reinstall clivly and re-run `clivly init`.\n");
5508
+ return 1;
5509
+ }
5510
+ const contactTable = tables ? planSqlInit(tables, { contactTable: options.contactTableFlag }).contact?.tableName : void 0;
5511
+ const existingToml = deps.readFile(join(options.cwd, SUPABASE_CONFIG_TOML));
5512
+ const files = supabaseFunctionMutations(options, deps, contactTable, version, existingToml);
5513
+ if (options.dryRun || options.diff) {
5514
+ out("\nDry run — nothing was written.\n\n");
5515
+ for (const file of files) out(` ${file.action.padEnd(9)} ${file.path}\n`);
5516
+ out("\nRe-run without --dry-run to apply.\n");
5517
+ return 0;
5518
+ }
5519
+ out("\nWriting the Clivly Edge Function:\n");
5520
+ applyFiles(options, deps, files);
5521
+ if (tables) out(`\n Contacts: ${contactTable && contactTable !== "auth.users" ? contactTable : "your Supabase Auth users (auth.users)"}\n`);
5522
+ else {
5523
+ out("\n Couldn't read your schema from here, so the function is written deploy-first:\n contacts default to your Supabase Auth users (auth.users), and the function\n reports your other tables to clivly.com once it is deployed.\n");
5524
+ if (deps.framework !== "unknown") out(` ${routeFilesHint(source, FRAMEWORK_LABELS[deps.framework])}\n`);
5525
+ }
5526
+ if (existingToml !== null && clivlyBlockVerifiesJwt(existingToml)) out(`\n ! ${SUPABASE_CONFIG_TOML} has [functions.clivly] with verify_jwt = true.\n Set it to verify_jwt = false: Clivly calls the function with its own signed
5527
+ request, not a Supabase user JWT, so the gateway would reject every call.
5528
+ `);
5529
+ printDeployFirstSteps(out);
5530
+ return 0;
5531
+ }
5532
+ function routeFilesHint(source, framework) {
5533
+ if (source.driverMissing) return `To generate route files for ${framework} instead, install \`postgres\` or \`pg\` in this app, then re-run.`;
5534
+ if (source.connectionLabel) return `Check ${source.connectionLabel}, then re-run to generate route files for ${framework} instead.`;
5535
+ return `Re-run with DATABASE_URL set to generate route files for ${framework} instead.`;
5536
+ }
5537
+ function printDeployFirstSteps(out) {
5538
+ out("\nNext steps:\n");
5539
+ out(` 1. Set CLIVLY_SECRET_KEY on the function (from ${CREDENTIALS_LOCATION}),\n in ${SUPABASE_SECRETS_LOCATION}, or from a terminal:\n\n npx supabase secrets set CLIVLY_SECRET_KEY=…
5540
+
5541
+ `);
5542
+ out(" 2. Deploy the function (on Lovable: push the change):\n\n npx supabase functions deploy clivly\n\n");
5543
+ out(" 3. Connect it to Clivly (this sends its first heartbeat):\n\n npx clivly connect --supabase\n\n");
5544
+ out(` 4. Generate the trigger secret at ${SYNC_SECRET_LOCATION},\n then set it on the function. No redeploy needed:
5545
+
5546
+ npx supabase secrets set CLIVLY_SYNC_TRIGGER_SECRET=…
5547
+
5548
+ `);
5549
+ out(` 5. ${FIRST_SYNC_LOCATION}\n`);
5550
+ }
4514
5551
  function normalizeAppRoot(options) {
4515
5552
  const resolution = (options.resolveTargetApp ?? resolveTargetApp)(options.cwd);
4516
5553
  const out = options.out ?? ((line) => process.stdout.write(line));
@@ -4539,6 +5576,7 @@ async function runInit(options) {
4539
5576
  const deps = resolveInitDeps(resolvedOptions);
4540
5577
  const acquired = await acquireSchema(resolvedOptions, deps);
4541
5578
  if ("code" in acquired) return acquired.code;
5579
+ if ("noOrm" in acquired) return runNoOrmInit(resolvedOptions, deps, acquired.noOrm);
4542
5580
  const dbOverride = importOverride(resolvedOptions.dbImportFlag, "db");
4543
5581
  const plan = planInit(dbOverride ? {
4544
5582
  ...acquired,
@@ -4777,6 +5815,7 @@ function runInitFromArgv(argv, cwd) {
4777
5815
  diff: argv.includes("--diff"),
4778
5816
  yes: argv.includes("--yes"),
4779
5817
  noLogin: argv.includes("--no-login"),
5818
+ noOrm: argv.includes("--no-orm"),
4780
5819
  openBrowser: !argv.includes("--no-browser"),
4781
5820
  schemaFlag: flagValue(argv, "--schema"),
4782
5821
  frameworkFlag,
@@ -4786,6 +5825,15 @@ function runInitFromArgv(argv, cwd) {
4786
5825
  companyTableFlag: flagValue(argv, "--company-table")
4787
5826
  });
4788
5827
  }
5828
+ function failedEngineCheck() {
5829
+ if (process.env.CLIVLY_SKIP_ENGINE_CHECK) return false;
5830
+ const engineProblem = engineError(process.version, readOwnEngines());
5831
+ if (engineProblem) {
5832
+ process.stderr.write(engineProblem);
5833
+ return true;
5834
+ }
5835
+ return false;
5836
+ }
4789
5837
  async function main(argv) {
4790
5838
  const [command, ...rest] = argv;
4791
5839
  if (command === "-h" || command === "--help" || isHelpRequest(rest)) {
@@ -4796,13 +5844,7 @@ async function main(argv) {
4796
5844
  process.stdout.write(`${readOwnVersion() ?? "unknown"}\n`);
4797
5845
  return 0;
4798
5846
  }
4799
- if (!process.env.CLIVLY_SKIP_ENGINE_CHECK) {
4800
- const engineProblem = engineError(process.version, readOwnEngines());
4801
- if (engineProblem) {
4802
- process.stderr.write(engineProblem);
4803
- return 1;
4804
- }
4805
- }
5847
+ if (failedEngineCheck()) return 1;
4806
5848
  let cliEnvFiles = [];
4807
5849
  try {
4808
5850
  cliEnvFiles = (await loadCliConfig(process.cwd()))?.envFiles ?? [];
@@ -4822,6 +5864,7 @@ async function main(argv) {
4822
5864
  case "ping":
4823
5865
  case "doctor":
4824
5866
  case "connect":
5867
+ if (command === "connect" && rest.includes("--supabase")) return await connectSupabase(rest);
4825
5868
  if (command !== "status") process.stderr.write(`\`clivly ${command}\` is a deprecated alias that runs part of \`clivly status\`. Prefer \`clivly status\`.\n`);
4826
5869
  return await runStatus({
4827
5870
  cwd: process.cwd(),