clivly 0.7.2 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs CHANGED
@@ -2,15 +2,81 @@
2
2
  import { t as CANONICAL_FIELDS } from "./entity-config-va2bkH5o.mjs";
3
3
  import "./mapping-score-C68uAqGB.mjs";
4
4
  import { matchesConcept, requiredFieldsFor, scoreFieldMap, scoreRelationships, suggestCursorField, toFieldMap } from "./internal-entity-heuristics.mjs";
5
- import { t as createClivlySDK } from "./sdk-C6WANW8M.mjs";
5
+ import { t as createClivlySDK } from "./sdk-C2VL28du.mjs";
6
6
  import { createRequire } from "node:module";
7
7
  import { spawn } from "node:child_process";
8
- import { accessSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
8
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, watch, writeFileSync } from "node:fs";
9
9
  import { homedir, hostname } from "node:os";
10
10
  import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
11
11
  import { createInterface } from "node:readline/promises";
12
12
  import { createJiti } from "jiti";
13
13
  import { fileURLToPath, pathToFileURL } from "node:url";
14
+ //#region ../core/src/env-file.ts
15
+ const ENV_FILES = {
16
+ next: ".env.local",
17
+ "tanstack-start": ".env",
18
+ sveltekit: ".env",
19
+ remix: ".env",
20
+ nuxt: ".env",
21
+ "hono-workers": ".dev.vars"
22
+ };
23
+ /** The conventional env file for a framework. `.env` when we do not know. */
24
+ function envFileFor(framework) {
25
+ return ENV_FILES[normalizeFramework(framework)] ?? ".env";
26
+ }
27
+ const ALIASES = {
28
+ next: "next",
29
+ nextjs: "next",
30
+ "next.js": "next",
31
+ "tanstack-start": "tanstack-start",
32
+ tanstack: "tanstack-start",
33
+ sveltekit: "sveltekit",
34
+ remix: "remix",
35
+ nuxt: "nuxt",
36
+ "hono-workers": "hono-workers",
37
+ hono: "hono-workers",
38
+ workers: "hono-workers"
39
+ };
40
+ /** The canonical id for a framework name, or null when unrecognised. */
41
+ function normalizeFramework(framework) {
42
+ if (!framework) return null;
43
+ return ALIASES[framework.toLowerCase()] ?? null;
44
+ }
45
+ /**
46
+ * Which env file to actually write to.
47
+ *
48
+ * Prefers a file that already holds the key over the conventional one: a
49
+ * project that has been running with credentials in `.env` must not suddenly
50
+ * get a second copy in `.env.local`, leaving two files disagreeing and the
51
+ * stale one still loading. Convention applies to new setups, not to a working
52
+ * one someone already has.
53
+ */
54
+ function resolveEnvFile(input) {
55
+ const conventional = envFileFor(input.framework);
56
+ if (input.existing.includes(conventional)) return conventional;
57
+ return input.existing[0] ?? conventional;
58
+ }
59
+ //#endregion
60
+ //#region src/app-layout.ts
61
+ function resolveAppLayout(cwd, fileExists = existsSync) {
62
+ if (fileExists(join(cwd, "src", "app"))) return "src/app";
63
+ if (fileExists(join(cwd, "app"))) return "app";
64
+ return fileExists(join(cwd, "src")) ? "src/app" : "app";
65
+ }
66
+ function shadowedAppDirError(cwd, framework, plannedPaths, fileExists = existsSync) {
67
+ if (framework !== "nextjs") return null;
68
+ if (!plannedPaths.some((path) => path.startsWith("app/"))) return null;
69
+ if (!fileExists(join(cwd, "src", "app"))) return null;
70
+ return `This project has a src/app directory, so writing routes to app/ would shadow it.
71
+
72
+ Next.js reads either app/ or src/app/, never both. A root app/ directory wins,
73
+ and every route under src/app/ disappears from the build.
74
+
75
+ Nothing was written. Please report this at https://github.com/amani-joseph/clivly/issues
76
+ — Clivly should have detected the src/app layout automatically.
77
+ `;
78
+ }
79
+ //#endregion
14
80
  //#region src/load-config.ts
15
81
  const CONFIG_HINT = "Expected clivly.config.ts at your app root exporting `createClivlySDK({...})`.";
