clivly 0.23.1 → 0.24.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +28 -0
  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/{auth-adapter-BIa-ZyVV.d.mts → auth-adapter-C17dzlzF.d.cts} +1 -1
  5. package/{auth-adapter-DwtMJb7D.d.cts → auth-adapter-CizFv7oU.d.mts} +1 -1
  6. package/auth-better-auth.d.cts +1 -1
  7. package/auth-better-auth.d.mts +1 -1
  8. package/auth-clerk.d.cts +1 -1
  9. package/auth-clerk.d.mts +1 -1
  10. package/auth-supabase.cjs +121 -0
  11. package/auth-supabase.d.cts +23 -0
  12. package/auth-supabase.d.mts +23 -0
  13. package/auth-supabase.mjs +119 -0
  14. package/auth-workos.d.cts +1 -1
  15. package/auth-workos.d.mts +1 -1
  16. package/core-adapter.d.cts +1 -1
  17. package/core-adapter.d.mts +1 -1
  18. package/core-auth-adapter.d.cts +1 -1
  19. package/core-auth-adapter.d.mts +1 -1
  20. package/core-mapping-score.d.cts +1 -0
  21. package/core-sync-engine.cjs +1 -1
  22. package/core-sync-engine.mjs +1 -1
  23. package/core-types.cjs +5 -1
  24. package/core-types.d.cts +2 -2
  25. package/core-types.d.mts +2 -2
  26. package/core-types.mjs +1 -1
  27. package/core-view-compiler.cjs +1 -1
  28. package/core-view-compiler.mjs +1 -1
  29. package/core.cjs +9 -5
  30. package/core.d.cts +6 -6
  31. package/core.d.mts +6 -6
  32. package/core.mjs +6 -6
  33. package/discover-BZIPXl23.cjs +200 -0
  34. package/discover-CFIi43Qn.mjs +195 -0
  35. package/drizzle.cjs +1 -1
  36. package/drizzle.d.cts +2 -2
  37. package/drizzle.d.mts +2 -2
  38. package/drizzle.mjs +1 -1
  39. package/executor-CJEWurjZ.mjs +23 -0
  40. package/executor-CU-jRgpC.cjs +40 -0
  41. package/index-CZkp8TV4.d.cts +108 -0
  42. package/index-Cnrz4ywf.d.mts +108 -0
  43. package/{index-Bh7o2J7K.d.mts → index-DOoX2GgI.d.mts} +3 -3
  44. package/{index-DRRTE5IJ.d.cts → index-uFDiQEjj.d.cts} +231 -5
  45. package/index.cjs +903 -30
  46. package/index.d.cts +27 -0
  47. package/index.d.mts +26 -0
  48. package/index.mjs +901 -28
  49. package/{internal-CdfVkh4O.d.mts → internal-D_2q2BOB.d.mts} +1 -1
  50. package/internal-adapter.d.cts +1 -1
  51. package/internal-adapter.d.mts +1 -1
  52. package/internal-auth-adapter.d.cts +1 -1
  53. package/internal-auth-adapter.d.mts +1 -1
  54. package/internal-sync-engine.cjs +1 -1
  55. package/internal-sync-engine.mjs +1 -1
  56. package/internal-types.cjs +5 -1
  57. package/internal-types.d.cts +2 -2
  58. package/internal-types.d.mts +2 -2
  59. package/internal-types.mjs +1 -1
  60. package/internal-view-compiler.cjs +1 -1
  61. package/internal-view-compiler.mjs +1 -1
  62. package/internal.cjs +9 -5
  63. package/internal.d.cts +5 -6
  64. package/internal.d.mts +6 -6
  65. package/internal.mjs +6 -6
  66. package/introspector-BwYgHGcS.cjs +363 -0
  67. package/introspector-Bz52xOUr.mjs +334 -0
  68. package/{namespace-probe-JuHriruA.d.mts → namespace-probe--GvxJ06J.d.mts} +8 -1
  69. package/package.json +31 -1
  70. package/projection-guard-7AMY0aCk.mjs +389 -0
  71. package/projection-guard-D8VUhCz7.cjs +508 -0
  72. package/{projection-sql-DQQdjw9I.mjs → projection-sql-2joBkLz2.mjs} +13 -3
  73. package/{projection-sql-BkrHR2ea.cjs → projection-sql-DS5sVTY-.cjs} +18 -2
  74. package/sdk-Bzkr24NW.cjs +207 -0
  75. package/sdk-D2WwGBzk.mjs +178 -0
  76. package/sdk.cjs +8 -6
  77. package/sdk.d.cts +7 -1
  78. package/sdk.d.mts +7 -1
  79. package/sdk.mjs +3 -2
  80. package/sql.cjs +13 -0
  81. package/sql.d.cts +2 -0
  82. package/sql.d.mts +2 -0
  83. package/sql.mjs +4 -0
  84. package/{sdk-BkMDOfCk.mjs → src-Dq2nY1Sj.mjs} +36 -495
  85. package/{sdk-BOarpe5I.cjs → src-X0-yIA3O.cjs} +63 -546
  86. package/supabase.cjs +255 -0
  87. package/supabase.d.cts +19 -0
  88. package/supabase.d.mts +19 -0
  89. package/supabase.mjs +254 -0
  90. package/{sync-engine-yFLEyId3.mjs → sync-engine-D0mJUeqP.mjs} +1 -1
  91. package/{sync-engine-DNSoZeo0.cjs → sync-engine-hU041kXO.cjs} +1 -1
  92. package/types-KMH5D5Lg.mjs +32 -0
  93. package/{namespace-probe-CcL6Wj8E.d.cts → types-UR-tT4c1.d.cts} +52 -45
  94. package/{types-BBfwsDxe.d.cts → types-f-Vcv-pl.d.cts} +18 -2
  95. package/{types-BBfwsDxe.d.mts → types-f-Vcv-pl.d.mts} +18 -2
  96. package/types-kR1kUlmz.cjs +67 -0
  97. package/{view-compiler-CSHSqZl7.mjs → view-compiler-BhKiezRH.mjs} +1 -1
  98. package/{view-compiler-NqiortOA.cjs → view-compiler-DgZadq1F.cjs} +1 -1
  99. package/vite.d.cts +1 -1
  100. package/vite.d.mts +1 -1
  101. package/internal-D7qVRIFb.d.cts +0 -228
  102. package/types-8KSw2AWg.mjs +0 -8
  103. 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_discover = require("./discover-BZIPXl23.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-X0-yIA3O.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",
@@ -770,11 +772,11 @@ async function runDev(options) {
770
772
  }
771
773
  // src/dev-override.ts
772
774
  const TRIGGER_URL_PATH = "/clivly/sdk/trigger-url";
773
- const HTTP_UNAUTHORIZED = 401;
774
- const HTTP_NOT_FOUND = 404;
775
+ const HTTP_UNAUTHORIZED$1 = 401;
776
+ const HTTP_NOT_FOUND$1 = 404;
775
777
  function kindForStatus(status) {
776
- if (status === HTTP_UNAUTHORIZED) return "unauthorized";
777
- if (status === HTTP_NOT_FOUND) return "not_enabled";
778
+ if (status === HTTP_UNAUTHORIZED$1) return "unauthorized";
779
+ if (status === HTTP_NOT_FOUND$1) return "not_enabled";
778
780
  return "unexpected_response";
779
781
  }
780
782
  function failureFor(status) {
@@ -1355,6 +1357,8 @@ Usage:
1355
1357
  Deprecated aliases — each runs part of \`clivly status\` and still works:
1356
1358
  clivly ping credential + reachability
1357
1359
  clivly connect the above, plus config and trigger URL
1360
+ clivly connect --supabase check a Supabase Edge Function is live and has
1361
+ contacts to sync (--project-url <url> to override)
1358
1362
  clivly doctor config, setup checks and edge safety
1359
1363
 
1360
1364
  Prefer \`clivly status\`: it runs the whole ladder and tells you which step you
@@ -1369,7 +1373,7 @@ Usage:
1369
1373
  clivly init [--force] [--dry-run] [--diff] [--yes] [--no-login] [--no-browser]
1370
1374
  [--schema <path|package>] [--db-import <specifier>]
1371
1375
  [--auth-import <specifier>] [--contact-table <table>]
1372
- [--company-table <table>] [--framework <name>]
1376
+ [--company-table <table>] [--framework <name>] [--no-orm]
1373
1377
 
1374
1378
  Scaffolds clivly.config.ts, the Clivly route files, and .env placeholders.
1375
1379
  Detects your framework, ORM, auth adapter and app layout from the project.
@@ -1388,6 +1392,9 @@ Options:
1388
1392
  --auth-import <s> Module specifier exporting your auth instance
1389
1393
  --contact-table <t> Table to map as contacts
1390
1394
  --company-table <t> Table to map as companies
1395
+ --no-orm Read the schema from the live database (DATABASE_URL)
1396
+ instead of an ORM schema. Implied for Supabase apps
1397
+ with no ORM; an SPA gets a Supabase Edge Function
1391
1398
  `,
1392
1399
  add: `clivly add widget — scaffold the chat-session route
1393
1400
 
@@ -1469,7 +1476,7 @@ function isHelpRequest(argv) {
1469
1476
  }
1470
1477
  function helpFor(command) {
1471
1478
  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";
1479
+ 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
1480
  }
1474
1481
  // src/install.ts
1475
1482
  const defaultRun = (command, args, cwd) => new Promise((resolvePromise, reject) => {
@@ -1639,6 +1646,222 @@ function loadEnv(cwd, env = process.env, options = {}) {
1639
1646
  files
1640
1647
  };
1641
1648
  }
1649
+ // src/live-schema.ts
1650
+ const CONNECTION_KEYS = ["DATABASE_URL", "SUPABASE_DB_URL"];
1651
+ const CONNECTION_ENV_FILES = [".env.local", ".env"];
1652
+ /**
1653
+ * `db query` against the linked project, machine-readable, non-interactive.
1654
+ * `--linked` is accepted by every CLI that has `db query` (v3 keeps it as a
1655
+ * hidden alias of a bare `--remote`), `--output json` prints the rows, and
1656
+ * `--yes` answers the hosted-database confirmation a script cannot.
1657
+ */
1658
+ const SUPABASE_CLI_QUERY_ARGS = [
1659
+ "db",
1660
+ "query",
1661
+ "--linked",
1662
+ "--output",
1663
+ "json",
1664
+ "--yes"
1665
+ ];
1666
+ const CLI_TIMEOUT_MS = 6e4;
1667
+ const CONNECT_TIMEOUT_SECONDS = 10;
1668
+ const MS_PER_SECOND = 1e3;
1669
+ /** The connection string and where it came from, or null when none is set. */
1670
+ function resolveConnectionString(env, readFile, cwd) {
1671
+ for (const key of CONNECTION_KEYS) {
1672
+ const value = env[key]?.trim();
1673
+ if (value) return {
1674
+ label: key,
1675
+ value
1676
+ };
1677
+ }
1678
+ for (const name of CONNECTION_ENV_FILES) {
1679
+ const contents = readFile((0, node_path.join)(cwd, name));
1680
+ if (contents === null) continue;
1681
+ const parsed = parseEnv(contents);
1682
+ for (const key of CONNECTION_KEYS) {
1683
+ const value = parsed[key]?.trim();
1684
+ if (value) return {
1685
+ label: key,
1686
+ value
1687
+ };
1688
+ }
1689
+ }
1690
+ return null;
1691
+ }
1692
+ const JSON_START = /[[{]/;
1693
+ const POSTGRES_ARRAY = /^\{(.*)\}$/s;
1694
+ function normaliseValue(value) {
1695
+ if (typeof value !== "string") return value;
1696
+ const match = POSTGRES_ARRAY.exec(value);
1697
+ if (!match) return value;
1698
+ const inner = match[1] ?? "";
1699
+ return inner === "" ? [] : inner.split(",").map((part) => part.replaceAll("\"", ""));
1700
+ }
1701
+ /** The rows `supabase db query --output json` printed, in either shape. */
1702
+ function parseSupabaseCliRows(stdout) {
1703
+ const start = stdout.search(JSON_START);
1704
+ if (start === -1) throw new Error("supabase db query printed no JSON");
1705
+ const parsed = JSON.parse(stdout.slice(start));
1706
+ const rows = Array.isArray(parsed) || parsed === null || typeof parsed !== "object" || !("rows" in parsed) ? parsed : parsed.rows;
1707
+ if (!Array.isArray(rows)) throw new Error("supabase db query printed no rows");
1708
+ return rows.map((row) => Object.fromEntries(Object.entries(row).map(([k, v]) => [k, normaliseValue(v)])));
1709
+ }
1710
+ const quoteLiteral = (value) => `'${value.replaceAll("'", "''")}'`;
1711
+ function literalFor(param) {
1712
+ if (Array.isArray(param)) return `ARRAY[${param.map((p) => quoteLiteral(String(p))).join(", ")}]`;
1713
+ if (param === null || param === void 0) return "null";
1714
+ return quoteLiteral(String(param));
1715
+ }
1716
+ const PARAM_REF = /\$(\d+)/g;
1717
+ /**
1718
+ * An executor over `supabase db query`. The CLI takes one SQL string and no
1719
+ * bind parameters, so parameters are inlined as quoted literals. Only the
1720
+ * catalog queries discovery issues go through here, and their one parameter
1721
+ * is the list of schema names.
1722
+ */
1723
+ function supabaseCliExecutor(run) {
1724
+ return { async query(text, params) {
1725
+ const sql = params ? text.replace(PARAM_REF, (_, n) => literalFor(params[Number(n) - 1])) : text;
1726
+ const result = await run([...SUPABASE_CLI_QUERY_ARGS, sql]);
1727
+ if (result.code !== 0) throw new SupabaseCliFailed(result.code);
1728
+ return parseSupabaseCliRows(result.stdout);
1729
+ } };
1730
+ }
1731
+ var SupabaseCliFailed = class extends Error {
1732
+ code;
1733
+ constructor(code) {
1734
+ super(`supabase exited with ${code}`);
1735
+ this.code = code;
1736
+ }
1737
+ };
1738
+ async function discoverOrNull(executor) {
1739
+ const tables = await require_discover.discoverFromSql(executor);
1740
+ return tables.length === 0 ? null : tables;
1741
+ }
1742
+ async function fromConnectionString(opts, out) {
1743
+ const label = opts.connectionLabel ?? "DATABASE_URL";
1744
+ let connection = null;
1745
+ try {
1746
+ connection = await (opts.connect ?? missingDriver)(opts.connectionString);
1747
+ return await discoverOrNull(connection.executor);
1748
+ } catch (error) {
1749
+ opts.onFailure?.(error instanceof DriverMissing ? "driver_missing" : "connect_failed");
1750
+ 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`);
1751
+ return null;
1752
+ } finally {
1753
+ await connection?.close().catch(() => void 0);
1754
+ }
1755
+ }
1756
+ async function fromSupabaseCli(run, out, onFailure) {
1757
+ try {
1758
+ return await discoverOrNull(supabaseCliExecutor(run));
1759
+ } catch (error) {
1760
+ if (!(error instanceof SupabaseCliFailed && error.code === 127)) {
1761
+ onFailure?.("cli_failed");
1762
+ out(" Couldn't read the schema through the Supabase CLI (is this project linked? `supabase link`).\n");
1763
+ }
1764
+ return null;
1765
+ }
1766
+ }
1767
+ async function readLiveSchema(opts) {
1768
+ const out = opts.out ?? (() => void 0);
1769
+ if (opts.connectionString) {
1770
+ const tables = await fromConnectionString({
1771
+ ...opts,
1772
+ connectionString: opts.connectionString
1773
+ }, out);
1774
+ if (tables) return tables;
1775
+ }
1776
+ if (opts.runSupabaseCli) return fromSupabaseCli(opts.runSupabaseCli, out, opts.onFailure);
1777
+ return null;
1778
+ }
1779
+ var DriverMissing = class extends Error {};
1780
+ function missingDriver() {
1781
+ return Promise.reject(new DriverMissing());
1782
+ }
1783
+ async function importFromHost(cwd, name) {
1784
+ try {
1785
+ const resolved = (0, node_module.createRequire)((0, node_path.join)(cwd, "package.json")).resolve(name);
1786
+ const mod = await import((0, node_url.pathToFileURL)(resolved).href);
1787
+ return mod.default ?? mod;
1788
+ } catch {
1789
+ return null;
1790
+ }
1791
+ }
1792
+ /**
1793
+ * Opens the database with the driver the host app already has — `postgres`
1794
+ * first, then `pg`. The CLI ships neither, so an app with no driver gets the
1795
+ * "install one" message and falls through to the next source.
1796
+ */
1797
+ function defaultConnect$1(cwd) {
1798
+ return async (url) => {
1799
+ const postgres = await importFromHost(cwd, "postgres");
1800
+ if (typeof postgres === "function") {
1801
+ const sql = postgres(url, {
1802
+ prepare: false,
1803
+ max: 1,
1804
+ connect_timeout: CONNECT_TIMEOUT_SECONDS
1805
+ });
1806
+ return {
1807
+ executor: require_executor.postgresJsExecutor(sql),
1808
+ close: () => sql.end()
1809
+ };
1810
+ }
1811
+ const pg = await importFromHost(cwd, "pg");
1812
+ if (pg?.Client) {
1813
+ const client = new pg.Client({
1814
+ connectionString: url,
1815
+ connectionTimeoutMillis: CONNECT_TIMEOUT_SECONDS * MS_PER_SECOND
1816
+ });
1817
+ await client.connect();
1818
+ return {
1819
+ executor: require_executor.pgExecutor(client),
1820
+ close: () => client.end()
1821
+ };
1822
+ }
1823
+ throw new DriverMissing();
1824
+ };
1825
+ }
1826
+ /**
1827
+ * Runs `supabase` with an args array (no shell), in the app directory. A
1828
+ * missing binary (ENOENT) reports SUPABASE_CLI_MISSING rather than throwing.
1829
+ */
1830
+ function defaultRunSupabaseCli(cwd) {
1831
+ return (args) => new Promise((resolve) => {
1832
+ let stdout = "";
1833
+ let settled = false;
1834
+ const finish = (code) => {
1835
+ if (!settled) {
1836
+ settled = true;
1837
+ clearTimeout(timer);
1838
+ resolve({
1839
+ code,
1840
+ stdout
1841
+ });
1842
+ }
1843
+ };
1844
+ const child = (0, node_child_process.spawn)("supabase", args, {
1845
+ cwd,
1846
+ stdio: [
1847
+ "ignore",
1848
+ "pipe",
1849
+ "ignore"
1850
+ ]
1851
+ });
1852
+ const timer = setTimeout(() => {
1853
+ child.kill();
1854
+ finish(1);
1855
+ }, CLI_TIMEOUT_MS);
1856
+ child.stdout?.on("data", (chunk) => {
1857
+ stdout += chunk.toString("utf8");
1858
+ });
1859
+ child.on("error", (error) => {
1860
+ finish(error.code === "ENOENT" ? 127 : 1);
1861
+ });
1862
+ child.on("close", (code) => finish(code ?? 1));
1863
+ });
1864
+ }
1642
1865
  // src/secret-key-env.ts
1643
1866
  const SECRET_KEY_ENV = "CLIVLY_SECRET_KEY";
1644
1867
  const LEGACY_SECRET_KEY_ENV = "CLIVLY_API_KEY";
@@ -2276,7 +2499,7 @@ function renderEntity(key, entity) {
2276
2499
  fields: ${renderFields(entity.fields)}${renderRelationships(entity)},
2277
2500
  }`;
2278
2501
  }
2279
- function renderSource(role, entity, dbExpr) {
2502
+ function renderSource$1(role, entity, dbExpr) {
2280
2503
  const opts = entity.idField === null ? `{ entity: "${entity.tableName}", cursorField: "${entity.cursorField}" }` : `{ entity: "${entity.tableName}", cursorField: "${entity.cursorField}", idField: "${entity.idField}" }`;
2281
2504
  return ` ${role}: fromDrizzle(${dbExpr}, schema.${entity.moduleKey}, ${opts})`;
2282
2505
  }
@@ -2329,8 +2552,8 @@ function renderInitConfig(plan) {
2329
2552
  const dbExpr = renderDbExpr(plan);
2330
2553
  const entities = [renderEntity(plan.contact.moduleKey, plan.contact)];
2331
2554
  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));
2555
+ const sources = [renderSource$1("contacts", plan.contact, dbExpr)];
2556
+ if (plan.company) sources.push(renderSource$1("companies", plan.company, dbExpr));
2334
2557
  return `${renderTodoHeader(plan.todos)}${renderImports(plan)}
2335
2558
 
2336
2559
  const entities = defineClivlyConfig({
@@ -2425,6 +2648,28 @@ function workosWiring() {
2425
2648
  ${RESOLVE_USER}`
2426
2649
  };
2427
2650
  }
2651
+ function supabaseWiring() {
2652
+ return {
2653
+ complete: true,
2654
+ envKeys: ["SUPABASE_URL", "SUPABASE_ANON_KEY"],
2655
+ hostImport: null,
2656
+ imports: ["import { createSupabaseAuthAdapter } from \"clivly/auth/supabase\";"],
2657
+ packages: [],
2658
+ body: `const supabaseUrl = process.env.SUPABASE_URL || process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.VITE_SUPABASE_URL;
2659
+ const supabaseAnonKey = process.env.SUPABASE_ANON_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || process.env.VITE_SUPABASE_ANON_KEY || process.env.SUPABASE_PUBLISHABLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY || process.env.VITE_SUPABASE_PUBLISHABLE_KEY;
2660
+ const adapter =
2661
+ supabaseUrl && supabaseAnonKey
2662
+ ? createSupabaseAuthAdapter({ supabaseUrl, anonKey: supabaseAnonKey })
2663
+ : {
2664
+ getUser(_req: Request): never {
2665
+ throw new Error(
2666
+ "Clivly: the auth/verify route needs your Supabase project URL and anon key. Set SUPABASE_URL (or NEXT_PUBLIC_SUPABASE_URL / VITE_SUPABASE_URL) and SUPABASE_ANON_KEY (or NEXT_PUBLIC_SUPABASE_ANON_KEY / VITE_SUPABASE_ANON_KEY, or a *_SUPABASE_PUBLISHABLE_KEY)."
2667
+ );
2668
+ },
2669
+ };
2670
+ ${RESOLVE_USER}`
2671
+ };
2672
+ }
2428
2673
  function hostImportFor(instance) {
2429
2674
  if (instance === null) return {
2430
2675
  binding: "auth",
@@ -2452,6 +2697,7 @@ function renderAuthWiring(auth, authInstance = null) {
2452
2697
  case "clerk": return clerkWiring();
2453
2698
  case "workos": return workosWiring();
2454
2699
  case "better-auth": return betterAuthWiring(authInstance);
2700
+ case "supabase": return supabaseWiring();
2455
2701
  default: return STUB;
2456
2702
  }
2457
2703
  }
@@ -2754,7 +3000,7 @@ function planFiles(args) {
2754
3000
  const mutations = [];
2755
3001
  const bootPath = bootHookPath(args.framework, args.layout);
2756
3002
  const render = (path) => {
2757
- if (path === "clivly.config.ts") return renderInitConfig(args.plan);
3003
+ if (path === "clivly.config.ts") return (args.renderConfig ?? renderInitConfig)(args.plan);
2758
3004
  if (bootPath !== null && path === bootPath) return renderBootHook(args.framework, args.layout);
2759
3005
  const kind = path.includes("verify") ? "verify" : "tick";
2760
3006
  return renderRouteFile(args.framework, kind, args.authWiring, args.layout, parseTsconfig(args.readFile((0, node_path.join)(args.cwd, "tsconfig.json")) ?? "")?.paths);
@@ -2776,10 +3022,16 @@ function envAction(addedCount, existingLength) {
2776
3022
  function planEnv(args) {
2777
3023
  const existing = args.readEnv(args.cwd);
2778
3024
  const addedKeys = CLIVLY_ENV_KEYS.filter((entry) => !hasKey(existing, entry.key)).map((entry) => entry.key);
3025
+ let contents = appendEnvKeys(existing, CLIVLY_ENV_KEYS);
3026
+ for (const { block, key } of args.commentedEnv ?? []) if (!(hasKey(existing, key) || contents.includes(block))) {
3027
+ const lead = contents.length === 0 || contents.endsWith("\n") ? "" : "\n";
3028
+ contents = `${contents}${lead}${block}\n`;
3029
+ addedKeys.push(key);
3030
+ }
2779
3031
  return {
2780
3032
  path: ".env",
2781
3033
  addedKeys,
2782
- contents: appendEnvKeys(existing, CLIVLY_ENV_KEYS),
3034
+ contents,
2783
3035
  action: envAction(addedKeys.length, existing.length)
2784
3036
  };
2785
3037
  }
@@ -3078,6 +3330,294 @@ async function runPushSchema(options) {
3078
3330
  out(" Open Integrations → Mapping to map your tables.\n");
3079
3331
  return 0;
3080
3332
  }
3333
+ // src/render-sql-config.ts
3334
+ const AUTH_USERS = "auth.users";
3335
+ const EMAIL_COLUMNS = /* @__PURE__ */ new Set(["email", "email_address"]);
3336
+ const NON_IDENTIFIER = /[^A-Za-z0-9_$]/g;
3337
+ const NO_CURSOR_TODO = /^No updated_at-like column on "([^"]+)"/;
3338
+ /** An entity key for a table: its bare name, made a valid identifier. */
3339
+ function entityKeyFor(name, taken) {
3340
+ const bare = name.slice(name.lastIndexOf(".") + 1).replace(NON_IDENTIFIER, "_");
3341
+ const key = taken.has(bare) ? name.replace(NON_IDENTIFIER, "_") : bare;
3342
+ taken.add(key);
3343
+ return key;
3344
+ }
3345
+ function toDiscoveredSchema(tables) {
3346
+ const taken = /* @__PURE__ */ new Set();
3347
+ return {
3348
+ importPath: "your database",
3349
+ db: null,
3350
+ tables: tables.map((table) => ({
3351
+ tableName: table.name,
3352
+ moduleKey: entityKeyFor(table.name, taken),
3353
+ columns: (table.columnsMeta ?? table.columns.map((name) => ({ name }))).map((column) => {
3354
+ const meta = column;
3355
+ return {
3356
+ key: meta.name,
3357
+ dbName: meta.name,
3358
+ isPrimary: meta.isPrimaryKey ?? false,
3359
+ ...meta.type === void 0 ? {} : { type: meta.type },
3360
+ ...meta.nullable === void 0 ? {} : { nullable: meta.nullable },
3361
+ ...meta.references ? { references: meta.references } : {}
3362
+ };
3363
+ }),
3364
+ ...table.uniqueConstraints ? { uniqueConstraints: table.uniqueConstraints } : {}
3365
+ }))
3366
+ };
3367
+ }
3368
+ /**
3369
+ * The contact table for a live schema: Supabase Auth's `auth.users` when it is
3370
+ * there, else the Drizzle path's heuristic pick, else the first table with an
3371
+ * email column. Undefined when nothing qualifies.
3372
+ */
3373
+ function chooseSqlContactTable(tables) {
3374
+ if (tables.some((table) => table.name === AUTH_USERS)) return AUTH_USERS;
3375
+ const heuristic = planInit(toDiscoveredSchema(tables)).contact?.tableName;
3376
+ if (heuristic) return heuristic;
3377
+ return tables.find((table) => table.columns.some((column) => EMAIL_COLUMNS.has(column.toLowerCase())))?.name;
3378
+ }
3379
+ /** `planInit` over a live schema, with the SQL contact-table default applied. */
3380
+ function planSqlInit(tables, overrides = {}) {
3381
+ const plan = planInit(toDiscoveredSchema(tables), {
3382
+ contactTable: overrides.contactTable ?? chooseSqlContactTable(tables),
3383
+ companyTable: overrides.companyTable
3384
+ });
3385
+ const todos = plan.todos.map((todo) => {
3386
+ const table = NO_CURSOR_TODO.exec(todo)?.[1];
3387
+ return table === void 0 ? todo : `No updated_at column on "${table}" — Clivly re-reads the whole table on each sync.`;
3388
+ });
3389
+ return {
3390
+ ...plan,
3391
+ todos
3392
+ };
3393
+ }
3394
+ function cursorOption(entity, plan) {
3395
+ if (plan.todos.some((todo) => todo.includes(`"${entity.tableName}"`) && todo.startsWith("No updated_at column")) || entity.cursorField === "updated_at") return "";
3396
+ return `, cursorField: ${JSON.stringify(entity.cursorField)}`;
3397
+ }
3398
+ function renderSource(role, entity, plan) {
3399
+ const table = JSON.stringify(entity.tableName);
3400
+ const id = entity.idField === null ? "" : `, idField: ${JSON.stringify(entity.idField)}`;
3401
+ return ` ${role}: fromSql(executor, { entity: ${table}, table: ${table}, meta: table(${table})${cursorOption(entity, plan)}${id} })`;
3402
+ }
3403
+ function renderDriver(driver) {
3404
+ if (driver === "pg") return {
3405
+ imports: `import pg from "pg";
3406
+ import { type ClivlySDK, createClivlySDK, defineClivlyConfig } from "clivly/sdk";
3407
+ import {
3408
+ discoverFromSql,
3409
+ fromSql,
3410
+ pgExecutor,
3411
+ type SqlExecutor,
3412
+ sqlAppIdStore,
3413
+ sqlIntrospector,
3414
+ } from "clivly/sql";`,
3415
+ connect: "pgExecutor(new pg.Pool({ connectionString: databaseUrl }))"
3416
+ };
3417
+ return {
3418
+ imports: `import postgres from "postgres";
3419
+ import { type ClivlySDK, createClivlySDK, defineClivlyConfig } from "clivly/sdk";
3420
+ import {
3421
+ connectPostgresJs,
3422
+ discoverFromSql,
3423
+ fromSql,
3424
+ type SqlExecutor,
3425
+ sqlAppIdStore,
3426
+ sqlIntrospector,
3427
+ } from "clivly/sql";`,
3428
+ connect: "connectPostgresJs(databaseUrl, postgres)"
3429
+ };
3430
+ }
3431
+ function renderSqlConfig(plan) {
3432
+ const { imports, connect } = renderDriver(plan.driver);
3433
+ const entities = [renderEntity(plan.contact.moduleKey, plan.contact)];
3434
+ const sources = [renderSource("contacts", plan.contact, plan)];
3435
+ if (plan.company) {
3436
+ entities.push(renderEntity(plan.company.moduleKey, plan.company));
3437
+ sources.push(renderSource("companies", plan.company, plan));
3438
+ }
3439
+ return `${renderTodoHeader(plan.todos)}${imports}
3440
+
3441
+ // Your database, read with SELECT only. Clivly's one write is its own one-row
3442
+ // \`crm_clivly_app\` table, which keeps the ID Clivly issues this app.
3443
+ const databaseUrl = process.env.DATABASE_URL || process.env.SUPABASE_DB_URL;
3444
+ const executor = databaseUrl ? ${connect} : null;
3445
+
3446
+ // Every table in your database, read once at boot, so the Clivly dashboard can
3447
+ // offer them all when you add a mapping — not just the sources below.
3448
+ const schema = executor ? await discoverFromSql(executor) : [];
3449
+
3450
+ const table = (name: string) => {
3451
+ const meta = schema.find((t) => t.name === name);
3452
+ if (!meta) {
3453
+ throw new Error(\`clivly.config.ts: table "\${name}" is not in your database.\`);
3454
+ }
3455
+ return meta;
3456
+ };
3457
+
3458
+ const entities = defineClivlyConfig({
3459
+ entities: {
3460
+ ${entities.join(",\n")},
3461
+ },
3462
+ });
3463
+
3464
+ // Clivly over the live database. Built only once there is a connection string.
3465
+ function connectedClivly(executor: SqlExecutor): ClivlySDK {
3466
+ return createClivlySDK({
3467
+ apiKey: process.env.CLIVLY_SECRET_KEY ?? process.env.CLIVLY_API_KEY!,
3468
+ entities,
3469
+ schema,
3470
+ // Lets derived objects authored in the dashboard run against this database.
3471
+ introspector: sqlIntrospector(executor),
3472
+ appIdStore: sqlAppIdStore(executor),
3473
+ source: {
3474
+ // Keyed by CRM concept — contacts/companies/deals/custom.
3475
+ // NOT by your entity key. The entity's own \`source:\` above is a table name.
3476
+ ${sources.join(",\n")},
3477
+ },
3478
+ syncTrigger: {
3479
+ // Where Clivly Cloud calls to start a sync — your mounted tick route.
3480
+ // \`path\` lets the SDK build its public URL from the hosting platform's
3481
+ // environment; \`url\` overrides that when you need to.
3482
+ path: "${CLIVLY_TICK_PATH}",
3483
+ url: process.env.CLIVLY_SYNC_TRIGGER_URL,
3484
+ secret: process.env.CLIVLY_SYNC_TRIGGER_SECRET,
3485
+ },
3486
+ // Changes arrive with Clivly's scheduled sync; there is no instant push
3487
+ // without an ORM write helper.
3488
+ });
3489
+ }
3490
+
3491
+ const MISSING_DATABASE_URL =
3492
+ "[clivly] Not connecting: set DATABASE_URL (or SUPABASE_DB_URL) to your Postgres connection string, then restart the app.";
3493
+
3494
+ // No connection string (a build step, or a deploy missing the variable): no
3495
+ // SDK is built, so nothing reaches Clivly — no heartbeat, no partial schema.
3496
+ // Each member answers as the real SDK does when it cannot deliver, and the
3497
+ // first call logs the error once. \`satisfies\` keeps it in step with the SDK.
3498
+ function clivlyWithoutDatabase(): ClivlySDK {
3499
+ let logged = false;
3500
+ const warnOnce = () => {
3501
+ if (!logged) {
3502
+ logged = true;
3503
+ console.error(MISSING_DATABASE_URL);
3504
+ }
3505
+ };
3506
+ const notConnected = async () => {
3507
+ warnOnce();
3508
+ return { ok: false, reason: "client_error", retryable: false, status: null } as const;
3509
+ };
3510
+ const refuse = async (): Promise<never> => {
3511
+ warnOnce();
3512
+ throw new Error(MISSING_DATABASE_URL);
3513
+ };
3514
+ const unavailable = () => async (_req: Request) => {
3515
+ warnOnce();
3516
+ return Response.json({ ok: false, error: MISSING_DATABASE_URL }, { status: 503 });
3517
+ };
3518
+ return {
3519
+ connect: notConnected,
3520
+ ping: notConnected,
3521
+ heartbeat: async () => {
3522
+ warnOnce();
3523
+ return false;
3524
+ },
3525
+ doctor: async () => {
3526
+ warnOnce();
3527
+ return {
3528
+ ok: false,
3529
+ checks: [{ name: "Database connection string", ok: false, detail: MISSING_DATABASE_URL }],
3530
+ };
3531
+ },
3532
+ ensureSchema: async () => {
3533
+ warnOnce();
3534
+ return null;
3535
+ },
3536
+ ensureCustomObjects: async () => {
3537
+ warnOnce();
3538
+ return null;
3539
+ },
3540
+ describeSyncTrigger: () => ({
3541
+ configured: process.env.CLIVLY_SYNC_TRIGGER_URL,
3542
+ hasSecret: Boolean(process.env.CLIVLY_SYNC_TRIGGER_SECRET),
3543
+ resolved: undefined,
3544
+ }),
3545
+ describeRemoteProjections: () => ({
3546
+ capable: false,
3547
+ failed: 0,
3548
+ invalid: 0,
3549
+ ok: 0,
3550
+ ran: false,
3551
+ skipped: 0,
3552
+ }),
3553
+ createClivlyHandler: unavailable,
3554
+ createAuthVerifyHandler: unavailable,
3555
+ recordConsent: async () => {
3556
+ warnOnce();
3557
+ return { ok: false, error: MISSING_DATABASE_URL, status: null };
3558
+ },
3559
+ pushOne: async () => warnOnce(),
3560
+ pushDelete: async () => warnOnce(),
3561
+ start: async () => warnOnce(),
3562
+ stop: async () => undefined,
3563
+ sync: refuse,
3564
+ runScheduled: refuse,
3565
+ } satisfies ClivlySDK;
3566
+ }
3567
+
3568
+ export default executor ? connectedClivly(executor) : clivlyWithoutDatabase();
3569
+ `;
3570
+ }
3571
+ // src/render-supabase.ts
3572
+ const SUPABASE_FUNCTION_INDEX = "supabase/functions/clivly/index.ts";
3573
+ const SUPABASE_DENO_JSON = "supabase/functions/clivly/deno.json";
3574
+ const SUPABASE_CONFIG_TOML = "supabase/config.toml";
3575
+ /** The runtime default `createSupabaseClivly` picks when `contact` is omitted. */
3576
+ const DEFAULT_CONTACT_TABLE = "auth.users";
3577
+ const CLIVLY_FUNCTION_BLOCK = "[functions.clivly]\nverify_jwt = false\n";
3578
+ const CLIVLY_FUNCTION_HEADER = /^[ \t]*\[functions\.clivly\][ \t]*(#.*)?$/m;
3579
+ const DENO_JSON = `${JSON.stringify({ imports: {} }, null, 2)}\n`;
3580
+ function hasClivlyFunctionBlock(toml) {
3581
+ return CLIVLY_FUNCTION_HEADER.test(toml);
3582
+ }
3583
+ const TABLE_HEADER = /^[ \t]*\[/m;
3584
+ const VERIFY_JWT_TRUE = /^[ \t]*verify_jwt[ \t]*=[ \t]*true\b/m;
3585
+ /** True when an existing `[functions.clivly]` block turns the JWT check on. */
3586
+ function clivlyBlockVerifiesJwt(toml) {
3587
+ const header = CLIVLY_FUNCTION_HEADER.exec(toml);
3588
+ if (!header) return false;
3589
+ const rest = toml.slice(header.index + header[0].length);
3590
+ const next = rest.search(TABLE_HEADER);
3591
+ return VERIFY_JWT_TRUE.test(next === -1 ? rest : rest.slice(0, next));
3592
+ }
3593
+ function renderConfigToml(existing) {
3594
+ if (!existing) return CLIVLY_FUNCTION_BLOCK;
3595
+ if (hasClivlyFunctionBlock(existing)) return existing;
3596
+ return `${existing}${existing.endsWith("\n") ? "\n" : "\n\n"}${CLIVLY_FUNCTION_BLOCK}`;
3597
+ }
3598
+ function renderIndex(plan) {
3599
+ const pkg = `clivly@${plan.version}`;
3600
+ return `import postgres from "npm:postgres@3";
3601
+ import { connectPostgresJs } from "npm:${pkg}/sql";
3602
+ import { createSupabaseClivly } from "npm:${pkg}/supabase";
3603
+
3604
+ const env = Deno.env.toObject();
3605
+ const handler = createSupabaseClivly({
3606
+ env,
3607
+ executor: connectPostgresJs(env.SUPABASE_DB_URL, postgres),
3608
+ waitUntil: (p) => EdgeRuntime.waitUntil(p),
3609
+ ${plan.contactTable && plan.contactTable !== DEFAULT_CONTACT_TABLE ? ` contact: { table: ${JSON.stringify(plan.contactTable)} },\n` : ""}});
3610
+
3611
+ Deno.serve(handler);
3612
+ `;
3613
+ }
3614
+ function renderSupabaseFunction(plan) {
3615
+ return { files: {
3616
+ [SUPABASE_FUNCTION_INDEX]: renderIndex(plan),
3617
+ [SUPABASE_DENO_JSON]: DENO_JSON,
3618
+ [SUPABASE_CONFIG_TOML]: renderConfigToml(plan.existingConfigToml)
3619
+ } };
3620
+ }
3081
3621
  // src/resolve-schema-path.ts
3082
3622
  const COMMON_PATHS = [
3083
3623
  "src/db/schema.ts",
@@ -3751,7 +4291,7 @@ const triggerUrlStage = {
3751
4291
  detail: trigger.resolved
3752
4292
  });
3753
4293
  const configured = trigger?.configured;
3754
- const isPlaceholder = configured !== void 0 && require_sdk.isPlaceholderUrl(configured);
4294
+ const isPlaceholder = configured !== void 0 && require_src.isPlaceholderUrl(configured);
3755
4295
  return Promise.resolve({
3756
4296
  state: "warn",
3757
4297
  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.",
@@ -3974,7 +4514,7 @@ const MARK = {
3974
4514
  skip: "⏭️ ",
3975
4515
  pending: "⏳"
3976
4516
  };
3977
- const defaultConnect = (apiKey, apiUrl) => require_sdk.createClivlySDK({
4517
+ const defaultConnect = (apiKey, apiUrl) => require_src.createClivlySDK({
3978
4518
  apiKey,
3979
4519
  apiUrl,
3980
4520
  retry: { maxAttempts: 1 }
@@ -4030,6 +4570,127 @@ async function runStatus(options) {
4030
4570
  if (code !== 0 && results.some((result) => result.state === "pending")) out("\nSetup is incomplete — finish the steps above and re-run.\n");
4031
4571
  return code;
4032
4572
  }
4573
+ // src/supabase-detect.ts
4574
+ const SUPABASE_DEPS = ["@supabase/supabase-js", "@supabase/ssr"];
4575
+ const CONFIG_TOML = "supabase/config.toml";
4576
+ const LOVABLE_CLIENT = "src/integrations/supabase/client.ts";
4577
+ const ENV_FILES = [
4578
+ ".env",
4579
+ ".env.local",
4580
+ ".env.development",
4581
+ ".env.development.local"
4582
+ ];
4583
+ const URL_KEYS = [
4584
+ "VITE_SUPABASE_URL",
4585
+ "NEXT_PUBLIC_SUPABASE_URL",
4586
+ "SUPABASE_URL"
4587
+ ];
4588
+ const PROJECT_URL_LITERAL = /https:\/\/[a-z0-9]+\.supabase\.co\b/i;
4589
+ function defaultReadFile$1(path) {
4590
+ return (0, node_fs.existsSync)(path) ? (0, node_fs.readFileSync)(path, "utf8") : null;
4591
+ }
4592
+ function urlFromEnvFiles(cwd, readFile) {
4593
+ const merged = {};
4594
+ for (const name of ENV_FILES) {
4595
+ const contents = readFile((0, node_path.join)(cwd, name));
4596
+ if (contents !== null) Object.assign(merged, parseEnv(contents));
4597
+ }
4598
+ for (const key of URL_KEYS) {
4599
+ const value = merged[key]?.trim();
4600
+ if (value) return value;
4601
+ }
4602
+ return null;
4603
+ }
4604
+ function detectSupabase(deps, fileExists, cwd, readFile = defaultReadFile$1) {
4605
+ const clientPath = (0, node_path.join)(cwd, LOVABLE_CLIENT);
4606
+ const hasClient = fileExists(clientPath);
4607
+ const present = SUPABASE_DEPS.some((dep) => dep in deps) || fileExists((0, node_path.join)(cwd, CONFIG_TOML)) || hasClient;
4608
+ if (!present) return {
4609
+ present: false,
4610
+ projectUrl: null
4611
+ };
4612
+ const fromEnv = urlFromEnvFiles(cwd, readFile);
4613
+ if (fromEnv) return {
4614
+ present,
4615
+ projectUrl: fromEnv
4616
+ };
4617
+ return {
4618
+ present,
4619
+ projectUrl: (hasClient ? PROJECT_URL_LITERAL.exec(readFile(clientPath) ?? "")?.[0] : void 0) ?? null
4620
+ };
4621
+ }
4622
+ // src/supabase-connect.ts
4623
+ const FAILURE = 1;
4624
+ const SUCCESS = 0;
4625
+ const HTTP_UNAUTHORIZED = 401;
4626
+ const HTTP_FORBIDDEN = 403;
4627
+ const HTTP_NOT_FOUND = 404;
4628
+ const HTTP_UNAVAILABLE = 503;
4629
+ const TRAILING_SLASHES = /\/+$/;
4630
+ 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";
4631
+ const NOT_DEPLOYED_HELP = "The clivly function is not deployed yet. Deploy it, then run this again:\n npx supabase functions deploy clivly\n";
4632
+ const VERIFY_JWT_HELP = "Could not reach the clivly function. 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";
4633
+ 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";
4634
+ 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.\n";
4635
+ async function readBody(response) {
4636
+ try {
4637
+ const parsed = await response.json();
4638
+ return parsed && typeof parsed === "object" ? parsed : {};
4639
+ } catch {
4640
+ return {};
4641
+ }
4642
+ }
4643
+ function failureText(status, body) {
4644
+ if (status === HTTP_NOT_FOUND) return NOT_DEPLOYED_HELP;
4645
+ if (status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN) return VERIFY_JWT_HELP;
4646
+ if (status === HTTP_UNAVAILABLE && body.reason === "missing_secret_key") return SECRET_KEY_HELP;
4647
+ return null;
4648
+ }
4649
+ async function runSupabaseConnect(deps) {
4650
+ const { out } = deps;
4651
+ const base = deps.projectUrl.replace(TRAILING_SLASHES, "");
4652
+ let response;
4653
+ try {
4654
+ response = await deps.fetch(`${base}/functions/v1/clivly/connect`, { method: "GET" });
4655
+ } catch {
4656
+ out(VERIFY_JWT_HELP);
4657
+ return { code: FAILURE };
4658
+ }
4659
+ const body = await readBody(response);
4660
+ if (response.ok && body.ok === true) {
4661
+ if (body.hasContacts === false) {
4662
+ out(ZERO_ROWS_HELP);
4663
+ return { code: FAILURE };
4664
+ }
4665
+ if (body.hasContacts !== true) {
4666
+ out(REDEPLOY_HELP);
4667
+ return { code: FAILURE };
4668
+ }
4669
+ out(`Connected${typeof body.org?.name === "string" ? ` to ${body.org.name}` : ""}.\n`);
4670
+ return { code: SUCCESS };
4671
+ }
4672
+ const help = failureText(response.status, body);
4673
+ if (help) {
4674
+ out(help);
4675
+ return { code: FAILURE };
4676
+ }
4677
+ out(`The clivly function reported a problem (${typeof body.reason === "string" ? body.reason : "unknown"}).\n`);
4678
+ return { code: FAILURE };
4679
+ }
4680
+ /** The project URL from `--project-url`, else the app's own Supabase config. */
4681
+ function resolveSupabaseProjectUrl(cwd, override) {
4682
+ if (override) return override;
4683
+ let deps = {};
4684
+ const pkgPath = (0, node_path.join)(cwd, "package.json");
4685
+ if ((0, node_fs.existsSync)(pkgPath)) try {
4686
+ const pkg = JSON.parse((0, node_fs.readFileSync)(pkgPath, "utf8"));
4687
+ deps = {
4688
+ ...pkg.dependencies,
4689
+ ...pkg.devDependencies
4690
+ };
4691
+ } catch {}
4692
+ return detectSupabase(deps, node_fs.existsSync, cwd).projectUrl;
4693
+ }
4033
4694
  // src/index.ts
4034
4695
  const ENV_FILE_CANDIDATES = [
4035
4696
  ".env",
@@ -4281,7 +4942,10 @@ function resolveInitDeps(options) {
4281
4942
  })),
4282
4943
  framework: "unknown",
4283
4944
  layout: "app",
4284
- authWiring: renderAuthWiring("unknown")
4945
+ authWiring: renderAuthWiring("unknown"),
4946
+ renderConfig: void 0,
4947
+ commentedEnv: [],
4948
+ extraPackages: []
4285
4949
  };
4286
4950
  }
4287
4951
  /**
@@ -4294,7 +4958,42 @@ function resolveInitDeps(options) {
4294
4958
  function renderDetectionLines(detection) {
4295
4959
  const from = (source) => source ? ` (from ${source})` : "";
4296
4960
  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`;
4961
+ 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`);
4962
+ }
4963
+ /**
4964
+ * Supabase Auth is never inferred from dependencies (supabase-js is often
4965
+ * there for storage alone, and the Drizzle path must not change). A Supabase
4966
+ * app on the no-ORM path with no other auth library opts into it here.
4967
+ */
4968
+ function effectiveAuth(detected, noOrm) {
4969
+ return detected === "unknown" && noOrm?.noOrm.supabase.present ? "supabase" : detected;
4970
+ }
4971
+ function authNoteFor(noOrm, framework) {
4972
+ return noOrm && framework === "unknown" ? "not needed for the Edge Function" : void 0;
4973
+ }
4974
+ function noOrmTarget(options, deps, appDeps, orm) {
4975
+ if (orm !== "unknown" || options.schemaFlag) return null;
4976
+ const supabase = detectSupabase(appDeps, deps.fileExists, options.cwd, deps.readFile);
4977
+ return supabase.present || options.noOrm ? { noOrm: {
4978
+ appDeps,
4979
+ supabase
4980
+ } } : null;
4981
+ }
4982
+ 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";
4983
+ async function connectSupabase(argv) {
4984
+ const projectUrl = resolveSupabaseProjectUrl(process.cwd(), flagValue(argv, "--project-url"));
4985
+ if (!projectUrl) {
4986
+ process.stdout.write(NO_SUPABASE_URL_HELP);
4987
+ return 1;
4988
+ }
4989
+ const { code } = await runSupabaseConnect({
4990
+ projectUrl,
4991
+ fetch,
4992
+ out: (text) => {
4993
+ process.stdout.write(text);
4994
+ }
4995
+ });
4996
+ return code;
4298
4997
  }
4299
4998
  async function acquireSchema(options, deps) {
4300
4999
  const { out } = deps;
@@ -4309,7 +5008,9 @@ async function acquireSchema(options, deps) {
4309
5008
  }));
4310
5009
  const detected = detectAcrossWorkspace(appDeps, workspacePackages);
4311
5010
  const framework = options.frameworkFlag ?? detected.framework;
4312
- const { auth, orm, sources } = detected;
5011
+ const { orm, sources } = detected;
5012
+ const noOrm = noOrmTarget(options, deps, appDeps, orm);
5013
+ const auth = effectiveAuth(detected.auth, noOrm);
4313
5014
  deps.framework = framework;
4314
5015
  const layout = deps.resolveAppLayout(options.cwd, deps.fileExists);
4315
5016
  deps.layout = layout;
@@ -4317,6 +5018,7 @@ async function acquireSchema(options, deps) {
4317
5018
  deps.authWiring = renderAuthWiring(auth, auth === "better-auth" ? authInstanceFromFlag(options.authImportFlag) ?? await deps.probeAuth(options.cwd) : null);
4318
5019
  out(renderDetectionLines({
4319
5020
  auth,
5021
+ authNote: authNoteFor(noOrm, framework),
4320
5022
  authWired: deps.authWiring.complete,
4321
5023
  framework,
4322
5024
  frameworkForced: options.frameworkFlag !== void 0,
@@ -4328,6 +5030,7 @@ async function acquireSchema(options, deps) {
4328
5030
  if (frameworkCaution) out(`\n${frameworkCaution}`);
4329
5031
  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
5032
  out("\n");
5033
+ if (noOrm) return noOrm;
4331
5034
  if (orm !== "drizzle" && !options.schemaFlag) {
4332
5035
  out(`clivly init currently generates config for Drizzle only. Detected ORM: ${orm}\n`);
4333
5036
  out(workspaceHint("orm", workspacePackages.length));
@@ -4378,11 +5081,13 @@ function mutationsFor(options, deps, plan) {
4378
5081
  authWiring: deps.authWiring,
4379
5082
  plan,
4380
5083
  readFile: deps.readFile,
4381
- readEnv: deps.readEnv
5084
+ readEnv: deps.readEnv,
5085
+ renderConfig: deps.renderConfig,
5086
+ commentedEnv: deps.commentedEnv
4382
5087
  });
4383
5088
  }
4384
- function applyMutations(options, deps, mutations) {
4385
- for (const file of mutations.files) {
5089
+ function applyFiles(options, deps, files) {
5090
+ for (const file of files) {
4386
5091
  if (file.action === "unchanged") {
4387
5092
  deps.out(` · ${file.path} already up to date\n`);
4388
5093
  continue;
@@ -4394,6 +5099,9 @@ function applyMutations(options, deps, mutations) {
4394
5099
  deps.writeConfig((0, node_path.join)(options.cwd, file.path), file.contents);
4395
5100
  deps.out(` ✓ ${file.path}\n`);
4396
5101
  }
5102
+ }
5103
+ function applyMutations(options, deps, mutations) {
5104
+ applyFiles(options, deps, mutations.files);
4397
5105
  if (mutations.env.action === "skip") deps.out(" • .env already has every CLIVLY_* key — skipped\n");
4398
5106
  else {
4399
5107
  deps.writeEnv(options.cwd, mutations.env.contents);
@@ -4473,7 +5181,11 @@ function resolveRuntimeInstallSpec(deps, env = process.env) {
4473
5181
  async function scaffold(options, deps, plan) {
4474
5182
  const { out } = deps;
4475
5183
  const pm = deps.detectPackageManager(options.cwd);
4476
- const packages = [resolveRuntimeInstallSpec(deps), ...deps.authWiring.packages];
5184
+ const packages = [
5185
+ resolveRuntimeInstallSpec(deps),
5186
+ ...deps.authWiring.packages,
5187
+ ...deps.extraPackages
5188
+ ];
4477
5189
  const mutations = mutationsFor(options, deps, plan);
4478
5190
  const shadowing = shadowedAppDirError(options.cwd, deps.framework, mutations.files.map((file) => file.path), deps.fileExists);
4479
5191
  if (shadowing) {
@@ -4512,6 +5224,161 @@ async function scaffold(options, deps, plan) {
4512
5224
  printNextSteps(out, deps.authWiring.complete, loginRan, envFileFor(initFramework), initFramework === "sveltekit" && deps.authWiring.hostImport !== null);
4513
5225
  return 0;
4514
5226
  }
5227
+ const DATABASE_URL_PLACEHOLDER = {
5228
+ key: "DATABASE_URL",
5229
+ 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"
5230
+ };
5231
+ const SUPABASE_SECRETS_LOCATION = "Supabase dashboard → Edge Functions → Secrets (on Lovable: the Secrets panel)";
5232
+ function sqlDriverFor(appDeps) {
5233
+ if ("postgres" in appDeps) return {
5234
+ driver: "postgres",
5235
+ install: []
5236
+ };
5237
+ if ("pg" in appDeps) return {
5238
+ driver: "pg",
5239
+ install: []
5240
+ };
5241
+ return {
5242
+ driver: "postgres",
5243
+ install: ["postgres"]
5244
+ };
5245
+ }
5246
+ /**
5247
+ * `clivly init` for an app with no ORM: read the live schema (connection
5248
+ * string, then the linked Supabase CLI), then write either the server config
5249
+ * and route files or, for an SPA or when no schema could be read, the Supabase
5250
+ * Edge Function in its deploy-first form.
5251
+ */
5252
+ async function runNoOrmInit(options, deps, target) {
5253
+ const { out } = deps;
5254
+ const { supabase } = target;
5255
+ if (supabase.present) out(` Supabase: detected${supabase.projectUrl ? ` (${supabase.projectUrl})` : ""}\n\n`);
5256
+ if (!supabase.present && deps.framework === "unknown") {
5257
+ 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");
5258
+ return 1;
5259
+ }
5260
+ const connection = resolveConnectionString(options.processEnv ?? process.env, deps.readFile, options.cwd);
5261
+ const read = options.readLiveSchema ?? ((opts) => readLiveSchema({
5262
+ ...opts,
5263
+ connect: defaultConnect$1(options.cwd),
5264
+ runSupabaseCli: defaultRunSupabaseCli(options.cwd)
5265
+ }));
5266
+ const failures = /* @__PURE__ */ new Set();
5267
+ const tables = await read({
5268
+ connectionString: connection?.value,
5269
+ connectionLabel: connection?.label,
5270
+ onFailure: (reason) => failures.add(reason),
5271
+ out
5272
+ });
5273
+ if (tables) out(` Schema: live database (${tables.length} tables)\n\n`);
5274
+ const source = {
5275
+ connectionLabel: connection?.label ?? null,
5276
+ driverMissing: failures.has("driver_missing")
5277
+ };
5278
+ if (tables && deps.framework !== "unknown") return scaffoldSqlServer(options, deps, target.appDeps, tables, source);
5279
+ if (!supabase.present) {
5280
+ 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");
5281
+ return 1;
5282
+ }
5283
+ return writeSupabaseFunction(options, deps, tables, source);
5284
+ }
5285
+ async function scaffoldSqlServer(options, deps, appDeps, tables, source) {
5286
+ const plan = planSqlInit(tables, {
5287
+ contactTable: options.contactTableFlag,
5288
+ companyTable: options.companyTableFlag
5289
+ });
5290
+ const { contact } = plan;
5291
+ if (!contact) {
5292
+ printNoContactGuidance(deps.out, plan, options);
5293
+ return options.dryRun ? 0 : 1;
5294
+ }
5295
+ const { driver, install } = sqlDriverFor(appDeps);
5296
+ deps.renderConfig = (renderable) => renderSqlConfig({
5297
+ ...renderable,
5298
+ driver
5299
+ });
5300
+ deps.commentedEnv = source.connectionLabel === null ? [DATABASE_URL_PLACEHOLDER] : [];
5301
+ deps.extraPackages = install;
5302
+ const renderable = {
5303
+ ...plan,
5304
+ contact
5305
+ };
5306
+ printPlan(deps.out, renderable);
5307
+ const code = await scaffold(options, deps, renderable);
5308
+ if (code === 0 && !options.dryRun && !options.diff) printSqlServerSteps(deps, source);
5309
+ return code;
5310
+ }
5311
+ function printSqlServerSteps(deps, source) {
5312
+ 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");
5313
+ const { envKeys } = deps.authWiring;
5314
+ if (envKeys.length > 0) deps.out(`\n The auth/verify route reads ${envKeys.join(" and ")} from the environment.\n`);
5315
+ }
5316
+ function supabaseFunctionMutations(options, deps, contactTable, version, existingToml) {
5317
+ const tomlPath = SUPABASE_CONFIG_TOML;
5318
+ const { files } = renderSupabaseFunction({
5319
+ contactTable,
5320
+ existingConfigToml: existingToml,
5321
+ version
5322
+ });
5323
+ return Object.entries(files).map(([path, contents]) => {
5324
+ if (path !== tomlPath) return {
5325
+ path,
5326
+ contents,
5327
+ action: fileAction(deps.readFile((0, node_path.join)(options.cwd, path)), contents, options.force)
5328
+ };
5329
+ let action = "patch";
5330
+ if (existingToml === null) action = "create";
5331
+ else if (existingToml === contents) action = "unchanged";
5332
+ return {
5333
+ path,
5334
+ contents,
5335
+ action
5336
+ };
5337
+ });
5338
+ }
5339
+ function writeSupabaseFunction(options, deps, tables, source) {
5340
+ const { out } = deps;
5341
+ const version = deps.readOwnVersion();
5342
+ if (!version) {
5343
+ 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");
5344
+ return 1;
5345
+ }
5346
+ const contactTable = tables ? planSqlInit(tables, { contactTable: options.contactTableFlag }).contact?.tableName : void 0;
5347
+ const existingToml = deps.readFile((0, node_path.join)(options.cwd, SUPABASE_CONFIG_TOML));
5348
+ const files = supabaseFunctionMutations(options, deps, contactTable, version, existingToml);
5349
+ if (options.dryRun || options.diff) {
5350
+ out("\nDry run — nothing was written.\n\n");
5351
+ for (const file of files) out(` ${file.action.padEnd(9)} ${file.path}\n`);
5352
+ out("\nRe-run without --dry-run to apply.\n");
5353
+ return 0;
5354
+ }
5355
+ out("\nWriting the Clivly Edge Function:\n");
5356
+ applyFiles(options, deps, files);
5357
+ if (tables) out(`\n Contacts: ${contactTable && contactTable !== "auth.users" ? contactTable : "your Supabase Auth users (auth.users)"}\n`);
5358
+ else {
5359
+ 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");
5360
+ if (deps.framework !== "unknown") out(` ${routeFilesHint(source, FRAMEWORK_LABELS[deps.framework])}\n`);
5361
+ }
5362
+ 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
5363
+ request, not a Supabase user JWT, so the gateway would reject every call.
5364
+ `);
5365
+ printDeployFirstSteps(out);
5366
+ return 0;
5367
+ }
5368
+ function routeFilesHint(source, framework) {
5369
+ if (source.driverMissing) return `To generate route files for ${framework} instead, install \`postgres\` or \`pg\` in this app, then re-run.`;
5370
+ if (source.connectionLabel) return `Check ${source.connectionLabel}, then re-run to generate route files for ${framework} instead.`;
5371
+ return `Re-run with DATABASE_URL set to generate route files for ${framework} instead.`;
5372
+ }
5373
+ function printDeployFirstSteps(out) {
5374
+ out("\nNext steps:\n");
5375
+ out(` 1. Set both secrets on the function (values from the Clivly dashboard):
5376
+ CLIVLY_SECRET_KEY ${CREDENTIALS_LOCATION}\n CLIVLY_SYNC_TRIGGER_SECRET ${SYNC_SECRET_LOCATION}\n Set them in ${SUPABASE_SECRETS_LOCATION},\n or from a terminal: supabase secrets set CLIVLY_SECRET_KEY=… CLIVLY_SYNC_TRIGGER_SECRET=…
5377
+ `);
5378
+ out(" 2. Deploy it: supabase functions deploy clivly (on Lovable: push the change)\n");
5379
+ out(" 3. Connect it to Clivly:\n\n");
5380
+ out(" npx clivly connect --supabase\n");
5381
+ }
4515
5382
  function normalizeAppRoot(options) {
4516
5383
  const resolution = (options.resolveTargetApp ?? resolveTargetApp)(options.cwd);
4517
5384
  const out = options.out ?? ((line) => process.stdout.write(line));
@@ -4540,6 +5407,7 @@ async function runInit(options) {
4540
5407
  const deps = resolveInitDeps(resolvedOptions);
4541
5408
  const acquired = await acquireSchema(resolvedOptions, deps);
4542
5409
  if ("code" in acquired) return acquired.code;
5410
+ if ("noOrm" in acquired) return runNoOrmInit(resolvedOptions, deps, acquired.noOrm);
4543
5411
  const dbOverride = importOverride(resolvedOptions.dbImportFlag, "db");
4544
5412
  const plan = planInit(dbOverride ? {
4545
5413
  ...acquired,
@@ -4778,6 +5646,7 @@ function runInitFromArgv(argv, cwd) {
4778
5646
  diff: argv.includes("--diff"),
4779
5647
  yes: argv.includes("--yes"),
4780
5648
  noLogin: argv.includes("--no-login"),
5649
+ noOrm: argv.includes("--no-orm"),
4781
5650
  openBrowser: !argv.includes("--no-browser"),
4782
5651
  schemaFlag: flagValue(argv, "--schema"),
4783
5652
  frameworkFlag,
@@ -4787,6 +5656,15 @@ function runInitFromArgv(argv, cwd) {
4787
5656
  companyTableFlag: flagValue(argv, "--company-table")
4788
5657
  });
4789
5658
  }
5659
+ function failedEngineCheck() {
5660
+ if (process.env.CLIVLY_SKIP_ENGINE_CHECK) return false;
5661
+ const engineProblem = engineError(process.version, readOwnEngines());
5662
+ if (engineProblem) {
5663
+ process.stderr.write(engineProblem);
5664
+ return true;
5665
+ }
5666
+ return false;
5667
+ }
4790
5668
  async function main(argv) {
4791
5669
  const [command, ...rest] = argv;
4792
5670
  if (command === "-h" || command === "--help" || isHelpRequest(rest)) {
@@ -4797,13 +5675,7 @@ async function main(argv) {
4797
5675
  process.stdout.write(`${readOwnVersion() ?? "unknown"}\n`);
4798
5676
  return 0;
4799
5677
  }
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
- }
5678
+ if (failedEngineCheck()) return 1;
4807
5679
  let cliEnvFiles = [];
4808
5680
  try {
4809
5681
  cliEnvFiles = (await loadCliConfig(process.cwd()))?.envFiles ?? [];
@@ -4823,6 +5695,7 @@ async function main(argv) {
4823
5695
  case "ping":
4824
5696
  case "doctor":
4825
5697
  case "connect":
5698
+ if (command === "connect" && rest.includes("--supabase")) return await connectSupabase(rest);
4826
5699
  if (command !== "status") process.stderr.write(`\`clivly ${command}\` is a deprecated alias that runs part of \`clivly status\`. Prefer \`clivly status\`.\n`);
4827
5700
  return await runStatus({
4828
5701
  cwd: process.cwd(),