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