16
82
  function resolveConfigPath(cwd, configPath) {
@@ -108,6 +174,14 @@ async function loadCliConfig(cwd) {
108
174
  return envFiles ? { envFiles } : {};
109
175
  }
110
176
  //#endregion
177
+ //#region src/dashboard-locations.ts
178
+ /** Secret + publishable keys. The Connect dialog mints them and shows the secret once. */
179
+ const CREDENTIALS_LOCATION = "Clivly dashboard → Connect app (or Settings → API keys)";
180
+ /** The signing secret Clivly Cloud uses on sync-trigger callbacks. */
181
+ const SYNC_SECRET_LOCATION = "Clivly dashboard → Integrations → Remote sync";
182
+ /** Chat widget records and their allowed origins. */
183
+ const WIDGET_LOCATION = "Clivly dashboard → Settings → Chat widget";
184
+ //#endregion
111
185
  //#region src/detect.ts
112
186
  const FRAMEWORK_MARKERS = [
113
187
  {
@@ -311,10 +385,14 @@ async function runDev(options) {
311
385
  if (result.ok) deps.out("Dashboard-triggered sync now points at this local session.");
312
386
  else deps.out(overrideFailureMessage(result.kind));
313
387
  });
388
+ const stopWatching = deps.watchConfig?.(options.cwd, () => {
389
+ deps.out("clivly.config.ts changed — restart your app for it to take effect.");
390
+ }) ?? null;
314
391
  return await new Promise((resolve) => {
315
392
  const shutdown = async (code) => {
316
393
  if (shuttingDown) return;
317
394
  shuttingDown = true;
395
+ stopWatching?.();
318
396
  tunnel.kill();
319
397
  app?.kill();
320
398
  if (!(await deps.clear().catch(() => UNREACHABLE_RESULT)).ok) deps.out("Warning: could not clear the tunnel override on exit.");
@@ -767,6 +845,29 @@ async function discoverSchema(opts) {
767
845
  };
768
846
  }
769
847
  //#endregion
848
+ //#region src/engine-check.ts
849
+ const MAJOR = /^v?(\d+)/;
850
+ const FIRST_NUMBER = /(\d+)/;
851
+ function currentMajor(version) {
852
+ const match = MAJOR.exec(version);
853
+ return match ? Number(match[1]) : null;
854
+ }
855
+ function requiredMajor(range) {
856
+ if (!range) return null;
857
+ const match = FIRST_NUMBER.exec(range);
858
+ return match ? Number(match[1]) : null;
859
+ }
860
+ function engineError(currentVersion, enginesRange) {
861
+ const have = currentMajor(currentVersion);
862
+ const need = requiredMajor(enginesRange);
863
+ if (have === null || need === null || have >= need) return null;
864
+ return `Clivly requires Node.js ${need} or newer. You are running ${currentVersion}.
865
+
866
+ Upgrade with \`nvm install ${need}\` (or your version manager of choice), then re-run.
867
+ Set CLIVLY_SKIP_ENGINE_CHECK=1 to run anyway — expect unrelated-looking failures.
868
+ `;
869
+ }
870
+ //#endregion
770
871
  //#region src/env-file.ts
771
872
  const REGEX_METACHARACTERS = /[.*+?^${}()|[\]\\]/g;
772
873
  function escapeForRegExp(key) {
@@ -851,6 +952,123 @@ function upsertEnvValues(existing, entries, options = {}) {
851
952
  };
852
953
  }
853
954
  //#endregion
955
+ //#region src/help.ts
956
+ const ROOT_HELP = `clivly — embed a CRM in your app
957
+
958
+ Usage:
959
+ clivly init [options] Scaffold Clivly (config, routes, env file) for your app
960
+ clivly add widget [options] Scaffold the chat-session route
961
+ clivly status [options] Check your setup, step by step
962
+ clivly push-schema [options] Report your schema to Clivly without deploying
963
+ clivly dev [options] Tunnel localhost so remote sync can reach you
964
+ clivly login [options] Pair this machine and write credentials to your env file
965
+ clivly --version Print the installed clivly version
966
+
967
+ Deprecated aliases — each runs part of \`clivly status\` and still works:
968
+ clivly ping credential + reachability
969
+ clivly connect the above, plus config and trigger URL
970
+ clivly doctor config, setup checks and edge safety
971
+
972
+ Prefer \`clivly status\`: it runs the whole ladder and tells you which step you
973
+ are on. The aliases are kept because output and docs have recommended them.
974
+
975
+ Run \`clivly <command> --help\` for details on a command.
976
+ `;
977
+ const COMMAND_HELP = {
978
+ init: `clivly init — scaffold Clivly into this app
979
+
980
+ Usage:
981
+ clivly init [--force] [--dry-run] [--diff] [--yes] [--no-login] [--no-browser]
982
+ [--schema <path|package>] [--db-import <specifier>]
983
+ [--auth-import <specifier>] [--contact-table <table>]
984
+ [--company-table <table>]
985
+
986
+ Scaffolds clivly.config.ts, the Clivly route files, and .env placeholders.
987
+ Detects your framework, ORM, auth adapter and app layout from the project.
988
+
989
+ Options:
990
+ --dry-run Show what would be written; write nothing
991
+ --diff Show a diff for files that already exist
992
+ --force Overwrite files Clivly owns
993
+ --yes Skip prompts
994
+ --no-login Skip browser pairing
995
+ --schema <p> Path or package holding your ORM schema
996
+ --db-import <s> Module specifier exporting your database instance
997
+ --auth-import <s> Module specifier exporting your auth instance
998
+ --contact-table <t> Table to map as contacts
999
+ --company-table <t> Table to map as companies
1000
+ `,
1001
+ add: `clivly add widget — scaffold the chat-session route
1002
+
1003
+ Usage:
1004
+ clivly add widget [--force] [--dry-run]
1005
+
1006
+ Writes the route that mints chat-widget sessions. Creates no widget record —
1007
+ that lives in the Clivly dashboard.
1008
+
1009
+ Options:
1010
+ --dry-run Show what would be written; write nothing
1011
+ --force Overwrite the route if it already exists
1012
+ `,
1013
+ status: `clivly status — check your setup, step by step
1014
+
1015
+ Usage:
1016
+ clivly status [--verbose] [--config <path>] [--env-file <path>]
1017
+
1018
+ Runs the setup ladder: credential, reachability, config load, edge-safety,
1019
+ setup checks, sync trigger. Read-only — writes nothing.
1020
+
1021
+ Options:
1022
+ --verbose Show every check, including those that passed
1023
+ --config <path> Path to clivly.config.ts
1024
+ --env-file <path> Extra env file to load
1025
+ `,
1026
+ "push-schema": `clivly push-schema — report your schema without deploying
1027
+
1028
+ Usage:
1029
+ clivly push-schema [--config <path>]
1030
+
1031
+ Sends your discovered tables to Clivly so the dashboard can offer them for
1032
+ mapping. Reads your config; writes nothing locally.
1033
+ `,
1034
+ dev: `clivly dev — tunnel localhost so remote sync can reach you
1035
+
1036
+ Usage:
1037
+ clivly dev [--port <n>] [--api-url <url>] [--route-path <path>] [-- <cmd>]
1038
+
1039
+ Opens a tunnel to your local app and points Clivly's sync trigger at it.
1040
+ Everything after \`--\` runs as your app's dev command.
1041
+
1042
+ Options:
1043
+ --port <n> Local port your app listens on
1044
+ --route-path <path> Path to your mounted tick route
1045
+ `,
1046
+ login: `clivly login — pair this machine with Clivly
1047
+
1048
+ Usage:
1049
+ clivly login [--force] [--rotate] [--api-url <url>] [--no-browser]
1050
+
1051
+ Opens a browser to approve this machine, then writes CLIVLY_SECRET_KEY and
1052
+ CLIVLY_SYNC_TRIGGER_SECRET to .env.
1053
+
1054
+ Options:
1055
+ --force Re-pair even if credentials already exist
1056
+ --rotate Replace the existing credentials
1057
+ --no-browser Print the URL instead of opening a browser
1058
+ `
1059
+ };
1060
+ function isHelpRequest(argv) {
1061
+ for (const arg of argv) {
1062
+ if (arg === "--") return false;
1063
+ if (arg === "--help" || arg === "-h") return true;
1064
+ }
1065
+ return false;
1066
+ }
1067
+ function helpFor(command) {
1068
+ if (!command) return ROOT_HELP;
1069
+ return COMMAND_HELP[command] ?? ROOT_HELP;
1070
+ }
1071
+ //#endregion
854
1072
  //#region src/install.ts
855
1073
  const defaultRun = (command, args, cwd) => new Promise((resolvePromise, reject) => {
856
1074
  const child = spawn(command, args, {
@@ -1090,11 +1308,11 @@ function credentialEntries(credentials) {
1090
1308
  return [{
1091
1309
  key: SECRET_KEY_ENV,
1092
1310
  value: credentials.apiKey,
1093
- comment: "Org secret key — Settings → API keys"
1311
+ comment: `Org secret key — ${CREDENTIALS_LOCATION}`
1094
1312
  }, {
1095
1313
  key: "CLIVLY_SYNC_TRIGGER_SECRET",
1096
1314
  value: credentials.triggerSecret,
1097
- comment: "Signing secret — Integrations → Remote sync"
1315
+ comment: `Signing secret — ${SYNC_SECRET_LOCATION}`
1098
1316
  }];
1099
1317
  }
1100
1318
  function writeCredentials(options, credentials) {
@@ -1181,12 +1399,19 @@ function chooseSyncFields(table, todos) {
1181
1399
  idField
1182
1400
  };
1183
1401
  }
1402
+ const SPLIT_NAME_COLUMNS = /* @__PURE__ */ new Set([
1403
+ "first_name",
1404
+ "firstname",
1405
+ "given_name"
1406
+ ]);
1184
1407
  function buildEntity(table, concept, todos) {
1185
1408
  const canonical = CANONICAL_FIELDS[concept];
1186
1409
  const suggested = toFieldMap(scoreFieldMap(concept, toScoredTable(table)));
1187
1410
  const fields = {};
1188
1411
  for (const [key, column] of Object.entries(suggested)) if (canonical.includes(key)) fields[key] = column;
1189
1412
  for (const required of requiredFieldsFor(concept)) if (!fields[required]) todos.push(`Could not map required ${concept} field "${required}" on "${table.tableName}" — add it manually.`);
1413
+ const nameColumn = fields.name?.toLowerCase();
1414
+ if (nameColumn && SPLIT_NAME_COLUMNS.has(nameColumn)) todos.push(`Mapped ${concept} "name" to "${fields.name}" on "${table.tableName}" — that is the given name only. Clivly mirrors one column per field, so add a full-name column if you want surnames.`);
1190
1415
  const { cursorField, idField } = chooseSyncFields(table, todos);
1191
1416
  return {
1192
1417
  moduleKey: table.moduleKey,
@@ -1257,15 +1482,99 @@ function planInit(schema, overrides = {}) {
1257
1482
  contact,
1258
1483
  company,
1259
1484
  tableNames: schema.tables.map((table) => table.tableName),
1485
+ contactCandidates: rankContactCandidates(schema.tables),
1260
1486
  todos
1261
1487
  };
1262
1488
  }
1489
+ const CONTACT_COLUMN_EVIDENCE = [
1490
+ {
1491
+ label: "email",
1492
+ names: ["email", "email_address"],
1493
+ weight: 3
1494
+ },
1495
+ {
1496
+ label: "phone",
1497
+ names: [
1498
+ "phone",
1499
+ "phone_number",
1500
+ "mobile"
1501
+ ],
1502
+ weight: 2
1503
+ },
1504
+ {
1505
+ label: "first name",
1506
+ names: [
1507
+ "first_name",
1508
+ "firstname",
1509
+ "given_name"
1510
+ ],
1511
+ weight: 2
1512
+ },
1513
+ {
1514
+ label: "last name",
1515
+ names: [
1516
+ "last_name",
1517
+ "lastname",
1518
+ "surname",
1519
+ "family_name"
1520
+ ],
1521
+ weight: 2
1522
+ },
1523
+ {
1524
+ label: "name",
1525
+ names: [
1526
+ "name",
1527
+ "full_name",
1528
+ "display_name"
1529
+ ],
1530
+ weight: 1
1531
+ }
1532
+ ];
1533
+ const NAME_MATCH_WEIGHT = 4;
1534
+ /**
1535
+ * Rank the schema's tables by how much they look like people, best first.
1536
+ *
1537
+ * Used only on the failure path, where detection found nothing mappable and the
1538
+ * developer has to choose. `init` previously suggested `tableNames[0]` — the
1539
+ * first table in schema order — so a rental app was told to map its `lease`
1540
+ * table as contacts. Wrong guidance is worse than none: it is confident, and
1541
+ * the developer has no way to see it is wrong.
1542
+ *
1543
+ * Deliberately evidence-based rather than name-based alone, so a table whose
1544
+ * name Clivly has never heard of still surfaces on the strength of its columns.
1545
+ */
1546
+ function rankContactCandidates(tables) {
1547
+ return tables.map((table) => {
1548
+ const columns = new Set(table.columns.flatMap((c) => [c.dbName.toLowerCase(), c.key.toLowerCase()]));
1549
+ const reasons = [];
1550
+ let score = 0;
1551
+ if (matchesConcept(table.tableName, "contact")) {
1552
+ score += NAME_MATCH_WEIGHT;
1553
+ reasons.push("the name looks like a people table");
1554
+ }
1555
+ for (const evidence of CONTACT_COLUMN_EVIDENCE) {
1556
+ const hit = evidence.names.find((name) => columns.has(name));
1557
+ if (hit) {
1558
+ score += evidence.weight;
1559
+ reasons.push(hit);
1560
+ }
1561
+ }
1562
+ return {
1563
+ reasons,
1564
+ score,
1565
+ table: table.tableName
1566
+ };
1567
+ }).filter((candidate) => candidate.score > 0).sort((a, b) => b.score - a.score || a.table.localeCompare(b.table)).map(({ reasons, table }) => ({
1568
+ reasons,
1569
+ table
1570
+ }));
1571
+ }
1263
1572
  //#endregion
1264
1573
  //#region src/render-config.ts
1265
1574
  const CLIVLY_ENV_KEYS = [
1266
1575
  {
1267
1576
  key: "CLIVLY_SECRET_KEY",
1268
- comment: "Org secret key — Settings → API keys"
1577
+ comment: `Org secret key — ${CREDENTIALS_LOCATION}`
1269
1578
  },
1270
1579
  {
1271
1580
  key: "CLIVLY_SYNC_TRIGGER_URL",
@@ -1273,7 +1582,7 @@ const CLIVLY_ENV_KEYS = [
1273
1582
  },
1274
1583
  {
1275
1584
  key: "CLIVLY_SYNC_TRIGGER_SECRET",
1276
- comment: "Signing secret — Integrations → Remote sync"
1585
+ comment: `Signing secret — ${SYNC_SECRET_LOCATION}`
1277
1586
  }
1278
1587
  ];
1279
1588
  function renderFields(fields) {
@@ -1302,6 +1611,28 @@ function renderDbExpr(plan) {
1302
1611
  if (!plan.db) return "db";
1303
1612
  return dbIsInSchemaModule(plan) ? `schema.${plan.db.moduleKey}` : plan.db.moduleKey;
1304
1613
  }
1614
+ const TRAILING_SCHEMA_SEGMENT = /\/schema(\/index)?$/;
1615
+ /**
1616
+ * Where the `db` instance most likely lives, given where the schema was found.
1617
+ *
1618
+ * Only reached when discovery could not confirm one. Discovery *evaluates* a
1619
+ * candidate module and duck-types its exports for `.select`, which is the right
1620
+ * check but fails for the most common real-world db module: `drizzle(process.
1621
+ * env.DATABASE_URL!)` throws at import time when the env var is absent, and it
1622
+ * is absent precisely when a developer is running `clivly init` for the first
1623
+ * time. So the probe misses, through no fault of the project.
1624
+ *
1625
+ * The old fallback emitted `<YOUR_DB_MODULE>` — not a module specifier, not
1626
+ * valid TypeScript, and invisible until the config failed to load at runtime.
1627
+ * A best-guess relative path is strictly better: right for the conventional
1628
+ * layout (`lib/db/schema.ts` beside `lib/db/index.ts`), and when it is wrong it
1629
+ * is a module-not-found error at build time, naming a real path the developer
1630
+ * can correct.
1631
+ */
1632
+ function guessDbImportPath(schemaImportPath) {
1633
+ const trimmed = schemaImportPath.replace(TRAILING_SCHEMA_SEGMENT, "");
1634
+ return trimmed === schemaImportPath || trimmed === "." || trimmed === "" ? "./db" : trimmed;
1635
+ }
1305
1636
  function renderImports(plan) {
1306
1637
  const lines = [
1307
1638
  "import { createClivlySDK, defineClivlyConfig } from \"clivly/sdk\";",
@@ -1309,8 +1640,10 @@ function renderImports(plan) {
1309
1640
  "import { discoverFromDrizzle } from \"clivly/drizzle\";",
1310
1641
  `import * as schema from "${plan.importPath}";`
1311
1642
  ];
1312
- if (!plan.db) lines.push("import { db } from \"<YOUR_DB_MODULE>\"; // TODO(clivly): replace with the path to your Drizzle `db` instance — NOT your schema file");
1313
- else if (!dbIsInSchemaModule(plan)) lines.push(`import { ${plan.db.moduleKey} } from "${plan.db.importPath}";`);
1643
+ if (plan.db === null) {
1644
+ const guess = guessDbImportPath(plan.importPath);
1645
+ lines.push(`import { db } from "${guess}"; // TODO(clivly): verify this path points at your Drizzle \`db\` instance — NOT your schema file`);
1646
+ } else if (!dbIsInSchemaModule(plan)) lines.push(`import { ${plan.db.moduleKey} } from "${plan.db.importPath}";`);
1314
1647
  return lines.join("\n");
1315
1648
  }
1316
1649
  function renderTodoHeader(todos) {
@@ -1428,6 +1761,83 @@ function renderAuthWiring(auth, authInstance = null) {
1428
1761
  }
1429
1762
  }
1430
1763
  //#endregion
1764
+ //#region src/tsconfig-alias.ts
1765
+ const LEADING_DOT_SLASH$1 = /^\.\//;
1766
+ const TRAILING_WILDCARD = /\/?\*$/;
1767
+ const TRAILING_SLASH = /\/$/;
1768
+ const BLOCK_COMMENT = /\/\*[\s\S]*?\*\//g;
1769
+ const LINE_COMMENT = /(^|[^:])\/\/.*$/gm;
1770
+ const TRAILING_COMMA = /,(\s*[}\]])/g;
1771
+ /**
1772
+ * `compilerOptions` from a tsconfig's text, or null when it cannot be read.
1773
+ *
1774
+ * tsconfig is JSONC — comments and trailing commas are legal and common, and
1775
+ * `JSON.parse` rejects both. Stripping them is enough here: this only ever reads
1776
+ * two string-valued fields, so the cost of being wrong is falling back to a
1777
+ * relative import, which already works.
1778
+ */
1779
+ function parseTsconfig(source) {
1780
+ try {
1781
+ const stripped = source.replace(BLOCK_COMMENT, "").replace(LINE_COMMENT, "$1").replace(TRAILING_COMMA, "$1");
1782
+ return JSON.parse(stripped).compilerOptions ?? null;
1783
+ } catch {
1784
+ return null;
1785
+ }
1786
+ }
1787
+ /**
1788
+ * Strip a leading "./" and any trailing wildcard so two paths can be compared.
1789
+ *
1790
+ * `"./*"` — an alias rooted at the app itself — must reduce to the empty string,
1791
+ * not to a stray `"*"`; that is the mapping which makes a root-level
1792
+ * clivly.config alias-reachable.
1793
+ */
1794
+ function normalize(value) {
1795
+ return value.replace(LEADING_DOT_SLASH$1, "").replace(TRAILING_WILDCARD, "").replace(TRAILING_SLASH, "");
1796
+ }
1797
+ /**
1798
+ * The alias specifier that reaches `target`, or null when none does.
1799
+ *
1800
+ * `target` is app-root-relative and extensionless, e.g. `lib/auth` or
1801
+ * `clivly.config`. Only wildcard patterns are considered — an exact mapping
1802
+ * names one module and is not a prefix anything else can be rebased onto.
1803
+ *
1804
+ * Longest prefix wins, so `"@components/*": ["./src/components/*"]` beats
1805
+ * `"@/*": ["./src/*"]` for a module under `src/components`, matching how
1806
+ * TypeScript itself resolves.
1807
+ */
1808
+ function aliasFor(input) {
1809
+ if (!input.paths) return null;
1810
+ const target = normalize(input.target);
1811
+ let best = null;
1812
+ for (const [pattern, targets] of Object.entries(input.paths)) {
1813
+ if (!pattern.endsWith("/*")) continue;
1814
+ const prefix = pattern.slice(0, -2);
1815
+ for (const mapped of targets) {
1816
+ const base = baseReaching(mapped, target);
1817
+ if (base === null) continue;
1818
+ const rest = base === "" ? target : target.slice(base.length + 1);
1819
+ if (!best || base.length > best.length) best = {
1820
+ alias: `${prefix}/${rest}`,
1821
+ length: base.length
1822
+ };
1823
+ }
1824
+ }
1825
+ return best?.alias ?? null;
1826
+ }
1827
+ /**
1828
+ * The normalized base of `mapped` when it contains `target`, else null.
1829
+ *
1830
+ * A prefix must end at a segment boundary — `src` must not match `srcinternal`,
1831
+ * a different directory — and the target must be strictly inside the base, since
1832
+ * a wildcard needs a remainder to substitute.
1833
+ */
1834
+ function baseReaching(mapped, target) {
1835
+ if (!mapped.endsWith("/*")) return null;
1836
+ const base = normalize(mapped);
1837
+ if (base === "") return target === "" ? null : "";
1838
+ return target.startsWith(`${base}/`) ? base : null;
1839
+ }
1840
+ //#endregion
1431
1841
  //#region src/scaffold.ts
1432
1842
  const TANSTACK_ROUTE_PREFIX = /^src\/routes\//;
1433
1843
  const TS_EXTENSION = /\.ts$/;
@@ -1459,10 +1869,14 @@ const ROUTE_PATHS = {
1459
1869
  },
1460
1870
  unknown: null
1461
1871
  };
1462
- function routePath(framework, kind) {
1872
+ function applyLayout(framework, path, layout) {
1873
+ if (framework !== "nextjs" || layout === "app") return path;
1874
+ return `src/${path}`;
1875
+ }
1876
+ function routePath(framework, kind, layout = "app") {
1463
1877
  const paths = ROUTE_PATHS[framework];
1464
1878
  if (!paths) throw new Error(`No route path for framework: ${framework}`);
1465
- return paths[kind];
1879
+ return applyLayout(framework, paths[kind], layout);
1466
1880
  }
1467
1881
  const WINDOWS_SEP = /\\/g;
1468
1882
  const LEADING_DOT_SLASH = /^\.\//;
@@ -1470,22 +1884,27 @@ function configImport(routeFilePath) {
1470
1884
  const rel = relative(dirname(routeFilePath), "clivly.config").replace(WINDOWS_SEP, "/");
1471
1885
  return rel.startsWith(".") ? rel : `./${rel}`;
1472
1886
  }
1473
- function hostImportPath(routeFilePath, appRelative) {
1887
+ function hostImportPath(routeFilePath, appRelative, paths) {
1474
1888
  const fromRoot = appRelative.replace(LEADING_DOT_SLASH, "");
1889
+ const alias = aliasFor({
1890
+ paths,
1891
+ target: fromRoot
1892
+ });
1893
+ if (alias) return alias;
1475
1894
  const rel = relative(dirname(routeFilePath), fromRoot).replace(WINDOWS_SEP, "/");
1476
1895
  return rel.startsWith(".") ? rel : `./${rel}`;
1477
1896
  }
1478
- function renderAuthPreamble(routeFilePath, auth) {
1897
+ function renderAuthPreamble(routeFilePath, auth, paths) {
1479
1898
  const lines = [...auth.imports];
1480
1899
  if (auth.hostImport) {
1481
1900
  if (auth.hostImport.todo) lines.push(`// ${auth.hostImport.todo}`);
1482
- const path = hostImportPath(routeFilePath, auth.hostImport.path);
1901
+ const path = hostImportPath(routeFilePath, auth.hostImport.path, paths);
1483
1902
  lines.push(`import { ${auth.hostImport.binding} } from "${path}";`);
1484
1903
  }
1485
1904
  lines.push("", auth.body);
1486
1905
  return lines.join("\n");
1487
1906
  }
1488
- function renderPreamble(kind, importPath, auth, routeFilePath) {
1907
+ function renderPreamble(kind, importPath, auth, paths, routeFilePath) {
1489
1908
  if (kind === "session") return `import { createChatSessionHandler } from "clivly/sdk";
1490
1909
 
1491
1910
  const handler = createChatSessionHandler({
@@ -1496,7 +1915,7 @@ const handler = createChatSessionHandler({
1496
1915
  });
1497
1916
  `;
1498
1917
  if (kind === "verify") return `import clivly from "${importPath}";
1499
- ${renderAuthPreamble(routeFilePath, auth)}
1918
+ ${renderAuthPreamble(routeFilePath, auth, paths)}
1500
1919
  const handler = clivly.createAuthVerifyHandler(resolveUser);
1501
1920
  `;
1502
1921
  return `import clivly from "${importPath}";
@@ -1504,8 +1923,8 @@ const handler = clivly.createAuthVerifyHandler(resolveUser);
1504
1923
  const handler = clivly.createClivlyHandler();
1505
1924
  `;
1506
1925
  }
1507
- function renderBody(framework, importPath, kind, auth, routeFilePath) {
1508
- const preamble = renderPreamble(kind, importPath, auth, routeFilePath);
1926
+ function renderBody(framework, importPath, kind, auth, routeFilePath, paths) {
1927
+ const preamble = renderPreamble(kind, importPath, auth, paths, routeFilePath);
1509
1928
  switch (framework) {
1510
1929
  case "nextjs": return `${preamble}
1511
1930
  export const POST = (request: Request) => handler(request);
@@ -1535,9 +1954,9 @@ export default defineEventHandler((event) => handler(toWebRequest(event)));
1535
1954
  default: throw new Error(`No route template for framework: ${framework}`);
1536
1955
  }
1537
1956
  }
1538
- function renderRouteFile(framework, kind, auth = renderAuthWiring("unknown")) {
1539
- const path = routePath(framework, kind);
1540
- let body = renderBody(framework, configImport(path), kind, auth, path);
1957
+ function renderRouteFile(framework, kind, auth = renderAuthWiring("unknown"), layout = "app", paths) {
1958
+ const path = routePath(framework, kind, layout);
1959
+ let body = renderBody(framework, configImport(path), kind, auth, path, paths);
1541
1960
  if (framework === "tanstack-start") {
1542
1961
  const url = `/${path.replace(TANSTACK_ROUTE_PREFIX, "").replace(TS_EXTENSION, "")}`;
1543
1962
  body = body.replace("__ROUTE__", url);
@@ -1549,28 +1968,28 @@ const COMMON_FILES = [{
1549
1968
  description: "Your Clivly configuration",
1550
1969
  owned: false
1551
1970
  }];
1552
- function planScaffold(framework) {
1971
+ function planScaffold(framework, layout = "app") {
1553
1972
  const paths = ROUTE_PATHS[framework];
1554
1973
  if (!paths) return [];
1555
1974
  return [
1556
1975
  {
1557
- path: paths.tick,
1976
+ path: applyLayout(framework, paths.tick, layout),
1558
1977
  description: "Clivly sync-trigger route (createClivlyHandler)",
1559
1978
  owned: true
1560
1979
  },
1561
1980
  {
1562
- path: paths.verify,
1981
+ path: applyLayout(framework, paths.verify, layout),
1563
1982
  description: "Clivly auth-verify route (createAuthVerifyHandler) — finish resolveUser",
1564
1983
  owned: true
1565
1984
  },
1566
1985
  ...COMMON_FILES
1567
1986
  ];
1568
1987
  }
1569
- function planWidgetScaffold(framework) {
1988
+ function planWidgetScaffold(framework, layout = "app") {
1570
1989
  const paths = ROUTE_PATHS[framework];
1571
1990
  if (!paths) return [];
1572
1991
  return [{
1573
- path: paths.session,
1992
+ path: applyLayout(framework, paths.session, layout),
1574
1993
  description: "Clivly chat-session route (createChatSessionHandler) — add allowedOrigins",
1575
1994
  owned: true
1576
1995
  }];
@@ -1590,9 +2009,9 @@ function planFiles(args) {
1590
2009
  const render = (path) => {
1591
2010
  if (path === "clivly.config.ts") return renderInitConfig(args.plan);
1592
2011
  const kind = path.includes("verify") ? "verify" : "tick";
1593
- return renderRouteFile(args.framework, kind, args.authWiring);
2012
+ return renderRouteFile(args.framework, kind, args.authWiring, args.layout, parseTsconfig(args.readFile(join(args.cwd, "tsconfig.json")) ?? "")?.paths);
1594
2013
  };
1595
- for (const file of planScaffold(args.framework)) {
2014
+ for (const file of planScaffold(args.framework, args.layout)) {
1596
2015
  const contents = render(file.path);
1597
2016
  mutations.push({
1598
2017
  path: file.path,
@@ -1623,8 +2042,8 @@ function planMutations(args) {
1623
2042
  };
1624
2043
  }
1625
2044
  function planWidgetMutations(args) {
1626
- return planWidgetScaffold(args.framework).map((file) => {
1627
- const contents = renderRouteFile(args.framework, "session");
2045
+ return planWidgetScaffold(args.framework, args.layout).map((file) => {
2046
+ const contents = renderRouteFile(args.framework, "session", void 0, args.layout);
1628
2047
  return {
1629
2048
  path: file.path,
1630
2049
  contents,
@@ -1949,7 +2368,17 @@ const ALLOWED_CALLS = /* @__PURE__ */ new Set([
1949
2368
  "while"
1950
2369
  ]);
1951
2370
  const SIDE_EFFECT_CALLS = /^(dotenv\.config|config|configDotenv|fileURLToPath|readFileSync|require|process\.chdir)$/;
2371
+ const NATIVE_PACKAGES = /* @__PURE__ */ new Set([
2372
+ "bcrypt",
2373
+ "better-sqlite3",
2374
+ "canvas",
2375
+ "node-gyp",
2376
+ "pg-native",
2377
+ "sharp",
2378
+ "sqlite3"
2379
+ ]);
1952
2380
  const ENV_HINT = "Move it to clivly.cli.ts (`envFiles`) or pass --env-file — the CLI reads those in Node, so your config stays edge-safe.";
2381
+ const NATIVE_HINT = "A compiled binary cannot load on an edge runtime — this is the \"Could not locate the bindings file\" / ERR_DLOPEN_FAILED failure. Import your db lazily inside a function, or use a driver that speaks HTTP (e.g. @neondatabase/serverless) in the config.";
1953
2382
  function isNodeBuiltin(specifier) {
1954
2383
  if (specifier.startsWith("node:")) return true;
1955
2384
  return NODE_BUILTINS.has(specifier.split("/")[0] ?? "");
@@ -1966,6 +2395,12 @@ function specifierIssue(specifier, line) {
1966
2395
  hint: ENV_HINT,
1967
2396
  line
1968
2397
  };
2398
+ if (NATIVE_PACKAGES.has(specifier.split("/")[0] ?? "")) return {
2399
+ code: "native_module_in_edge_config",
2400
+ detail: `imports "${specifier}", which ships a compiled binary`,
2401
+ hint: NATIVE_HINT,
2402
+ line
2403
+ };
1969
2404
  if (isNodeBuiltin(specifier)) return {
1970
2405
  code: "node_builtin_in_edge_config",
1971
2406
  detail: `imports "${specifier}", which does not exist on an edge runtime`,
@@ -2005,8 +2440,56 @@ function analyzeEdgeSafety(source) {
2005
2440
  });
2006
2441
  return issues;
2007
2442
  }
2443
+ /** Every relative specifier `source` imports, in first-seen order, deduped. */
2444
+ function relativeImports(source) {
2445
+ const seen = /* @__PURE__ */ new Set();
2446
+ for (const rawLine of source.split(NEWLINE)) {
2447
+ const line = stripComment(rawLine);
2448
+ const specifier = BARE_IMPORT.exec(line)?.[1] ?? IMPORT_FROM.exec(line)?.[1] ?? REQUIRE_CALL.exec(line)?.[1];
2449
+ if (specifier?.startsWith(".")) seen.add(specifier);
2450
+ }
2451
+ return [...seen];
2452
+ }
2453
+ /**
2454
+ * Edge-safety for the config *and* the modules it imports directly.
2455
+ *
2456
+ * The dominant real-world shape is a clean-looking config with
2457
+ * `import { db } from "./lib/db"`, where the problem is one hop away and
2458
+ * invisible to a scan that reads only the config file.
2459
+ *
2460
+ * One hop, not more: each additional level multiplies the files read for a
2461
+ * shrinking return, and the config's own imports are where a host app puts its
2462
+ * database. Bare specifiers are never followed — resolving into node_modules is
2463
+ * a different job with different failure modes, and the denylist already covers
2464
+ * the packages that matter.
2465
+ *
2466
+ * `readModule` returns source text, or null when the module cannot be read;
2467
+ * unreadable is not a finding, since a scan is not a build.
2468
+ */
2469
+ function analyzeConfigTree(input) {
2470
+ const issues = analyzeEdgeSafety(input.source);
2471
+ for (const specifier of relativeImports(input.source)) {
2472
+ const source = input.readModule(specifier);
2473
+ if (source === null) continue;
2474
+ for (const issue of analyzeEdgeSafety(source)) issues.push({
2475
+ ...issue,
2476
+ module: specifier
2477
+ });
2478
+ }
2479
+ return issues;
2480
+ }
2008
2481
  //#endregion
2009
2482
  //#region src/status-stages.ts
2483
+ const MODULE_CANDIDATES = [
2484
+ ".ts",
2485
+ ".tsx",
2486
+ ".js",
2487
+ ".mjs",
2488
+ ".cjs",
2489
+ "/index.ts",
2490
+ "/index.js",
2491
+ ""
2492
+ ];
2010
2493
  function defaultReadConfigSource(path) {
2011
2494
  try {
2012
2495
  return readFileSync(path, "utf8");
@@ -2021,10 +2504,11 @@ const REASON_HINT = {
2021
2504
  rate_limited: "Rate limited (429). Wait a moment and retry.",
2022
2505
  server_error: "Clivly returned a server error (5xx). Retry shortly.",
2023
2506
  client_error: "The request was rejected (4xx). Check your configuration.",
2507
+ server_too_old: "This Clivly server is older than your CLI and has no /clivly/sdk/ping. Upgrade the server, or pin the CLI to match it.",
2024
2508
  network_error: "Could not reach Clivly. Check your network or --api-url."
2025
2509
  };
2026
2510
  const apiKeyStage = {
2027
- id: "api-key",
2511
+ id: "credential",
2028
2512
  label: "API key present",
2029
2513
  run(ctx) {
2030
2514
  if (ctx.apiKey) return Promise.resolve({
@@ -2034,20 +2518,29 @@ const apiKeyStage = {
2034
2518
  return Promise.resolve({
2035
2519
  state: "fail",
2036
2520
  detail: "Secret key is not set.",
2037
- hint: "Copy your secret key from Settings → API keys into CLIVLY_SECRET_KEY in .env."
2521
+ hint: `Copy your secret key from ${CREDENTIALS_LOCATION} into CLIVLY_SECRET_KEY in .env.`
2038
2522
  });
2039
2523
  }
2040
2524
  };
2041
- const heartbeatStage = {
2042
- id: "heartbeat",
2525
+ const reachabilityStage = {
2526
+ id: "application",
2043
2527
  label: "Clivly reachable",
2044
2528
  needs: [apiKeyStage.id],
2045
2529
  async run(ctx) {
2046
2530
  const result = await ctx.connect(ctx.apiKey, ctx.apiUrl);
2047
- if (result.ok) return {
2048
- state: "pass",
2049
- detail: `Reached org: ${result.org?.name ?? "(unnamed org)"}${result.org?.id ? ` (${result.org.id})` : ""}`
2050
- };
2531
+ if (result.ok) {
2532
+ const name = result.org?.name ?? "(unnamed org)";
2533
+ const id = result.org?.id ? ` (${result.org.id})` : "";
2534
+ if (result.appLastSeenAt === null) return {
2535
+ state: "warn",
2536
+ detail: `Reached org: ${name}${id} — your app has not connected yet`,
2537
+ hint: "Start your app with the Clivly SDK mounted; it will appear in the dashboard within a minute."
2538
+ };
2539
+ return {
2540
+ state: "pass",
2541
+ detail: `Reached org: ${name}${id}`
2542
+ };
2543
+ }
2051
2544
  const status = result.status === null ? "no response" : `HTTP ${result.status}`;
2052
2545
  return {
2053
2546
  state: "fail",
@@ -2075,22 +2568,76 @@ const configStage = {
2075
2568
  }
2076
2569
  }
2077
2570
  };
2078
- const LADDER_OWNED_CHECKS = /* @__PURE__ */ new Set(["API key present", "Heartbeat"]);
2571
+ const LADDER_OWNED_CHECKS = /* @__PURE__ */ new Set(["API key present", "Clivly reachable"]);
2572
+ const sdkChecksStage = {
2573
+ id: "setup-checks",
2574
+ label: "Setup checks",
2575
+ needs: [configStage.id],
2576
+ async run(ctx) {
2577
+ const owned = (await ctx.sdk.doctor()).checks.filter((check) => !LADDER_OWNED_CHECKS.has(check.name));
2578
+ const counted = owned.filter((check) => !check.skipped);
2579
+ const passed = counted.filter((check) => check.ok).length;
2580
+ const ok = counted.every((check) => check.ok);
2581
+ const warned = counted.filter((check) => check.warn).length;
2582
+ const summary = warned > 0 ? `${passed} of ${counted.length} passed, ${warned} with warnings` : `${passed} of ${counted.length} passed`;
2583
+ return {
2584
+ state: ok ? "pass" : "fail",
2585
+ detail: summary,
2586
+ sub: owned.map((check) => ({
2587
+ label: check.name,
2588
+ ok: check.ok,
2589
+ skipped: check.skipped,
2590
+ warn: check.warn,
2591
+ detail: check.detail
2592
+ }))
2593
+ };
2594
+ }
2595
+ };
2596
+ const triggerUrlStage = {
2597
+ id: "trigger-url",
2598
+ label: "Sync trigger URL",
2599
+ needs: [configStage.id],
2600
+ run(ctx) {
2601
+ const url = ctx.sdk?.syncTrigger?.url;
2602
+ if (url) return Promise.resolve({
2603
+ state: "pass",
2604
+ detail: url
2605
+ });
2606
+ return Promise.resolve({
2607
+ state: "warn",
2608
+ detail: "Not set — remote sync cannot call back into this app.",
2609
+ hint: "Set CLIVLY_SYNC_TRIGGER_URL once the app is deployed. For local development run `clivly dev` — it opens a tunnel and registers the URL for you. Push-only setups can ignore this."
2610
+ });
2611
+ }
2612
+ };
2079
2613
  /** The full ladder, in the order a developer completes setup. */
2080
2614
  const STATUS_STAGES = [
2081
2615
  apiKeyStage,
2082
- heartbeatStage,
2616
+ reachabilityStage,
2083
2617
  configStage,
2084
2618
  {
2085
2619
  id: "runtime",
2086
2620
  label: "clivly.config is edge-safe",
2621
+ needs: [configStage.id],
2087
2622
  run(ctx) {
2088
2623
  const source = (ctx.readConfigSource ?? defaultReadConfigSource)(ctx.configPath);
2089
2624
  if (source === null) return Promise.resolve({
2090
2625
  state: "skip",
2091
2626
  detail: "config not readable"
2092
2627
  });
2093
- const issues = analyzeEdgeSafety(source);
2628
+ const read = ctx.readConfigSource ?? defaultReadConfigSource;
2629
+ const base = dirname(ctx.configPath);
2630
+ const issues = analyzeConfigTree({
2631
+ source,
2632
+ readModule: (specifier) => {
2633
+ const target = resolve(base, specifier);
2634
+ for (const candidate of MODULE_CANDIDATES) {
2635
+ const found = read(`${target}${candidate}`);
2636
+ if (found !== null) return found;
2637
+ }
2638
+ return null;
2639
+ }
2640
+ });
2094
2641
  if (issues.length === 0) return Promise.resolve({
2095
2642
  state: "pass",
2096
2643
  detail: "no Node-only code at module scope"
@@ -2107,43 +2654,8 @@ const STATUS_STAGES = [
2107
2654
  });
2108
2655
  }
2109
2656
  },
2110
- {
2111
- id: "setup-checks",
2112
- label: "Setup checks",
2113
- needs: [configStage.id],
2114
- async run(ctx) {
2115
- const owned = (await ctx.sdk.doctor()).checks.filter((check) => !LADDER_OWNED_CHECKS.has(check.name));
2116
- const counted = owned.filter((check) => !check.skipped);
2117
- const passed = counted.filter((check) => check.ok).length;
2118
- return {
2119
- state: counted.every((check) => check.ok) ? "pass" : "fail",
2120
- detail: `${passed} of ${counted.length} passed`,
2121
- sub: owned.map((check) => ({
2122
- label: check.name,
2123
- ok: check.ok,
2124
- skipped: check.skipped,
2125
- detail: check.detail
2126
- }))
2127
- };
2128
- }
2129
- },
2130
- {
2131
- id: "trigger-url",
2132
- label: "Sync trigger URL",
2133
- needs: [configStage.id],
2134
- run(ctx) {
2135
- const url = ctx.sdk?.syncTrigger?.url;
2136
- if (url) return Promise.resolve({
2137
- state: "pass",
2138
- detail: url
2139
- });
2140
- return Promise.resolve({
2141
- state: "warn",
2142
- detail: "Not set — remote sync cannot call back into this app.",
2143
- hint: "Set CLIVLY_SYNC_TRIGGER_URL once the app is deployed. For local development run `clivly dev` — it opens a tunnel and registers the URL for you. Push-only setups can ignore this."
2144
- });
2145
- }
2146
- }
2657
+ sdkChecksStage,
2658
+ triggerUrlStage
2147
2659
  ];
2148
2660
  function defaultLoadSdk(path) {
2149
2661
  return loadConfigSdk(path, "doctor");
@@ -2153,15 +2665,15 @@ function defaultLoadSdk(path) {
2153
2665
  /** Stage ids each legacy command maps onto. */
2154
2666
  const ALIAS_STAGE_IDS = {
2155
2667
  status: STATUS_STAGES.map((stage) => stage.id),
2156
- ping: ["api-key", "heartbeat"],
2668
+ ping: ["credential", "application"],
2157
2669
  doctor: [
2158
2670
  "config",
2159
2671
  "runtime",
2160
2672
  "setup-checks"
2161
2673
  ],
2162
2674
  connect: [
2163
- "api-key",
2164
- "heartbeat",
2675
+ "credential",
2676
+ "application",
2165
2677
  "config",
2166
2678
  "trigger-url"
2167
2679
  ]
@@ -2177,9 +2689,9 @@ const defaultConnect = (apiKey, apiUrl) => createClivlySDK({
2177
2689
  apiKey,
2178
2690
  apiUrl,
2179
2691
  retry: { maxAttempts: 1 }
2180
- }).connect();
2692
+ }).ping();
2181
2693
  function subMark(sub) {
2182
- if (sub.skipped) return "⚠️ ";
2694
+ if (sub.skipped || sub.warn) return "⚠️ ";
2183
2695
  return sub.ok ? "✅" : "❌";
2184
2696
  }
2185
2697
  function renderStage(result, verbose, out) {
@@ -2187,7 +2699,7 @@ function renderStage(result, verbose, out) {
2187
2699
  const detail = result.detail ? ` — ${result.detail}` : "";
2188
2700
  out(` ${MARK[result.state]} ${step} · ${result.label}${detail}\n`);
2189
2701
  for (const sub of result.sub ?? []) {
2190
- if (!(verbose || sub.skipped || !sub.ok)) continue;
2702
+ if (!(verbose || sub.skipped || sub.warn || !sub.ok)) continue;
2191
2703
  const subDetail = sub.detail ? ` — ${sub.detail}` : "";
2192
2704
  out(` ${subMark(sub)} ${sub.label}${subDetail}\n`);
2193
2705
  }
@@ -2213,6 +2725,12 @@ async function runStatus(options) {
2213
2725
  }
2214
2726
  //#endregion
2215
2727
  //#region src/index.ts
2728
+ const ENV_FILE_CANDIDATES = [
2729
+ ".env",
2730
+ ".env.local",
2731
+ ".dev.vars"
2732
+ ];
2733
+ const CONFIG_WATCH_DEBOUNCE_MS = 150;
2216
2734
  function flagValue(argv, flag) {
2217
2735
  const index = argv.indexOf(flag);
2218
2736
  return index >= 0 ? argv[index + 1] : void 0;
@@ -2231,7 +2749,10 @@ const KNOWN_COMMANDS = [
2231
2749
  "push-schema",
2232
2750
  "dev",
2233
2751
  "login",
2234
- "help"
2752
+ "help",
2753
+ "ping",
2754
+ "doctor",
2755
+ "connect"
2235
2756
  ];
2236
2757
  function editDistance(a, b) {
2237
2758
  const m = a.length;
@@ -2274,6 +2795,7 @@ function readDeps(cwd) {
2274
2795
  }
2275
2796
  const ADD_USAGE = "Usage: clivly add widget [--force] [--dry-run]";
2276
2797
  const defaultAddDeps = {
2798
+ fileExists: existsSync,
2277
2799
  out: (line) => process.stdout.write(line),
2278
2800
  readFile: (path) => existsSync(path) ? readFileSync(path, "utf8") : null,
2279
2801
  writeFile: (path, contents) => {
@@ -2293,14 +2815,21 @@ function runAdd(argv, cwd, deps = defaultAddDeps) {
2293
2815
  deps.out("Couldn't detect your framework from package.json. `clivly add widget` supports Next.js, TanStack Start, SvelteKit, Remix, and Nuxt.\n");
2294
2816
  return 1;
2295
2817
  }
2818
+ const layout = resolveAppLayout(cwd, deps.fileExists);
2296
2819
  const force = argv.includes("--force");
2297
2820
  const dryRun = argv.includes("--dry-run");
2298
2821
  const files = planWidgetMutations({
2299
2822
  framework,
2300
2823
  cwd,
2301
2824
  force,
2825
+ layout,
2302
2826
  readFile: (path) => deps.readFile(path)
2303
2827
  });
2828
+ const shadowing = shadowedAppDirError(cwd, framework, files.map((file) => file.path), deps.fileExists);
2829
+ if (shadowing) {
2830
+ deps.out(shadowing);
2831
+ return 1;
2832
+ }
2304
2833
  deps.out(`\nClivly add widget — ${FRAMEWORK_LABELS[framework]}\n\n`);
2305
2834
  if (dryRun) deps.out("Dry run — nothing was written.\n\n");
2306
2835
  for (const file of files) {
@@ -2321,7 +2850,7 @@ function runAdd(argv, cwd, deps = defaultAddDeps) {
2321
2850
  }
2322
2851
  if (!dryRun) {
2323
2852
  const sessionPath = files[0]?.path ?? "";
2324
- deps.out(`\nNext steps:\n 1. Add your site origins to allowedOrigins in ${sessionPath}\n 2. Create the widget + set allowed origins in the Clivly dashboard (Settings → Chat widget)\n 3. Embed it: <ClivlyChatWidget widgetId="…" />\n`);
2853
+ deps.out(`\nNext steps:\n 1. Add your site origins to allowedOrigins in ${sessionPath}\n 2. Create the widget + set allowed origins at ${WIDGET_LOCATION}\n 3. Embed it: <ClivlyChatWidget widgetId="…" />\n`);
2325
2854
  }
2326
2855
  return 0;
2327
2856
  }
@@ -2332,6 +2861,13 @@ function readOwnVersion() {
2332
2861
  if (pkg.name === "clivly" && pkg.version) return pkg.version;
2333
2862
  } catch {}
2334
2863
  }
2864
+ function readOwnEngines() {
2865
+ const req = createRequire(import.meta.url);
2866
+ for (const rel of ["./package.json", "../package.json"]) try {
2867
+ const pkg = req(rel);
2868
+ if (pkg.name === "clivly") return pkg.engines?.node;
2869
+ } catch {}
2870
+ }
2335
2871
  /**
2336
2872
  * Parse a `--db-import` / `--auth-import` value into a discovery-shaped override.
2337
2873
  *
@@ -2361,12 +2897,24 @@ function authInstanceFromFlag(flag) {
2361
2897
  function defaultReadFile(path) {
2362
2898
  return existsSync(path) ? readFileSync(path, "utf8") : null;
2363
2899
  }
2900
+ function resolveEnvPath(cwd) {
2901
+ const framework = detectFramework(readDeps(cwd));
2902
+ return join(cwd, resolveEnvFile({
2903
+ existing: ENV_FILE_CANDIDATES.filter((name) => {
2904
+ const path = join(cwd, name);
2905
+ if (!existsSync(path)) return false;
2906
+ const contents = readFileSync(path, "utf8");
2907
+ return isKeySet(contents, "CLIVLY_SECRET_KEY") || isKeySet(contents, "CLIVLY_API_KEY");
2908
+ }),
2909
+ framework
2910
+ }));
2911
+ }
2364
2912
  function defaultReadEnv(cwd) {
2365
- const path = join(cwd, ".env");
2913
+ const path = resolveEnvPath(cwd);
2366
2914
  return existsSync(path) ? readFileSync(path, "utf8") : "";
2367
2915
  }
2368
2916
  function defaultWriteEnv(cwd, contents) {
2369
- writeFileSync(join(cwd, ".env"), contents, "utf8");
2917
+ writeFileSync(resolveEnvPath(cwd), contents, "utf8");
2370
2918
  }
2371
2919
  function defaultIsInteractive() {
2372
2920
  return Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY) && !process.env.CI;
@@ -2393,6 +2941,8 @@ function resolveInitDeps(options) {
2393
2941
  graph: graphFor(cwd)
2394
2942
  })),
2395
2943
  readFile: options.readFile ?? defaultReadFile,
2944
+ fileExists: options.fileExists ?? existsSync,
2945
+ resolveAppLayout: options.resolveAppLayout ?? resolveAppLayout,
2396
2946
  writeConfig: options.writeConfig ?? ((path, contents) => {
2397
2947
  mkdirSync(dirname(path), { recursive: true });
2398
2948
  writeFileSync(path, contents, "utf8");
@@ -2413,6 +2963,7 @@ function resolveInitDeps(options) {
2413
2963
  rotate: false
2414
2964
  })),
2415
2965
  framework: "unknown",
2966
+ layout: "app",
2416
2967
  authWiring: renderAuthWiring("unknown")
2417
2968
  };
2418
2969
  }
@@ -2427,11 +2978,15 @@ async function acquireSchema(options, deps) {
2427
2978
  const orm = detectOrm(appDeps);
2428
2979
  const auth = detectAuth(appDeps);
2429
2980
  deps.framework = framework;
2981
+ const layout = deps.resolveAppLayout(options.cwd, deps.fileExists);
2982
+ deps.layout = layout;
2430
2983
  deps.authWiring = renderAuthWiring(auth, auth === "better-auth" ? authInstanceFromFlag(options.authImportFlag) ?? await deps.probeAuth(options.cwd) : null);
2431
2984
  out("\nClivly init\n");
2432
2985
  out(` Framework: ${FRAMEWORK_LABELS[framework]}\n`);
2433
2986
  out(` ORM: ${orm}\n`);
2434
- out(` Auth: ${auth}${deps.authWiring.complete ? " (wired)" : ""}\n\n`);
2987
+ out(` Auth: ${auth}${deps.authWiring.complete ? " (wired)" : ""}\n`);
2988
+ if (framework === "nextjs") out(` Layout: ${layout}\n`);
2989
+ out("\n");
2435
2990
  if (orm !== "drizzle") {
2436
2991
  out(`clivly init currently generates config for Drizzle only. Detected ORM: ${orm}\n`);
2437
2992
  return { code: 1 };
@@ -2475,6 +3030,7 @@ function mutationsFor(options, deps, plan) {
2475
3030
  cwd: options.cwd,
2476
3031
  force: options.force,
2477
3032
  framework: deps.framework,
3033
+ layout: deps.layout,
2478
3034
  authWiring: deps.authWiring,
2479
3035
  plan,
2480
3036
  readFile: deps.readFile,
@@ -2534,14 +3090,15 @@ function previewMutations(deps, mutations, options) {
2534
3090
  }
2535
3091
  out(options.diff ? "\nRe-run without --diff to apply; --force to overwrite the files marked conflict.\n" : "\nRe-run without --dry-run to apply.\n");
2536
3092
  }
2537
- function printNextSteps(out, authComplete, loginRan) {
3093
+ function printNextSteps(out, authComplete, loginRan, envFile) {
2538
3094
  out("\nNext steps:\n");
2539
- out(loginRan ? " 1. Credentials written by `clivly login`\n" : " 1. Add CLIVLY_SECRET_KEY to .env — create one in the Clivly dashboard\n under Integrations → Create API Key (or Settings → API keys)\n (the legacy CLIVLY_API_KEY is still accepted)\n");
3095
+ out(loginRan ? " 1. Credentials written by `clivly login`\n" : ` 1. Add CLIVLY_SECRET_KEY to ${envFile} — create one at\n ${CREDENTIALS_LOCATION}\n (the legacy CLIVLY_API_KEY is still accepted)\n`);
2540
3096
  out(" 2. Set CLIVLY_SYNC_TRIGGER_URL to your public tick route\n");
2541
3097
  out(" Local dev? Run `clivly dev` to open a tunnel, or skip this step until you deploy (remote sync is deploy-only locally).\n");
2542
3098
  const step = authComplete ? 3 : 4;
2543
3099
  if (!authComplete) out(" 3. Finish resolveUser in the auth/verify route\n");
2544
3100
  out(` ${step}. Run \`clivly status\` to see where you are\n`);
3101
+ out("\nAfter editing clivly.config.ts, restart your app — it loads the config\nat boot, so a running server keeps using the old one.\n");
2545
3102
  }
2546
3103
  function credentialsMissing(envContents) {
2547
3104
  return !(isKeySet(envContents, "CLIVLY_SECRET_KEY") || isKeySet(envContents, "CLIVLY_API_KEY"));
@@ -2562,6 +3119,11 @@ async function scaffold(options, deps, plan) {
2562
3119
  const pm = deps.detectPackageManager(options.cwd);
2563
3120
  const packages = [resolveRuntimeInstallSpec(deps), ...deps.authWiring.packages];
2564
3121
  const mutations = mutationsFor(options, deps, plan);
3122
+ const shadowing = shadowedAppDirError(options.cwd, deps.framework, mutations.files.map((file) => file.path), deps.fileExists);
3123
+ if (shadowing) {
3124
+ out(shadowing);
3125
+ return 1;
3126
+ }
2565
3127
  if (options.dryRun || options.diff) {
2566
3128
  out(`\nWould install (${pm}): ${packages.join(", ")}\n`);
2567
3129
  previewMutations(deps, mutations, {
@@ -2586,7 +3148,7 @@ async function scaffold(options, deps, plan) {
2586
3148
  out(" Run `clivly login` from a terminal to write CLIVLY_SECRET_KEY and CLIVLY_SYNC_TRIGGER_SECRET.\n");
2587
3149
  } else loginRan = await deps.login(options.cwd) === 0;
2588
3150
  }
2589
- printNextSteps(out, deps.authWiring.complete, loginRan);
3151
+ printNextSteps(out, deps.authWiring.complete, loginRan, envFileFor(detectFramework(deps.readDepsFn(options.cwd))));
2590
3152
  return 0;
2591
3153
  }
2592
3154
  function normalizeAppRoot(options) {
@@ -2653,8 +3215,18 @@ function printNoContactGuidance(out, plan, options) {
2653
3215
  out(`\n Tables in ${plan.importPath}:\n`);
2654
3216
  for (const name of plan.tableNames) out(` ${name}\n`);
2655
3217
  const schemaArg = options.schemaFlag ? ` --schema ${options.schemaFlag}` : "";
2656
- out("\n Pick the one that holds your people and re-run:\n");
2657
- out(` clivly init${schemaArg} --contact-table ${plan.tableNames[0]}\n\n`);
3218
+ const best = plan.contactCandidates[0];
3219
+ if (best) {
3220
+ out(`\n Best guess: ${best.table} — ${best.reasons.join(", ")}\n`);
3221
+ const runnerUp = plan.contactCandidates.slice(1, 3).map((candidate) => candidate.table);
3222
+ if (runnerUp.length > 0) out(` Also possible: ${runnerUp.join(", ")}\n`);
3223
+ out("\n Confirm it and re-run:\n");
3224
+ out(` clivly init${schemaArg} --contact-table ${best.table}\n\n`);
3225
+ return;
3226
+ }
3227
+ out("\n Nothing here looks like a people table — no email, phone or name\n");
3228
+ out(" columns turned up. Pick the one that holds your people and re-run:\n");
3229
+ out(` clivly init${schemaArg} --contact-table ${plan.tableNames[0] ?? "<table>"}\n\n`);
2658
3230
  out(" Nothing was written — Clivly needs one entity before a config can load.\n\n");
2659
3231
  }
2660
3232
  function hasCloudflaredOnPath() {
@@ -2750,6 +3322,22 @@ function defaultDevDeps(options) {
2750
3322
  },
2751
3323
  out: (line) => {
2752
3324
  process.stdout.write(`${line}\n`);
3325
+ },
3326
+ watchConfig: (cwd, onChange) => {
3327
+ const target = resolveConfigPath(cwd);
3328
+ try {
3329
+ let timer = null;
3330
+ const watcher = watch(target, () => {
3331
+ if (timer) clearTimeout(timer);
3332
+ timer = setTimeout(onChange, CONFIG_WATCH_DEBOUNCE_MS);
3333
+ });
3334
+ return () => {
3335
+ if (timer) clearTimeout(timer);
3336
+ watcher.close();
3337
+ };
3338
+ } catch {
3339
+ return null;
3340
+ }
2753
3341
  }
2754
3342
  };
2755
3343
  }
@@ -2828,6 +3416,21 @@ function runInitFromArgv(argv, cwd) {
2828
3416
  }
2829
3417
  async function main(argv) {
2830
3418
  const [command, ...rest] = argv;
3419
+ if (command === "-h" || command === "--help" || isHelpRequest(rest)) {
3420
+ process.stdout.write(helpFor(command));
3421
+ return 0;
3422
+ }
3423
+ if (command === "--version" || command === "-v") {
3424
+ process.stdout.write(`${readOwnVersion() ?? "unknown"}\n`);
3425
+ return 0;
3426
+ }
3427
+ if (!process.env.CLIVLY_SKIP_ENGINE_CHECK) {
3428
+ const engineProblem = engineError(process.version, readOwnEngines());
3429
+ if (engineProblem) {
3430
+ process.stderr.write(engineProblem);
3431
+ return 1;
3432
+ }
3433
+ }
2831
3434
  let cliEnvFiles = [];
2832
3435
  try {
2833
3436
  cliEnvFiles = (await loadCliConfig(process.cwd()))?.envFiles ?? [];
@@ -2846,14 +3449,16 @@ async function main(argv) {
2846
3449
  case "status":
2847
3450
  case "ping":
2848
3451
  case "doctor":
2849
- case "connect": return await runStatus({
2850
- cwd: process.cwd(),
2851
- apiKey: readSecretKeyEnv(process.env),
2852
- apiUrl: flagValue(rest, "--api-url") ?? process.env.CLIVLY_API_URL,
2853
- configPath: flagValue(rest, "--config"),
2854
- only: ALIAS_STAGE_IDS[command],
2855
- verbose: rest.includes("--verbose")
2856
- });
3452
+ case "connect":
3453
+ if (command !== "status") process.stderr.write(`\`clivly ${command}\` is a deprecated alias that runs part of \`clivly status\`. Prefer \`clivly status\`.\n`);
3454
+ return await runStatus({
3455
+ cwd: process.cwd(),
3456
+ apiKey: readSecretKeyEnv(process.env),
3457
+ apiUrl: flagValue(rest, "--api-url") ?? process.env.CLIVLY_API_URL,
3458
+ configPath: flagValue(rest, "--config"),
3459
+ only: ALIAS_STAGE_IDS[command],
3460
+ verbose: rest.includes("--verbose")
3461
+ });
2857
3462
  case "dev": {
2858
3463
  const apiKey = readSecretKeyEnv(process.env);
2859
3464
  const apiUrl = flagValue(rest, "--api-url") ?? process.env.CLIVLY_API_URL ?? "https://api.clivly.com";
@@ -2876,14 +3481,11 @@ async function main(argv) {
2876
3481
  openBrowser: !rest.includes("--no-browser"),
2877
3482
  deps: defaultLoginDeps()
2878
3483
  });
2879
- case "--version":
2880
- case "-v":
2881
- process.stdout.write(`${readOwnVersion() ?? "unknown"}\n`);
2882
- return 0;
2883
3484
  case void 0:
3485
+ process.stdout.write(ROOT_HELP);
3486
+ return 0;
2884
3487
  case "help":
2885
- case "--help":
2886
- process.stdout.write("clivly — embed a CRM in your app\n\nUsage:\n clivly init [--force] [--dry-run] [--diff] [--yes] [--no-login] [--no-browser]\n [--schema <path|package>] [--db-import <specifier>] [--auth-import <specifier>]\n Scaffold Clivly (config, routes, .env) for your app\n clivly add widget [--force] [--dry-run] Scaffold the chat-session route\n clivly status [--verbose] [--config <path>] [--env-file <path>] Check your setup, step by step\n clivly push-schema [--config <path>] Report your schema to Clivly without deploying\n clivly dev [--port <n>] [--api-url <url>] [--route-path <path>] [-- <cmd>] Tunnel localhost for remote sync\n clivly login [--force] [--rotate] [--api-url <url>] [--no-browser] Pair this machine and write CLIVLY_SECRET_KEY / CLIVLY_SYNC_TRIGGER_SECRET to .env\n clivly --version Print the installed clivly version\n");
3488
+ process.stdout.write(helpFor(rest[0]));
2887
3489
  return 0;
2888
3490
  default: {
2889
3491
  process.stdout.write(`Unknown command: ${command}\n`);