clivly 0.7.2 → 0.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +362 -110
- package/drizzle.cjs +7 -3
- package/drizzle.d.cts +1 -9
- package/drizzle.d.mts +1 -9
- package/drizzle.mjs +7 -3
- package/index.cjs +736 -118
- package/index.d.cts +6 -0
- package/index.d.mts +6 -0
- package/index.mjs +737 -119
- package/internal-entity-heuristics.cjs +27 -7
- package/internal-entity-heuristics.mjs +27 -7
- package/namespace-probe-B4WE45TH.d.mts +372 -0
- package/namespace-probe-DRzOtaRT.d.cts +372 -0
- package/package.json +1 -1
- package/{sdk-iqOXeWIp.cjs → sdk-Bj-ZDf4u.cjs} +126 -28
- package/{sdk-C6WANW8M.mjs → sdk-BvRD2jAp.mjs} +126 -28
- package/sdk.cjs +1 -1
- package/sdk.d.cts +36 -1
- package/sdk.d.mts +36 -1
- package/sdk.mjs +1 -1
- package/vite.d.cts +1 -1
- package/vite.d.mts +1 -1
- package/types-CsL0rFYh.d.cts +0 -155
- package/types-CsL0rFYh.d.mts +0 -155
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-
|
|
5
|
+
import { t as createClivlySDK } from "./sdk-BvRD2jAp.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
|
{
|
|
@@ -253,8 +327,19 @@ const OVERRIDE_FAILURE_CAUSES = {
|
|
|
253
327
|
not_enabled: "The target backend does not have the feature-flagged trigger-url endpoint enabled (likely the wrong backend, or the flag is off).",
|
|
254
328
|
unreachable: "Could not reach Clivly at the selected API base URL."
|
|
255
329
|
};
|
|
256
|
-
|
|
257
|
-
|
|
330
|
+
/**
|
|
331
|
+
* `status` is required in practice for `unexpected_response` and meaningless
|
|
332
|
+
* for the others.
|
|
333
|
+
*
|
|
334
|
+
* Every non-401/404 status used to collapse into `unreachable`, so the CLI told
|
|
335
|
+
* developers it "could not reach Clivly" while Clivly was answering. That is
|
|
336
|
+
* not a wording nit: when neon-http broke these endpoints in production the CLI
|
|
337
|
+
* discarded the one honest signal it had (HTTP 500) and sent people to check
|
|
338
|
+
* their network and API URL, where nothing was wrong. A response is proof of
|
|
339
|
+
* reachability — so say what came back.
|
|
340
|
+
*/
|
|
341
|
+
function overrideFailureMessage(kind, status) {
|
|
342
|
+
return `Warning: could not register the tunnel URL — ${kind === "unexpected_response" ? `Clivly answered HTTP ${status ?? "an error"} — the request reached Clivly but was rejected, so this is a Clivly-side or request problem rather than a network one.` : OVERRIDE_FAILURE_CAUSES[kind]} Dashboard-triggered sync is unavailable this session. Your app is still running.`;
|
|
258
343
|
}
|
|
259
344
|
function cloudflaredMissingMessage() {
|
|
260
345
|
return [
|
|
@@ -309,12 +394,16 @@ async function runDev(options) {
|
|
|
309
394
|
deps.out(`Tunnel: ${triggerUrl}`);
|
|
310
395
|
const result = await deps.register(triggerUrl).catch(() => UNREACHABLE_RESULT);
|
|
311
396
|
if (result.ok) deps.out("Dashboard-triggered sync now points at this local session.");
|
|
312
|
-
else deps.out(overrideFailureMessage(result.kind));
|
|
397
|
+
else deps.out(overrideFailureMessage(result.kind, result.status));
|
|
313
398
|
});
|
|
399
|
+
const stopWatching = deps.watchConfig?.(options.cwd, () => {
|
|
400
|
+
deps.out("clivly.config.ts changed — restart your app for it to take effect.");
|
|
401
|
+
}) ?? null;
|
|
314
402
|
return await new Promise((resolve) => {
|
|
315
403
|
const shutdown = async (code) => {
|
|
316
404
|
if (shuttingDown) return;
|
|
317
405
|
shuttingDown = true;
|
|
406
|
+
stopWatching?.();
|
|
318
407
|
tunnel.kill();
|
|
319
408
|
app?.kill();
|
|
320
409
|
if (!(await deps.clear().catch(() => UNREACHABLE_RESULT)).ok) deps.out("Warning: could not clear the tunnel override on exit.");
|
|
@@ -336,7 +425,18 @@ const HTTP_NOT_FOUND = 404;
|
|
|
336
425
|
function kindForStatus(status) {
|
|
337
426
|
if (status === HTTP_UNAUTHORIZED) return "unauthorized";
|
|
338
427
|
if (status === HTTP_NOT_FOUND) return "not_enabled";
|
|
339
|
-
return "
|
|
428
|
+
return "unexpected_response";
|
|
429
|
+
}
|
|
430
|
+
function failureFor(status) {
|
|
431
|
+
const kind = kindForStatus(status);
|
|
432
|
+
return kind === "unexpected_response" ? {
|
|
433
|
+
ok: false,
|
|
434
|
+
kind,
|
|
435
|
+
status
|
|
436
|
+
} : {
|
|
437
|
+
ok: false,
|
|
438
|
+
kind
|
|
439
|
+
};
|
|
340
440
|
}
|
|
341
441
|
async function registerTunnelOverride(deps) {
|
|
342
442
|
const res = await (deps.fetchImpl ?? globalThis.fetch)(`${deps.apiUrl}${TRIGGER_URL_PATH}`, {
|
|
@@ -348,10 +448,7 @@ async function registerTunnelOverride(deps) {
|
|
|
348
448
|
body: JSON.stringify({ url: deps.triggerUrl })
|
|
349
449
|
});
|
|
350
450
|
if (res.ok) return { ok: true };
|
|
351
|
-
return
|
|
352
|
-
ok: false,
|
|
353
|
-
kind: kindForStatus(res.status)
|
|
354
|
-
};
|
|
451
|
+
return failureFor(res.status);
|
|
355
452
|
}
|
|
356
453
|
async function clearTunnelOverride(deps) {
|
|
357
454
|
const res = await (deps.fetchImpl ?? globalThis.fetch)(`${deps.apiUrl}${TRIGGER_URL_PATH}`, {
|
|
@@ -359,10 +456,7 @@ async function clearTunnelOverride(deps) {
|
|
|
359
456
|
headers: { authorization: `Bearer ${deps.apiKey}` }
|
|
360
457
|
});
|
|
361
458
|
if (res.ok) return { ok: true };
|
|
362
|
-
return
|
|
363
|
-
ok: false,
|
|
364
|
-
kind: kindForStatus(res.status)
|
|
365
|
-
};
|
|
459
|
+
return failureFor(res.status);
|
|
366
460
|
}
|
|
367
461
|
//#endregion
|
|
368
462
|
//#region src/probe-module.ts
|
|
@@ -767,6 +861,29 @@ async function discoverSchema(opts) {
|
|
|
767
861
|
};
|
|
768
862
|
}
|
|
769
863
|
//#endregion
|
|
864
|
+
//#region src/engine-check.ts
|
|
865
|
+
const MAJOR = /^v?(\d+)/;
|
|
866
|
+
const FIRST_NUMBER = /(\d+)/;
|
|
867
|
+
function currentMajor(version) {
|
|
868
|
+
const match = MAJOR.exec(version);
|
|
869
|
+
return match ? Number(match[1]) : null;
|
|
870
|
+
}
|
|
871
|
+
function requiredMajor(range) {
|
|
872
|
+
if (!range) return null;
|
|
873
|
+
const match = FIRST_NUMBER.exec(range);
|
|
874
|
+
return match ? Number(match[1]) : null;
|
|
875
|
+
}
|
|
876
|
+
function engineError(currentVersion, enginesRange) {
|
|
877
|
+
const have = currentMajor(currentVersion);
|
|
878
|
+
const need = requiredMajor(enginesRange);
|
|
879
|
+
if (have === null || need === null || have >= need) return null;
|
|
880
|
+
return `Clivly requires Node.js ${need} or newer. You are running ${currentVersion}.
|
|
881
|
+
|
|
882
|
+
Upgrade with \`nvm install ${need}\` (or your version manager of choice), then re-run.
|
|
883
|
+
Set CLIVLY_SKIP_ENGINE_CHECK=1 to run anyway — expect unrelated-looking failures.
|
|
884
|
+
`;
|
|
885
|
+
}
|
|
886
|
+
//#endregion
|
|
770
887
|
//#region src/env-file.ts
|
|
771
888
|
const REGEX_METACHARACTERS = /[.*+?^${}()|[\]\\]/g;
|
|
772
889
|
function escapeForRegExp(key) {
|
|
@@ -851,6 +968,123 @@ function upsertEnvValues(existing, entries, options = {}) {
|
|
|
851
968
|
};
|
|
852
969
|
}
|
|
853
970
|
//#endregion
|
|
971
|
+
//#region src/help.ts
|
|
972
|
+
const ROOT_HELP = `clivly — embed a CRM in your app
|
|
973
|
+
|
|
974
|
+
Usage:
|
|
975
|
+
clivly init [options] Scaffold Clivly (config, routes, env file) for your app
|
|
976
|
+
clivly add widget [options] Scaffold the chat-session route
|
|
977
|
+
clivly status [options] Check your setup, step by step
|
|
978
|
+
clivly push-schema [options] Report your schema to Clivly without deploying
|
|
979
|
+
clivly dev [options] Tunnel localhost so remote sync can reach you
|
|
980
|
+
clivly login [options] Pair this machine and write credentials to your env file
|
|
981
|
+
clivly --version Print the installed clivly version
|
|
982
|
+
|
|
983
|
+
Deprecated aliases — each runs part of \`clivly status\` and still works:
|
|
984
|
+
clivly ping credential + reachability
|
|
985
|
+
clivly connect the above, plus config and trigger URL
|
|
986
|
+
clivly doctor config, setup checks and edge safety
|
|
987
|
+
|
|
988
|
+
Prefer \`clivly status\`: it runs the whole ladder and tells you which step you
|
|
989
|
+
are on. The aliases are kept because output and docs have recommended them.
|
|
990
|
+
|
|
991
|
+
Run \`clivly <command> --help\` for details on a command.
|
|
992
|
+
`;
|
|
993
|
+
const COMMAND_HELP = {
|
|
994
|
+
init: `clivly init — scaffold Clivly into this app
|
|
995
|
+
|
|
996
|
+
Usage:
|
|
997
|
+
clivly init [--force] [--dry-run] [--diff] [--yes] [--no-login] [--no-browser]
|
|
998
|
+
[--schema <path|package>] [--db-import <specifier>]
|
|
999
|
+
[--auth-import <specifier>] [--contact-table <table>]
|
|
1000
|
+
[--company-table <table>]
|
|
1001
|
+
|
|
1002
|
+
Scaffolds clivly.config.ts, the Clivly route files, and .env placeholders.
|
|
1003
|
+
Detects your framework, ORM, auth adapter and app layout from the project.
|
|
1004
|
+
|
|
1005
|
+
Options:
|
|
1006
|
+
--dry-run Show what would be written; write nothing
|
|
1007
|
+
--diff Show a diff for files that already exist
|
|
1008
|
+
--force Overwrite files Clivly owns
|
|
1009
|
+
--yes Skip prompts
|
|
1010
|
+
--no-login Skip browser pairing
|
|
1011
|
+
--schema <p> Path or package holding your ORM schema
|
|
1012
|
+
--db-import <s> Module specifier exporting your database instance
|
|
1013
|
+
--auth-import <s> Module specifier exporting your auth instance
|
|
1014
|
+
--contact-table <t> Table to map as contacts
|
|
1015
|
+
--company-table <t> Table to map as companies
|
|
1016
|
+
`,
|
|
1017
|
+
add: `clivly add widget — scaffold the chat-session route
|
|
1018
|
+
|
|
1019
|
+
Usage:
|
|
1020
|
+
clivly add widget [--force] [--dry-run]
|
|
1021
|
+
|
|
1022
|
+
Writes the route that mints chat-widget sessions. Creates no widget record —
|
|
1023
|
+
that lives in the Clivly dashboard.
|
|
1024
|
+
|
|
1025
|
+
Options:
|
|
1026
|
+
--dry-run Show what would be written; write nothing
|
|
1027
|
+
--force Overwrite the route if it already exists
|
|
1028
|
+
`,
|
|
1029
|
+
status: `clivly status — check your setup, step by step
|
|
1030
|
+
|
|
1031
|
+
Usage:
|
|
1032
|
+
clivly status [--verbose] [--config <path>] [--env-file <path>]
|
|
1033
|
+
|
|
1034
|
+
Runs the setup ladder: credential, reachability, config load, edge-safety,
|
|
1035
|
+
setup checks, sync trigger. Read-only — writes nothing.
|
|
1036
|
+
|
|
1037
|
+
Options:
|
|
1038
|
+
--verbose Show every check, including those that passed
|
|
1039
|
+
--config <path> Path to clivly.config.ts
|
|
1040
|
+
--env-file <path> Extra env file to load
|
|
1041
|
+
`,
|
|
1042
|
+
"push-schema": `clivly push-schema — report your schema without deploying
|
|
1043
|
+
|
|
1044
|
+
Usage:
|
|
1045
|
+
clivly push-schema [--config <path>]
|
|
1046
|
+
|
|
1047
|
+
Sends your discovered tables to Clivly so the dashboard can offer them for
|
|
1048
|
+
mapping. Reads your config; writes nothing locally.
|
|
1049
|
+
`,
|
|
1050
|
+
dev: `clivly dev — tunnel localhost so remote sync can reach you
|
|
1051
|
+
|
|
1052
|
+
Usage:
|
|
1053
|
+
clivly dev [--port <n>] [--api-url <url>] [--route-path <path>] [-- <cmd>]
|
|
1054
|
+
|
|
1055
|
+
Opens a tunnel to your local app and points Clivly's sync trigger at it.
|
|
1056
|
+
Everything after \`--\` runs as your app's dev command.
|
|
1057
|
+
|
|
1058
|
+
Options:
|
|
1059
|
+
--port <n> Local port your app listens on
|
|
1060
|
+
--route-path <path> Path to your mounted tick route
|
|
1061
|
+
`,
|
|
1062
|
+
login: `clivly login — pair this machine with Clivly
|
|
1063
|
+
|
|
1064
|
+
Usage:
|
|
1065
|
+
clivly login [--force] [--rotate] [--api-url <url>] [--no-browser]
|
|
1066
|
+
|
|
1067
|
+
Opens a browser to approve this machine, then writes CLIVLY_SECRET_KEY and
|
|
1068
|
+
CLIVLY_SYNC_TRIGGER_SECRET to .env.
|
|
1069
|
+
|
|
1070
|
+
Options:
|
|
1071
|
+
--force Re-pair even if credentials already exist
|
|
1072
|
+
--rotate Replace the existing credentials
|
|
1073
|
+
--no-browser Print the URL instead of opening a browser
|
|
1074
|
+
`
|
|
1075
|
+
};
|
|
1076
|
+
function isHelpRequest(argv) {
|
|
1077
|
+
for (const arg of argv) {
|
|
1078
|
+
if (arg === "--") return false;
|
|
1079
|
+
if (arg === "--help" || arg === "-h") return true;
|
|
1080
|
+
}
|
|
1081
|
+
return false;
|
|
1082
|
+
}
|
|
1083
|
+
function helpFor(command) {
|
|
1084
|
+
if (!command) return ROOT_HELP;
|
|
1085
|
+
return COMMAND_HELP[command] ?? ROOT_HELP;
|
|
1086
|
+
}
|
|
1087
|
+
//#endregion
|
|
854
1088
|
//#region src/install.ts
|
|
855
1089
|
const defaultRun = (command, args, cwd) => new Promise((resolvePromise, reject) => {
|
|
856
1090
|
const child = spawn(command, args, {
|
|
@@ -1090,11 +1324,11 @@ function credentialEntries(credentials) {
|
|
|
1090
1324
|
return [{
|
|
1091
1325
|
key: SECRET_KEY_ENV,
|
|
1092
1326
|
value: credentials.apiKey,
|
|
1093
|
-
comment:
|
|
1327
|
+
comment: `Org secret key — ${CREDENTIALS_LOCATION}`
|
|
1094
1328
|
}, {
|
|
1095
1329
|
key: "CLIVLY_SYNC_TRIGGER_SECRET",
|
|
1096
1330
|
value: credentials.triggerSecret,
|
|
1097
|
-
comment:
|
|
1331
|
+
comment: `Signing secret — ${SYNC_SECRET_LOCATION}`
|
|
1098
1332
|
}];
|
|
1099
1333
|
}
|
|
1100
1334
|
function writeCredentials(options, credentials) {
|
|
@@ -1181,12 +1415,19 @@ function chooseSyncFields(table, todos) {
|
|
|
1181
1415
|
idField
|
|
1182
1416
|
};
|
|
1183
1417
|
}
|
|
1418
|
+
const SPLIT_NAME_COLUMNS = /* @__PURE__ */ new Set([
|
|
1419
|
+
"first_name",
|
|
1420
|
+
"firstname",
|
|
1421
|
+
"given_name"
|
|
1422
|
+
]);
|
|
1184
1423
|
function buildEntity(table, concept, todos) {
|
|
1185
1424
|
const canonical = CANONICAL_FIELDS[concept];
|
|
1186
1425
|
const suggested = toFieldMap(scoreFieldMap(concept, toScoredTable(table)));
|
|
1187
1426
|
const fields = {};
|
|
1188
1427
|
for (const [key, column] of Object.entries(suggested)) if (canonical.includes(key)) fields[key] = column;
|
|
1189
1428
|
for (const required of requiredFieldsFor(concept)) if (!fields[required]) todos.push(`Could not map required ${concept} field "${required}" on "${table.tableName}" — add it manually.`);
|
|
1429
|
+
const nameColumn = fields.name?.toLowerCase();
|
|
1430
|
+
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
1431
|
const { cursorField, idField } = chooseSyncFields(table, todos);
|
|
1191
1432
|
return {
|
|
1192
1433
|
moduleKey: table.moduleKey,
|
|
@@ -1257,15 +1498,99 @@ function planInit(schema, overrides = {}) {
|
|
|
1257
1498
|
contact,
|
|
1258
1499
|
company,
|
|
1259
1500
|
tableNames: schema.tables.map((table) => table.tableName),
|
|
1501
|
+
contactCandidates: rankContactCandidates(schema.tables),
|
|
1260
1502
|
todos
|
|
1261
1503
|
};
|
|
1262
1504
|
}
|
|
1505
|
+
const CONTACT_COLUMN_EVIDENCE = [
|
|
1506
|
+
{
|
|
1507
|
+
label: "email",
|
|
1508
|
+
names: ["email", "email_address"],
|
|
1509
|
+
weight: 3
|
|
1510
|
+
},
|
|
1511
|
+
{
|
|
1512
|
+
label: "phone",
|
|
1513
|
+
names: [
|
|
1514
|
+
"phone",
|
|
1515
|
+
"phone_number",
|
|
1516
|
+
"mobile"
|
|
1517
|
+
],
|
|
1518
|
+
weight: 2
|
|
1519
|
+
},
|
|
1520
|
+
{
|
|
1521
|
+
label: "first name",
|
|
1522
|
+
names: [
|
|
1523
|
+
"first_name",
|
|
1524
|
+
"firstname",
|
|
1525
|
+
"given_name"
|
|
1526
|
+
],
|
|
1527
|
+
weight: 2
|
|
1528
|
+
},
|
|
1529
|
+
{
|
|
1530
|
+
label: "last name",
|
|
1531
|
+
names: [
|
|
1532
|
+
"last_name",
|
|
1533
|
+
"lastname",
|
|
1534
|
+
"surname",
|
|
1535
|
+
"family_name"
|
|
1536
|
+
],
|
|
1537
|
+
weight: 2
|
|
1538
|
+
},
|
|
1539
|
+
{
|
|
1540
|
+
label: "name",
|
|
1541
|
+
names: [
|
|
1542
|
+
"name",
|
|
1543
|
+
"full_name",
|
|
1544
|
+
"display_name"
|
|
1545
|
+
],
|
|
1546
|
+
weight: 1
|
|
1547
|
+
}
|
|
1548
|
+
];
|
|
1549
|
+
const NAME_MATCH_WEIGHT = 4;
|
|
1550
|
+
/**
|
|
1551
|
+
* Rank the schema's tables by how much they look like people, best first.
|
|
1552
|
+
*
|
|
1553
|
+
* Used only on the failure path, where detection found nothing mappable and the
|
|
1554
|
+
* developer has to choose. `init` previously suggested `tableNames[0]` — the
|
|
1555
|
+
* first table in schema order — so a rental app was told to map its `lease`
|
|
1556
|
+
* table as contacts. Wrong guidance is worse than none: it is confident, and
|
|
1557
|
+
* the developer has no way to see it is wrong.
|
|
1558
|
+
*
|
|
1559
|
+
* Deliberately evidence-based rather than name-based alone, so a table whose
|
|
1560
|
+
* name Clivly has never heard of still surfaces on the strength of its columns.
|
|
1561
|
+
*/
|
|
1562
|
+
function rankContactCandidates(tables) {
|
|
1563
|
+
return tables.map((table) => {
|
|
1564
|
+
const columns = new Set(table.columns.flatMap((c) => [c.dbName.toLowerCase(), c.key.toLowerCase()]));
|
|
1565
|
+
const reasons = [];
|
|
1566
|
+
let score = 0;
|
|
1567
|
+
if (matchesConcept(table.tableName, "contact")) {
|
|
1568
|
+
score += NAME_MATCH_WEIGHT;
|
|
1569
|
+
reasons.push("the name looks like a people table");
|
|
1570
|
+
}
|
|
1571
|
+
for (const evidence of CONTACT_COLUMN_EVIDENCE) {
|
|
1572
|
+
const hit = evidence.names.find((name) => columns.has(name));
|
|
1573
|
+
if (hit) {
|
|
1574
|
+
score += evidence.weight;
|
|
1575
|
+
reasons.push(hit);
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
return {
|
|
1579
|
+
reasons,
|
|
1580
|
+
score,
|
|
1581
|
+
table: table.tableName
|
|
1582
|
+
};
|
|
1583
|
+
}).filter((candidate) => candidate.score > 0).sort((a, b) => b.score - a.score || a.table.localeCompare(b.table)).map(({ reasons, table }) => ({
|
|
1584
|
+
reasons,
|
|
1585
|
+
table
|
|
1586
|
+
}));
|
|
1587
|
+
}
|
|
1263
1588
|
//#endregion
|
|
1264
1589
|
//#region src/render-config.ts
|
|
1265
1590
|
const CLIVLY_ENV_KEYS = [
|
|
1266
1591
|
{
|
|
1267
1592
|
key: "CLIVLY_SECRET_KEY",
|
|
1268
|
-
comment:
|
|
1593
|
+
comment: `Org secret key — ${CREDENTIALS_LOCATION}`
|
|
1269
1594
|
},
|
|
1270
1595
|
{
|
|
1271
1596
|
key: "CLIVLY_SYNC_TRIGGER_URL",
|
|
@@ -1273,7 +1598,7 @@ const CLIVLY_ENV_KEYS = [
|
|
|
1273
1598
|
},
|
|
1274
1599
|
{
|
|
1275
1600
|
key: "CLIVLY_SYNC_TRIGGER_SECRET",
|
|
1276
|
-
comment:
|
|
1601
|
+
comment: `Signing secret — ${SYNC_SECRET_LOCATION}`
|
|
1277
1602
|
}
|
|
1278
1603
|
];
|
|
1279
1604
|
function renderFields(fields) {
|
|
@@ -1302,6 +1627,28 @@ function renderDbExpr(plan) {
|
|
|
1302
1627
|
if (!plan.db) return "db";
|
|
1303
1628
|
return dbIsInSchemaModule(plan) ? `schema.${plan.db.moduleKey}` : plan.db.moduleKey;
|
|
1304
1629
|
}
|
|
1630
|
+
const TRAILING_SCHEMA_SEGMENT = /\/schema(\/index)?$/;
|
|
1631
|
+
/**
|
|
1632
|
+
* Where the `db` instance most likely lives, given where the schema was found.
|
|
1633
|
+
*
|
|
1634
|
+
* Only reached when discovery could not confirm one. Discovery *evaluates* a
|
|
1635
|
+
* candidate module and duck-types its exports for `.select`, which is the right
|
|
1636
|
+
* check but fails for the most common real-world db module: `drizzle(process.
|
|
1637
|
+
* env.DATABASE_URL!)` throws at import time when the env var is absent, and it
|
|
1638
|
+
* is absent precisely when a developer is running `clivly init` for the first
|
|
1639
|
+
* time. So the probe misses, through no fault of the project.
|
|
1640
|
+
*
|
|
1641
|
+
* The old fallback emitted `<YOUR_DB_MODULE>` — not a module specifier, not
|
|
1642
|
+
* valid TypeScript, and invisible until the config failed to load at runtime.
|
|
1643
|
+
* A best-guess relative path is strictly better: right for the conventional
|
|
1644
|
+
* layout (`lib/db/schema.ts` beside `lib/db/index.ts`), and when it is wrong it
|
|
1645
|
+
* is a module-not-found error at build time, naming a real path the developer
|
|
1646
|
+
* can correct.
|
|
1647
|
+
*/
|
|
1648
|
+
function guessDbImportPath(schemaImportPath) {
|
|
1649
|
+
const trimmed = schemaImportPath.replace(TRAILING_SCHEMA_SEGMENT, "");
|
|
1650
|
+
return trimmed === schemaImportPath || trimmed === "." || trimmed === "" ? "./db" : trimmed;
|
|
1651
|
+
}
|
|
1305
1652
|
function renderImports(plan) {
|
|
1306
1653
|
const lines = [
|
|
1307
1654
|
"import { createClivlySDK, defineClivlyConfig } from \"clivly/sdk\";",
|
|
@@ -1309,8 +1656,10 @@ function renderImports(plan) {
|
|
|
1309
1656
|
"import { discoverFromDrizzle } from \"clivly/drizzle\";",
|
|
1310
1657
|
`import * as schema from "${plan.importPath}";`
|
|
1311
1658
|
];
|
|
1312
|
-
if (
|
|
1313
|
-
|
|
1659
|
+
if (plan.db === null) {
|
|
1660
|
+
const guess = guessDbImportPath(plan.importPath);
|
|
1661
|
+
lines.push(`import { db } from "${guess}"; // TODO(clivly): verify this path points at your Drizzle \`db\` instance — NOT your schema file`);
|
|
1662
|
+
} else if (!dbIsInSchemaModule(plan)) lines.push(`import { ${plan.db.moduleKey} } from "${plan.db.importPath}";`);
|
|
1314
1663
|
return lines.join("\n");
|
|
1315
1664
|
}
|
|
1316
1665
|
function renderTodoHeader(todos) {
|
|
@@ -1428,6 +1777,83 @@ function renderAuthWiring(auth, authInstance = null) {
|
|
|
1428
1777
|
}
|
|
1429
1778
|
}
|
|
1430
1779
|
//#endregion
|
|
1780
|
+
//#region src/tsconfig-alias.ts
|
|
1781
|
+
const LEADING_DOT_SLASH$1 = /^\.\//;
|
|
1782
|
+
const TRAILING_WILDCARD = /\/?\*$/;
|
|
1783
|
+
const TRAILING_SLASH = /\/$/;
|
|
1784
|
+
const BLOCK_COMMENT = /\/\*[\s\S]*?\*\//g;
|
|
1785
|
+
const LINE_COMMENT = /(^|[^:])\/\/.*$/gm;
|
|
1786
|
+
const TRAILING_COMMA = /,(\s*[}\]])/g;
|
|
1787
|
+
/**
|
|
1788
|
+
* `compilerOptions` from a tsconfig's text, or null when it cannot be read.
|
|
1789
|
+
*
|
|
1790
|
+
* tsconfig is JSONC — comments and trailing commas are legal and common, and
|
|
1791
|
+
* `JSON.parse` rejects both. Stripping them is enough here: this only ever reads
|
|
1792
|
+
* two string-valued fields, so the cost of being wrong is falling back to a
|
|
1793
|
+
* relative import, which already works.
|
|
1794
|
+
*/
|
|
1795
|
+
function parseTsconfig(source) {
|
|
1796
|
+
try {
|
|
1797
|
+
const stripped = source.replace(BLOCK_COMMENT, "").replace(LINE_COMMENT, "$1").replace(TRAILING_COMMA, "$1");
|
|
1798
|
+
return JSON.parse(stripped).compilerOptions ?? null;
|
|
1799
|
+
} catch {
|
|
1800
|
+
return null;
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
/**
|
|
1804
|
+
* Strip a leading "./" and any trailing wildcard so two paths can be compared.
|
|
1805
|
+
*
|
|
1806
|
+
* `"./*"` — an alias rooted at the app itself — must reduce to the empty string,
|
|
1807
|
+
* not to a stray `"*"`; that is the mapping which makes a root-level
|
|
1808
|
+
* clivly.config alias-reachable.
|
|
1809
|
+
*/
|
|
1810
|
+
function normalize(value) {
|
|
1811
|
+
return value.replace(LEADING_DOT_SLASH$1, "").replace(TRAILING_WILDCARD, "").replace(TRAILING_SLASH, "");
|
|
1812
|
+
}
|
|
1813
|
+
/**
|
|
1814
|
+
* The alias specifier that reaches `target`, or null when none does.
|
|
1815
|
+
*
|
|
1816
|
+
* `target` is app-root-relative and extensionless, e.g. `lib/auth` or
|
|
1817
|
+
* `clivly.config`. Only wildcard patterns are considered — an exact mapping
|
|
1818
|
+
* names one module and is not a prefix anything else can be rebased onto.
|
|
1819
|
+
*
|
|
1820
|
+
* Longest prefix wins, so `"@components/*": ["./src/components/*"]` beats
|
|
1821
|
+
* `"@/*": ["./src/*"]` for a module under `src/components`, matching how
|
|
1822
|
+
* TypeScript itself resolves.
|
|
1823
|
+
*/
|
|
1824
|
+
function aliasFor(input) {
|
|
1825
|
+
if (!input.paths) return null;
|
|
1826
|
+
const target = normalize(input.target);
|
|
1827
|
+
let best = null;
|
|
1828
|
+
for (const [pattern, targets] of Object.entries(input.paths)) {
|
|
1829
|
+
if (!pattern.endsWith("/*")) continue;
|
|
1830
|
+
const prefix = pattern.slice(0, -2);
|
|
1831
|
+
for (const mapped of targets) {
|
|
1832
|
+
const base = baseReaching(mapped, target);
|
|
1833
|
+
if (base === null) continue;
|
|
1834
|
+
const rest = base === "" ? target : target.slice(base.length + 1);
|
|
1835
|
+
if (!best || base.length > best.length) best = {
|
|
1836
|
+
alias: `${prefix}/${rest}`,
|
|
1837
|
+
length: base.length
|
|
1838
|
+
};
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
return best?.alias ?? null;
|
|
1842
|
+
}
|
|
1843
|
+
/**
|
|
1844
|
+
* The normalized base of `mapped` when it contains `target`, else null.
|
|
1845
|
+
*
|
|
1846
|
+
* A prefix must end at a segment boundary — `src` must not match `srcinternal`,
|
|
1847
|
+
* a different directory — and the target must be strictly inside the base, since
|
|
1848
|
+
* a wildcard needs a remainder to substitute.
|
|
1849
|
+
*/
|
|
1850
|
+
function baseReaching(mapped, target) {
|
|
1851
|
+
if (!mapped.endsWith("/*")) return null;
|
|
1852
|
+
const base = normalize(mapped);
|
|
1853
|
+
if (base === "") return target === "" ? null : "";
|
|
1854
|
+
return target.startsWith(`${base}/`) ? base : null;
|
|
1855
|
+
}
|
|
1856
|
+
//#endregion
|
|
1431
1857
|
//#region src/scaffold.ts
|
|
1432
1858
|
const TANSTACK_ROUTE_PREFIX = /^src\/routes\//;
|
|
1433
1859
|
const TS_EXTENSION = /\.ts$/;
|
|
@@ -1459,10 +1885,14 @@ const ROUTE_PATHS = {
|
|
|
1459
1885
|
},
|
|
1460
1886
|
unknown: null
|
|
1461
1887
|
};
|
|
1462
|
-
function
|
|
1888
|
+
function applyLayout(framework, path, layout) {
|
|
1889
|
+
if (framework !== "nextjs" || layout === "app") return path;
|
|
1890
|
+
return `src/${path}`;
|
|
1891
|
+
}
|
|
1892
|
+
function routePath(framework, kind, layout = "app") {
|
|
1463
1893
|
const paths = ROUTE_PATHS[framework];
|
|
1464
1894
|
if (!paths) throw new Error(`No route path for framework: ${framework}`);
|
|
1465
|
-
return paths[kind];
|
|
1895
|
+
return applyLayout(framework, paths[kind], layout);
|
|
1466
1896
|
}
|
|
1467
1897
|
const WINDOWS_SEP = /\\/g;
|
|
1468
1898
|
const LEADING_DOT_SLASH = /^\.\//;
|
|
@@ -1470,22 +1900,27 @@ function configImport(routeFilePath) {
|
|
|
1470
1900
|
const rel = relative(dirname(routeFilePath), "clivly.config").replace(WINDOWS_SEP, "/");
|
|
1471
1901
|
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
1472
1902
|
}
|
|
1473
|
-
function hostImportPath(routeFilePath, appRelative) {
|
|
1903
|
+
function hostImportPath(routeFilePath, appRelative, paths) {
|
|
1474
1904
|
const fromRoot = appRelative.replace(LEADING_DOT_SLASH, "");
|
|
1905
|
+
const alias = aliasFor({
|
|
1906
|
+
paths,
|
|
1907
|
+
target: fromRoot
|
|
1908
|
+
});
|
|
1909
|
+
if (alias) return alias;
|
|
1475
1910
|
const rel = relative(dirname(routeFilePath), fromRoot).replace(WINDOWS_SEP, "/");
|
|
1476
1911
|
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
1477
1912
|
}
|
|
1478
|
-
function renderAuthPreamble(routeFilePath, auth) {
|
|
1913
|
+
function renderAuthPreamble(routeFilePath, auth, paths) {
|
|
1479
1914
|
const lines = [...auth.imports];
|
|
1480
1915
|
if (auth.hostImport) {
|
|
1481
1916
|
if (auth.hostImport.todo) lines.push(`// ${auth.hostImport.todo}`);
|
|
1482
|
-
const path = hostImportPath(routeFilePath, auth.hostImport.path);
|
|
1917
|
+
const path = hostImportPath(routeFilePath, auth.hostImport.path, paths);
|
|
1483
1918
|
lines.push(`import { ${auth.hostImport.binding} } from "${path}";`);
|
|
1484
1919
|
}
|
|
1485
1920
|
lines.push("", auth.body);
|
|
1486
1921
|
return lines.join("\n");
|
|
1487
1922
|
}
|
|
1488
|
-
function renderPreamble(kind, importPath, auth, routeFilePath) {
|
|
1923
|
+
function renderPreamble(kind, importPath, auth, paths, routeFilePath) {
|
|
1489
1924
|
if (kind === "session") return `import { createChatSessionHandler } from "clivly/sdk";
|
|
1490
1925
|
|
|
1491
1926
|
const handler = createChatSessionHandler({
|
|
@@ -1496,7 +1931,7 @@ const handler = createChatSessionHandler({
|
|
|
1496
1931
|
});
|
|
1497
1932
|
`;
|
|
1498
1933
|
if (kind === "verify") return `import clivly from "${importPath}";
|
|
1499
|
-
${renderAuthPreamble(routeFilePath, auth)}
|
|
1934
|
+
${renderAuthPreamble(routeFilePath, auth, paths)}
|
|
1500
1935
|
const handler = clivly.createAuthVerifyHandler(resolveUser);
|
|
1501
1936
|
`;
|
|
1502
1937
|
return `import clivly from "${importPath}";
|
|
@@ -1504,8 +1939,8 @@ const handler = clivly.createAuthVerifyHandler(resolveUser);
|
|
|
1504
1939
|
const handler = clivly.createClivlyHandler();
|
|
1505
1940
|
`;
|
|
1506
1941
|
}
|
|
1507
|
-
function renderBody(framework, importPath, kind, auth, routeFilePath) {
|
|
1508
|
-
const preamble = renderPreamble(kind, importPath, auth, routeFilePath);
|
|
1942
|
+
function renderBody(framework, importPath, kind, auth, routeFilePath, paths) {
|
|
1943
|
+
const preamble = renderPreamble(kind, importPath, auth, paths, routeFilePath);
|
|
1509
1944
|
switch (framework) {
|
|
1510
1945
|
case "nextjs": return `${preamble}
|
|
1511
1946
|
export const POST = (request: Request) => handler(request);
|
|
@@ -1535,9 +1970,9 @@ export default defineEventHandler((event) => handler(toWebRequest(event)));
|
|
|
1535
1970
|
default: throw new Error(`No route template for framework: ${framework}`);
|
|
1536
1971
|
}
|
|
1537
1972
|
}
|
|
1538
|
-
function renderRouteFile(framework, kind, auth = renderAuthWiring("unknown")) {
|
|
1539
|
-
const path = routePath(framework, kind);
|
|
1540
|
-
let body = renderBody(framework, configImport(path), kind, auth, path);
|
|
1973
|
+
function renderRouteFile(framework, kind, auth = renderAuthWiring("unknown"), layout = "app", paths) {
|
|
1974
|
+
const path = routePath(framework, kind, layout);
|
|
1975
|
+
let body = renderBody(framework, configImport(path), kind, auth, path, paths);
|
|
1541
1976
|
if (framework === "tanstack-start") {
|
|
1542
1977
|
const url = `/${path.replace(TANSTACK_ROUTE_PREFIX, "").replace(TS_EXTENSION, "")}`;
|
|
1543
1978
|
body = body.replace("__ROUTE__", url);
|
|
@@ -1549,28 +1984,28 @@ const COMMON_FILES = [{
|
|
|
1549
1984
|
description: "Your Clivly configuration",
|
|
1550
1985
|
owned: false
|
|
1551
1986
|
}];
|
|
1552
|
-
function planScaffold(framework) {
|
|
1987
|
+
function planScaffold(framework, layout = "app") {
|
|
1553
1988
|
const paths = ROUTE_PATHS[framework];
|
|
1554
1989
|
if (!paths) return [];
|
|
1555
1990
|
return [
|
|
1556
1991
|
{
|
|
1557
|
-
path: paths.tick,
|
|
1992
|
+
path: applyLayout(framework, paths.tick, layout),
|
|
1558
1993
|
description: "Clivly sync-trigger route (createClivlyHandler)",
|
|
1559
1994
|
owned: true
|
|
1560
1995
|
},
|
|
1561
1996
|
{
|
|
1562
|
-
path: paths.verify,
|
|
1997
|
+
path: applyLayout(framework, paths.verify, layout),
|
|
1563
1998
|
description: "Clivly auth-verify route (createAuthVerifyHandler) — finish resolveUser",
|
|
1564
1999
|
owned: true
|
|
1565
2000
|
},
|
|
1566
2001
|
...COMMON_FILES
|
|
1567
2002
|
];
|
|
1568
2003
|
}
|
|
1569
|
-
function planWidgetScaffold(framework) {
|
|
2004
|
+
function planWidgetScaffold(framework, layout = "app") {
|
|
1570
2005
|
const paths = ROUTE_PATHS[framework];
|
|
1571
2006
|
if (!paths) return [];
|
|
1572
2007
|
return [{
|
|
1573
|
-
path: paths.session,
|
|
2008
|
+
path: applyLayout(framework, paths.session, layout),
|
|
1574
2009
|
description: "Clivly chat-session route (createChatSessionHandler) — add allowedOrigins",
|
|
1575
2010
|
owned: true
|
|
1576
2011
|
}];
|
|
@@ -1590,9 +2025,9 @@ function planFiles(args) {
|
|
|
1590
2025
|
const render = (path) => {
|
|
1591
2026
|
if (path === "clivly.config.ts") return renderInitConfig(args.plan);
|
|
1592
2027
|
const kind = path.includes("verify") ? "verify" : "tick";
|
|
1593
|
-
return renderRouteFile(args.framework, kind, args.authWiring);
|
|
2028
|
+
return renderRouteFile(args.framework, kind, args.authWiring, args.layout, parseTsconfig(args.readFile(join(args.cwd, "tsconfig.json")) ?? "")?.paths);
|
|
1594
2029
|
};
|
|
1595
|
-
for (const file of planScaffold(args.framework)) {
|
|
2030
|
+
for (const file of planScaffold(args.framework, args.layout)) {
|
|
1596
2031
|
const contents = render(file.path);
|
|
1597
2032
|
mutations.push({
|
|
1598
2033
|
path: file.path,
|
|
@@ -1623,8 +2058,8 @@ function planMutations(args) {
|
|
|
1623
2058
|
};
|
|
1624
2059
|
}
|
|
1625
2060
|
function planWidgetMutations(args) {
|
|
1626
|
-
return planWidgetScaffold(args.framework).map((file) => {
|
|
1627
|
-
const contents = renderRouteFile(args.framework, "session");
|
|
2061
|
+
return planWidgetScaffold(args.framework, args.layout).map((file) => {
|
|
2062
|
+
const contents = renderRouteFile(args.framework, "session", void 0, args.layout);
|
|
1628
2063
|
return {
|
|
1629
2064
|
path: file.path,
|
|
1630
2065
|
contents,
|
|
@@ -1949,7 +2384,17 @@ const ALLOWED_CALLS = /* @__PURE__ */ new Set([
|
|
|
1949
2384
|
"while"
|
|
1950
2385
|
]);
|
|
1951
2386
|
const SIDE_EFFECT_CALLS = /^(dotenv\.config|config|configDotenv|fileURLToPath|readFileSync|require|process\.chdir)$/;
|
|
2387
|
+
const NATIVE_PACKAGES = /* @__PURE__ */ new Set([
|
|
2388
|
+
"bcrypt",
|
|
2389
|
+
"better-sqlite3",
|
|
2390
|
+
"canvas",
|
|
2391
|
+
"node-gyp",
|
|
2392
|
+
"pg-native",
|
|
2393
|
+
"sharp",
|
|
2394
|
+
"sqlite3"
|
|
2395
|
+
]);
|
|
1952
2396
|
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.";
|
|
2397
|
+
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
2398
|
function isNodeBuiltin(specifier) {
|
|
1954
2399
|
if (specifier.startsWith("node:")) return true;
|
|
1955
2400
|
return NODE_BUILTINS.has(specifier.split("/")[0] ?? "");
|
|
@@ -1966,6 +2411,12 @@ function specifierIssue(specifier, line) {
|
|
|
1966
2411
|
hint: ENV_HINT,
|
|
1967
2412
|
line
|
|
1968
2413
|
};
|
|
2414
|
+
if (NATIVE_PACKAGES.has(specifier.split("/")[0] ?? "")) return {
|
|
2415
|
+
code: "native_module_in_edge_config",
|
|
2416
|
+
detail: `imports "${specifier}", which ships a compiled binary`,
|
|
2417
|
+
hint: NATIVE_HINT,
|
|
2418
|
+
line
|
|
2419
|
+
};
|
|
1969
2420
|
if (isNodeBuiltin(specifier)) return {
|
|
1970
2421
|
code: "node_builtin_in_edge_config",
|
|
1971
2422
|
detail: `imports "${specifier}", which does not exist on an edge runtime`,
|
|
@@ -2005,8 +2456,56 @@ function analyzeEdgeSafety(source) {
|
|
|
2005
2456
|
});
|
|
2006
2457
|
return issues;
|
|
2007
2458
|
}
|
|
2459
|
+
/** Every relative specifier `source` imports, in first-seen order, deduped. */
|
|
2460
|
+
function relativeImports(source) {
|
|
2461
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2462
|
+
for (const rawLine of source.split(NEWLINE)) {
|
|
2463
|
+
const line = stripComment(rawLine);
|
|
2464
|
+
const specifier = BARE_IMPORT.exec(line)?.[1] ?? IMPORT_FROM.exec(line)?.[1] ?? REQUIRE_CALL.exec(line)?.[1];
|
|
2465
|
+
if (specifier?.startsWith(".")) seen.add(specifier);
|
|
2466
|
+
}
|
|
2467
|
+
return [...seen];
|
|
2468
|
+
}
|
|
2469
|
+
/**
|
|
2470
|
+
* Edge-safety for the config *and* the modules it imports directly.
|
|
2471
|
+
*
|
|
2472
|
+
* The dominant real-world shape is a clean-looking config with
|
|
2473
|
+
* `import { db } from "./lib/db"`, where the problem is one hop away and
|
|
2474
|
+
* invisible to a scan that reads only the config file.
|
|
2475
|
+
*
|
|
2476
|
+
* One hop, not more: each additional level multiplies the files read for a
|
|
2477
|
+
* shrinking return, and the config's own imports are where a host app puts its
|
|
2478
|
+
* database. Bare specifiers are never followed — resolving into node_modules is
|
|
2479
|
+
* a different job with different failure modes, and the denylist already covers
|
|
2480
|
+
* the packages that matter.
|
|
2481
|
+
*
|
|
2482
|
+
* `readModule` returns source text, or null when the module cannot be read;
|
|
2483
|
+
* unreadable is not a finding, since a scan is not a build.
|
|
2484
|
+
*/
|
|
2485
|
+
function analyzeConfigTree(input) {
|
|
2486
|
+
const issues = analyzeEdgeSafety(input.source);
|
|
2487
|
+
for (const specifier of relativeImports(input.source)) {
|
|
2488
|
+
const source = input.readModule(specifier);
|
|
2489
|
+
if (source === null) continue;
|
|
2490
|
+
for (const issue of analyzeEdgeSafety(source)) issues.push({
|
|
2491
|
+
...issue,
|
|
2492
|
+
module: specifier
|
|
2493
|
+
});
|
|
2494
|
+
}
|
|
2495
|
+
return issues;
|
|
2496
|
+
}
|
|
2008
2497
|
//#endregion
|
|
2009
2498
|
//#region src/status-stages.ts
|
|
2499
|
+
const MODULE_CANDIDATES = [
|
|
2500
|
+
".ts",
|
|
2501
|
+
".tsx",
|
|
2502
|
+
".js",
|
|
2503
|
+
".mjs",
|
|
2504
|
+
".cjs",
|
|
2505
|
+
"/index.ts",
|
|
2506
|
+
"/index.js",
|
|
2507
|
+
""
|
|
2508
|
+
];
|
|
2010
2509
|
function defaultReadConfigSource(path) {
|
|
2011
2510
|
try {
|
|
2012
2511
|
return readFileSync(path, "utf8");
|
|
@@ -2021,10 +2520,11 @@ const REASON_HINT = {
|
|
|
2021
2520
|
rate_limited: "Rate limited (429). Wait a moment and retry.",
|
|
2022
2521
|
server_error: "Clivly returned a server error (5xx). Retry shortly.",
|
|
2023
2522
|
client_error: "The request was rejected (4xx). Check your configuration.",
|
|
2523
|
+
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
2524
|
network_error: "Could not reach Clivly. Check your network or --api-url."
|
|
2025
2525
|
};
|
|
2026
2526
|
const apiKeyStage = {
|
|
2027
|
-
id: "
|
|
2527
|
+
id: "credential",
|
|
2028
2528
|
label: "API key present",
|
|
2029
2529
|
run(ctx) {
|
|
2030
2530
|
if (ctx.apiKey) return Promise.resolve({
|
|
@@ -2034,20 +2534,29 @@ const apiKeyStage = {
|
|
|
2034
2534
|
return Promise.resolve({
|
|
2035
2535
|
state: "fail",
|
|
2036
2536
|
detail: "Secret key is not set.",
|
|
2037
|
-
hint:
|
|
2537
|
+
hint: `Copy your secret key from ${CREDENTIALS_LOCATION} into CLIVLY_SECRET_KEY in .env.`
|
|
2038
2538
|
});
|
|
2039
2539
|
}
|
|
2040
2540
|
};
|
|
2041
|
-
const
|
|
2042
|
-
id: "
|
|
2541
|
+
const reachabilityStage = {
|
|
2542
|
+
id: "application",
|
|
2043
2543
|
label: "Clivly reachable",
|
|
2044
2544
|
needs: [apiKeyStage.id],
|
|
2045
2545
|
async run(ctx) {
|
|
2046
2546
|
const result = await ctx.connect(ctx.apiKey, ctx.apiUrl);
|
|
2047
|
-
if (result.ok)
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2547
|
+
if (result.ok) {
|
|
2548
|
+
const name = result.org?.name ?? "(unnamed org)";
|
|
2549
|
+
const id = result.org?.id ? ` (${result.org.id})` : "";
|
|
2550
|
+
if (result.appLastSeenAt === null) return {
|
|
2551
|
+
state: "warn",
|
|
2552
|
+
detail: `Reached org: ${name}${id} — your app has not connected yet`,
|
|
2553
|
+
hint: "Start your app with the Clivly SDK mounted; it will appear in the dashboard within a minute."
|
|
2554
|
+
};
|
|
2555
|
+
return {
|
|
2556
|
+
state: "pass",
|
|
2557
|
+
detail: `Reached org: ${name}${id}`
|
|
2558
|
+
};
|
|
2559
|
+
}
|
|
2051
2560
|
const status = result.status === null ? "no response" : `HTTP ${result.status}`;
|
|
2052
2561
|
return {
|
|
2053
2562
|
state: "fail",
|
|
@@ -2075,22 +2584,76 @@ const configStage = {
|
|
|
2075
2584
|
}
|
|
2076
2585
|
}
|
|
2077
2586
|
};
|
|
2078
|
-
const LADDER_OWNED_CHECKS = /* @__PURE__ */ new Set(["API key present", "
|
|
2587
|
+
const LADDER_OWNED_CHECKS = /* @__PURE__ */ new Set(["API key present", "Clivly reachable"]);
|
|
2588
|
+
const sdkChecksStage = {
|
|
2589
|
+
id: "setup-checks",
|
|
2590
|
+
label: "Setup checks",
|
|
2591
|
+
needs: [configStage.id],
|
|
2592
|
+
async run(ctx) {
|
|
2593
|
+
const owned = (await ctx.sdk.doctor()).checks.filter((check) => !LADDER_OWNED_CHECKS.has(check.name));
|
|
2594
|
+
const counted = owned.filter((check) => !check.skipped);
|
|
2595
|
+
const passed = counted.filter((check) => check.ok).length;
|
|
2596
|
+
const ok = counted.every((check) => check.ok);
|
|
2597
|
+
const warned = counted.filter((check) => check.warn).length;
|
|
2598
|
+
const summary = warned > 0 ? `${passed} of ${counted.length} passed, ${warned} with warnings` : `${passed} of ${counted.length} passed`;
|
|
2599
|
+
return {
|
|
2600
|
+
state: ok ? "pass" : "fail",
|
|
2601
|
+
detail: summary,
|
|
2602
|
+
sub: owned.map((check) => ({
|
|
2603
|
+
label: check.name,
|
|
2604
|
+
ok: check.ok,
|
|
2605
|
+
skipped: check.skipped,
|
|
2606
|
+
warn: check.warn,
|
|
2607
|
+
detail: check.detail
|
|
2608
|
+
}))
|
|
2609
|
+
};
|
|
2610
|
+
}
|
|
2611
|
+
};
|
|
2612
|
+
const triggerUrlStage = {
|
|
2613
|
+
id: "trigger-url",
|
|
2614
|
+
label: "Sync trigger URL",
|
|
2615
|
+
needs: [configStage.id],
|
|
2616
|
+
run(ctx) {
|
|
2617
|
+
const url = ctx.sdk?.syncTrigger?.url;
|
|
2618
|
+
if (url) return Promise.resolve({
|
|
2619
|
+
state: "pass",
|
|
2620
|
+
detail: url
|
|
2621
|
+
});
|
|
2622
|
+
return Promise.resolve({
|
|
2623
|
+
state: "warn",
|
|
2624
|
+
detail: "Not set — remote sync cannot call back into this app.",
|
|
2625
|
+
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."
|
|
2626
|
+
});
|
|
2627
|
+
}
|
|
2628
|
+
};
|
|
2079
2629
|
/** The full ladder, in the order a developer completes setup. */
|
|
2080
2630
|
const STATUS_STAGES = [
|
|
2081
2631
|
apiKeyStage,
|
|
2082
|
-
|
|
2632
|
+
reachabilityStage,
|
|
2083
2633
|
configStage,
|
|
2084
2634
|
{
|
|
2085
2635
|
id: "runtime",
|
|
2086
2636
|
label: "clivly.config is edge-safe",
|
|
2637
|
+
needs: [configStage.id],
|
|
2087
2638
|
run(ctx) {
|
|
2088
2639
|
const source = (ctx.readConfigSource ?? defaultReadConfigSource)(ctx.configPath);
|
|
2089
2640
|
if (source === null) return Promise.resolve({
|
|
2090
2641
|
state: "skip",
|
|
2091
2642
|
detail: "config not readable"
|
|
2092
2643
|
});
|
|
2093
|
-
const
|
|
2644
|
+
const read = ctx.readConfigSource ?? defaultReadConfigSource;
|
|
2645
|
+
const base = dirname(ctx.configPath);
|
|
2646
|
+
const issues = analyzeConfigTree({
|
|
2647
|
+
source,
|
|
2648
|
+
readModule: (specifier) => {
|
|
2649
|
+
const target = resolve(base, specifier);
|
|
2650
|
+
for (const candidate of MODULE_CANDIDATES) {
|
|
2651
|
+
const found = read(`${target}${candidate}`);
|
|
2652
|
+
if (found !== null) return found;
|
|
2653
|
+
}
|
|
2654
|
+
return null;
|
|
2655
|
+
}
|
|
2656
|
+
});
|
|
2094
2657
|
if (issues.length === 0) return Promise.resolve({
|
|
2095
2658
|
state: "pass",
|
|
2096
2659
|
detail: "no Node-only code at module scope"
|
|
@@ -2107,43 +2670,8 @@ const STATUS_STAGES = [
|
|
|
2107
2670
|
});
|
|
2108
2671
|
}
|
|
2109
2672
|
},
|
|
2110
|
-
|
|
2111
|
-
|
|
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
|
-
}
|
|
2673
|
+
sdkChecksStage,
|
|
2674
|
+
triggerUrlStage
|
|
2147
2675
|
];
|
|
2148
2676
|
function defaultLoadSdk(path) {
|
|
2149
2677
|
return loadConfigSdk(path, "doctor");
|
|
@@ -2153,15 +2681,15 @@ function defaultLoadSdk(path) {
|
|
|
2153
2681
|
/** Stage ids each legacy command maps onto. */
|
|
2154
2682
|
const ALIAS_STAGE_IDS = {
|
|
2155
2683
|
status: STATUS_STAGES.map((stage) => stage.id),
|
|
2156
|
-
ping: ["
|
|
2684
|
+
ping: ["credential", "application"],
|
|
2157
2685
|
doctor: [
|
|
2158
2686
|
"config",
|
|
2159
2687
|
"runtime",
|
|
2160
2688
|
"setup-checks"
|
|
2161
2689
|
],
|
|
2162
2690
|
connect: [
|
|
2163
|
-
"
|
|
2164
|
-
"
|
|
2691
|
+
"credential",
|
|
2692
|
+
"application",
|
|
2165
2693
|
"config",
|
|
2166
2694
|
"trigger-url"
|
|
2167
2695
|
]
|
|
@@ -2177,9 +2705,9 @@ const defaultConnect = (apiKey, apiUrl) => createClivlySDK({
|
|
|
2177
2705
|
apiKey,
|
|
2178
2706
|
apiUrl,
|
|
2179
2707
|
retry: { maxAttempts: 1 }
|
|
2180
|
-
}).
|
|
2708
|
+
}).ping();
|
|
2181
2709
|
function subMark(sub) {
|
|
2182
|
-
if (sub.skipped) return "⚠️ ";
|
|
2710
|
+
if (sub.skipped || sub.warn) return "⚠️ ";
|
|
2183
2711
|
return sub.ok ? "✅" : "❌";
|
|
2184
2712
|
}
|
|
2185
2713
|
function renderStage(result, verbose, out) {
|
|
@@ -2187,7 +2715,7 @@ function renderStage(result, verbose, out) {
|
|
|
2187
2715
|
const detail = result.detail ? ` — ${result.detail}` : "";
|
|
2188
2716
|
out(` ${MARK[result.state]} ${step} · ${result.label}${detail}\n`);
|
|
2189
2717
|
for (const sub of result.sub ?? []) {
|
|
2190
|
-
if (!(verbose || sub.skipped || !sub.ok)) continue;
|
|
2718
|
+
if (!(verbose || sub.skipped || sub.warn || !sub.ok)) continue;
|
|
2191
2719
|
const subDetail = sub.detail ? ` — ${sub.detail}` : "";
|
|
2192
2720
|
out(` ${subMark(sub)} ${sub.label}${subDetail}\n`);
|
|
2193
2721
|
}
|
|
@@ -2213,6 +2741,12 @@ async function runStatus(options) {
|
|
|
2213
2741
|
}
|
|
2214
2742
|
//#endregion
|
|
2215
2743
|
//#region src/index.ts
|
|
2744
|
+
const ENV_FILE_CANDIDATES = [
|
|
2745
|
+
".env",
|
|
2746
|
+
".env.local",
|
|
2747
|
+
".dev.vars"
|
|
2748
|
+
];
|
|
2749
|
+
const CONFIG_WATCH_DEBOUNCE_MS = 150;
|
|
2216
2750
|
function flagValue(argv, flag) {
|
|
2217
2751
|
const index = argv.indexOf(flag);
|
|
2218
2752
|
return index >= 0 ? argv[index + 1] : void 0;
|
|
@@ -2231,7 +2765,10 @@ const KNOWN_COMMANDS = [
|
|
|
2231
2765
|
"push-schema",
|
|
2232
2766
|
"dev",
|
|
2233
2767
|
"login",
|
|
2234
|
-
"help"
|
|
2768
|
+
"help",
|
|
2769
|
+
"ping",
|
|
2770
|
+
"doctor",
|
|
2771
|
+
"connect"
|
|
2235
2772
|
];
|
|
2236
2773
|
function editDistance(a, b) {
|
|
2237
2774
|
const m = a.length;
|
|
@@ -2274,6 +2811,7 @@ function readDeps(cwd) {
|
|
|
2274
2811
|
}
|
|
2275
2812
|
const ADD_USAGE = "Usage: clivly add widget [--force] [--dry-run]";
|
|
2276
2813
|
const defaultAddDeps = {
|
|
2814
|
+
fileExists: existsSync,
|
|
2277
2815
|
out: (line) => process.stdout.write(line),
|
|
2278
2816
|
readFile: (path) => existsSync(path) ? readFileSync(path, "utf8") : null,
|
|
2279
2817
|
writeFile: (path, contents) => {
|
|
@@ -2293,14 +2831,21 @@ function runAdd(argv, cwd, deps = defaultAddDeps) {
|
|
|
2293
2831
|
deps.out("Couldn't detect your framework from package.json. `clivly add widget` supports Next.js, TanStack Start, SvelteKit, Remix, and Nuxt.\n");
|
|
2294
2832
|
return 1;
|
|
2295
2833
|
}
|
|
2834
|
+
const layout = resolveAppLayout(cwd, deps.fileExists);
|
|
2296
2835
|
const force = argv.includes("--force");
|
|
2297
2836
|
const dryRun = argv.includes("--dry-run");
|
|
2298
2837
|
const files = planWidgetMutations({
|
|
2299
2838
|
framework,
|
|
2300
2839
|
cwd,
|
|
2301
2840
|
force,
|
|
2841
|
+
layout,
|
|
2302
2842
|
readFile: (path) => deps.readFile(path)
|
|
2303
2843
|
});
|
|
2844
|
+
const shadowing = shadowedAppDirError(cwd, framework, files.map((file) => file.path), deps.fileExists);
|
|
2845
|
+
if (shadowing) {
|
|
2846
|
+
deps.out(shadowing);
|
|
2847
|
+
return 1;
|
|
2848
|
+
}
|
|
2304
2849
|
deps.out(`\nClivly add widget — ${FRAMEWORK_LABELS[framework]}\n\n`);
|
|
2305
2850
|
if (dryRun) deps.out("Dry run — nothing was written.\n\n");
|
|
2306
2851
|
for (const file of files) {
|
|
@@ -2321,7 +2866,7 @@ function runAdd(argv, cwd, deps = defaultAddDeps) {
|
|
|
2321
2866
|
}
|
|
2322
2867
|
if (!dryRun) {
|
|
2323
2868
|
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
|
|
2869
|
+
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
2870
|
}
|
|
2326
2871
|
return 0;
|
|
2327
2872
|
}
|
|
@@ -2332,6 +2877,13 @@ function readOwnVersion() {
|
|
|
2332
2877
|
if (pkg.name === "clivly" && pkg.version) return pkg.version;
|
|
2333
2878
|
} catch {}
|
|
2334
2879
|
}
|
|
2880
|
+
function readOwnEngines() {
|
|
2881
|
+
const req = createRequire(import.meta.url);
|
|
2882
|
+
for (const rel of ["./package.json", "../package.json"]) try {
|
|
2883
|
+
const pkg = req(rel);
|
|
2884
|
+
if (pkg.name === "clivly") return pkg.engines?.node;
|
|
2885
|
+
} catch {}
|
|
2886
|
+
}
|
|
2335
2887
|
/**
|
|
2336
2888
|
* Parse a `--db-import` / `--auth-import` value into a discovery-shaped override.
|
|
2337
2889
|
*
|
|
@@ -2361,12 +2913,24 @@ function authInstanceFromFlag(flag) {
|
|
|
2361
2913
|
function defaultReadFile(path) {
|
|
2362
2914
|
return existsSync(path) ? readFileSync(path, "utf8") : null;
|
|
2363
2915
|
}
|
|
2916
|
+
function resolveEnvPath(cwd) {
|
|
2917
|
+
const framework = detectFramework(readDeps(cwd));
|
|
2918
|
+
return join(cwd, resolveEnvFile({
|
|
2919
|
+
existing: ENV_FILE_CANDIDATES.filter((name) => {
|
|
2920
|
+
const path = join(cwd, name);
|
|
2921
|
+
if (!existsSync(path)) return false;
|
|
2922
|
+
const contents = readFileSync(path, "utf8");
|
|
2923
|
+
return isKeySet(contents, "CLIVLY_SECRET_KEY") || isKeySet(contents, "CLIVLY_API_KEY");
|
|
2924
|
+
}),
|
|
2925
|
+
framework
|
|
2926
|
+
}));
|
|
2927
|
+
}
|
|
2364
2928
|
function defaultReadEnv(cwd) {
|
|
2365
|
-
const path =
|
|
2929
|
+
const path = resolveEnvPath(cwd);
|
|
2366
2930
|
return existsSync(path) ? readFileSync(path, "utf8") : "";
|
|
2367
2931
|
}
|
|
2368
2932
|
function defaultWriteEnv(cwd, contents) {
|
|
2369
|
-
writeFileSync(
|
|
2933
|
+
writeFileSync(resolveEnvPath(cwd), contents, "utf8");
|
|
2370
2934
|
}
|
|
2371
2935
|
function defaultIsInteractive() {
|
|
2372
2936
|
return Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY) && !process.env.CI;
|
|
@@ -2393,6 +2957,8 @@ function resolveInitDeps(options) {
|
|
|
2393
2957
|
graph: graphFor(cwd)
|
|
2394
2958
|
})),
|
|
2395
2959
|
readFile: options.readFile ?? defaultReadFile,
|
|
2960
|
+
fileExists: options.fileExists ?? existsSync,
|
|
2961
|
+
resolveAppLayout: options.resolveAppLayout ?? resolveAppLayout,
|
|
2396
2962
|
writeConfig: options.writeConfig ?? ((path, contents) => {
|
|
2397
2963
|
mkdirSync(dirname(path), { recursive: true });
|
|
2398
2964
|
writeFileSync(path, contents, "utf8");
|
|
@@ -2413,6 +2979,7 @@ function resolveInitDeps(options) {
|
|
|
2413
2979
|
rotate: false
|
|
2414
2980
|
})),
|
|
2415
2981
|
framework: "unknown",
|
|
2982
|
+
layout: "app",
|
|
2416
2983
|
authWiring: renderAuthWiring("unknown")
|
|
2417
2984
|
};
|
|
2418
2985
|
}
|
|
@@ -2427,11 +2994,15 @@ async function acquireSchema(options, deps) {
|
|
|
2427
2994
|
const orm = detectOrm(appDeps);
|
|
2428
2995
|
const auth = detectAuth(appDeps);
|
|
2429
2996
|
deps.framework = framework;
|
|
2997
|
+
const layout = deps.resolveAppLayout(options.cwd, deps.fileExists);
|
|
2998
|
+
deps.layout = layout;
|
|
2430
2999
|
deps.authWiring = renderAuthWiring(auth, auth === "better-auth" ? authInstanceFromFlag(options.authImportFlag) ?? await deps.probeAuth(options.cwd) : null);
|
|
2431
3000
|
out("\nClivly init\n");
|
|
2432
3001
|
out(` Framework: ${FRAMEWORK_LABELS[framework]}\n`);
|
|
2433
3002
|
out(` ORM: ${orm}\n`);
|
|
2434
|
-
out(` Auth: ${auth}${deps.authWiring.complete ? " (wired)" : ""}\n
|
|
3003
|
+
out(` Auth: ${auth}${deps.authWiring.complete ? " (wired)" : ""}\n`);
|
|
3004
|
+
if (framework === "nextjs") out(` Layout: ${layout}\n`);
|
|
3005
|
+
out("\n");
|
|
2435
3006
|
if (orm !== "drizzle") {
|
|
2436
3007
|
out(`clivly init currently generates config for Drizzle only. Detected ORM: ${orm}\n`);
|
|
2437
3008
|
return { code: 1 };
|
|
@@ -2475,6 +3046,7 @@ function mutationsFor(options, deps, plan) {
|
|
|
2475
3046
|
cwd: options.cwd,
|
|
2476
3047
|
force: options.force,
|
|
2477
3048
|
framework: deps.framework,
|
|
3049
|
+
layout: deps.layout,
|
|
2478
3050
|
authWiring: deps.authWiring,
|
|
2479
3051
|
plan,
|
|
2480
3052
|
readFile: deps.readFile,
|
|
@@ -2534,14 +3106,15 @@ function previewMutations(deps, mutations, options) {
|
|
|
2534
3106
|
}
|
|
2535
3107
|
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
3108
|
}
|
|
2537
|
-
function printNextSteps(out, authComplete, loginRan) {
|
|
3109
|
+
function printNextSteps(out, authComplete, loginRan, envFile) {
|
|
2538
3110
|
out("\nNext steps:\n");
|
|
2539
|
-
out(loginRan ? " 1. Credentials written by `clivly login`\n" :
|
|
3111
|
+
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
3112
|
out(" 2. Set CLIVLY_SYNC_TRIGGER_URL to your public tick route\n");
|
|
2541
3113
|
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
3114
|
const step = authComplete ? 3 : 4;
|
|
2543
3115
|
if (!authComplete) out(" 3. Finish resolveUser in the auth/verify route\n");
|
|
2544
3116
|
out(` ${step}. Run \`clivly status\` to see where you are\n`);
|
|
3117
|
+
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
3118
|
}
|
|
2546
3119
|
function credentialsMissing(envContents) {
|
|
2547
3120
|
return !(isKeySet(envContents, "CLIVLY_SECRET_KEY") || isKeySet(envContents, "CLIVLY_API_KEY"));
|
|
@@ -2562,6 +3135,11 @@ async function scaffold(options, deps, plan) {
|
|
|
2562
3135
|
const pm = deps.detectPackageManager(options.cwd);
|
|
2563
3136
|
const packages = [resolveRuntimeInstallSpec(deps), ...deps.authWiring.packages];
|
|
2564
3137
|
const mutations = mutationsFor(options, deps, plan);
|
|
3138
|
+
const shadowing = shadowedAppDirError(options.cwd, deps.framework, mutations.files.map((file) => file.path), deps.fileExists);
|
|
3139
|
+
if (shadowing) {
|
|
3140
|
+
out(shadowing);
|
|
3141
|
+
return 1;
|
|
3142
|
+
}
|
|
2565
3143
|
if (options.dryRun || options.diff) {
|
|
2566
3144
|
out(`\nWould install (${pm}): ${packages.join(", ")}\n`);
|
|
2567
3145
|
previewMutations(deps, mutations, {
|
|
@@ -2586,7 +3164,7 @@ async function scaffold(options, deps, plan) {
|
|
|
2586
3164
|
out(" Run `clivly login` from a terminal to write CLIVLY_SECRET_KEY and CLIVLY_SYNC_TRIGGER_SECRET.\n");
|
|
2587
3165
|
} else loginRan = await deps.login(options.cwd) === 0;
|
|
2588
3166
|
}
|
|
2589
|
-
printNextSteps(out, deps.authWiring.complete, loginRan);
|
|
3167
|
+
printNextSteps(out, deps.authWiring.complete, loginRan, envFileFor(detectFramework(deps.readDepsFn(options.cwd))));
|
|
2590
3168
|
return 0;
|
|
2591
3169
|
}
|
|
2592
3170
|
function normalizeAppRoot(options) {
|
|
@@ -2653,8 +3231,18 @@ function printNoContactGuidance(out, plan, options) {
|
|
|
2653
3231
|
out(`\n Tables in ${plan.importPath}:\n`);
|
|
2654
3232
|
for (const name of plan.tableNames) out(` ${name}\n`);
|
|
2655
3233
|
const schemaArg = options.schemaFlag ? ` --schema ${options.schemaFlag}` : "";
|
|
2656
|
-
|
|
2657
|
-
|
|
3234
|
+
const best = plan.contactCandidates[0];
|
|
3235
|
+
if (best) {
|
|
3236
|
+
out(`\n Best guess: ${best.table} — ${best.reasons.join(", ")}\n`);
|
|
3237
|
+
const runnerUp = plan.contactCandidates.slice(1, 3).map((candidate) => candidate.table);
|
|
3238
|
+
if (runnerUp.length > 0) out(` Also possible: ${runnerUp.join(", ")}\n`);
|
|
3239
|
+
out("\n Confirm it and re-run:\n");
|
|
3240
|
+
out(` clivly init${schemaArg} --contact-table ${best.table}\n\n`);
|
|
3241
|
+
return;
|
|
3242
|
+
}
|
|
3243
|
+
out("\n Nothing here looks like a people table — no email, phone or name\n");
|
|
3244
|
+
out(" columns turned up. Pick the one that holds your people and re-run:\n");
|
|
3245
|
+
out(` clivly init${schemaArg} --contact-table ${plan.tableNames[0] ?? "<table>"}\n\n`);
|
|
2658
3246
|
out(" Nothing was written — Clivly needs one entity before a config can load.\n\n");
|
|
2659
3247
|
}
|
|
2660
3248
|
function hasCloudflaredOnPath() {
|
|
@@ -2750,6 +3338,22 @@ function defaultDevDeps(options) {
|
|
|
2750
3338
|
},
|
|
2751
3339
|
out: (line) => {
|
|
2752
3340
|
process.stdout.write(`${line}\n`);
|
|
3341
|
+
},
|
|
3342
|
+
watchConfig: (cwd, onChange) => {
|
|
3343
|
+
const target = resolveConfigPath(cwd);
|
|
3344
|
+
try {
|
|
3345
|
+
let timer = null;
|
|
3346
|
+
const watcher = watch(target, () => {
|
|
3347
|
+
if (timer) clearTimeout(timer);
|
|
3348
|
+
timer = setTimeout(onChange, CONFIG_WATCH_DEBOUNCE_MS);
|
|
3349
|
+
});
|
|
3350
|
+
return () => {
|
|
3351
|
+
if (timer) clearTimeout(timer);
|
|
3352
|
+
watcher.close();
|
|
3353
|
+
};
|
|
3354
|
+
} catch {
|
|
3355
|
+
return null;
|
|
3356
|
+
}
|
|
2753
3357
|
}
|
|
2754
3358
|
};
|
|
2755
3359
|
}
|
|
@@ -2828,6 +3432,21 @@ function runInitFromArgv(argv, cwd) {
|
|
|
2828
3432
|
}
|
|
2829
3433
|
async function main(argv) {
|
|
2830
3434
|
const [command, ...rest] = argv;
|
|
3435
|
+
if (command === "-h" || command === "--help" || isHelpRequest(rest)) {
|
|
3436
|
+
process.stdout.write(helpFor(command));
|
|
3437
|
+
return 0;
|
|
3438
|
+
}
|
|
3439
|
+
if (command === "--version" || command === "-v") {
|
|
3440
|
+
process.stdout.write(`${readOwnVersion() ?? "unknown"}\n`);
|
|
3441
|
+
return 0;
|
|
3442
|
+
}
|
|
3443
|
+
if (!process.env.CLIVLY_SKIP_ENGINE_CHECK) {
|
|
3444
|
+
const engineProblem = engineError(process.version, readOwnEngines());
|
|
3445
|
+
if (engineProblem) {
|
|
3446
|
+
process.stderr.write(engineProblem);
|
|
3447
|
+
return 1;
|
|
3448
|
+
}
|
|
3449
|
+
}
|
|
2831
3450
|
let cliEnvFiles = [];
|
|
2832
3451
|
try {
|
|
2833
3452
|
cliEnvFiles = (await loadCliConfig(process.cwd()))?.envFiles ?? [];
|
|
@@ -2846,14 +3465,16 @@ async function main(argv) {
|
|
|
2846
3465
|
case "status":
|
|
2847
3466
|
case "ping":
|
|
2848
3467
|
case "doctor":
|
|
2849
|
-
case "connect":
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
|
|
3468
|
+
case "connect":
|
|
3469
|
+
if (command !== "status") process.stderr.write(`\`clivly ${command}\` is a deprecated alias that runs part of \`clivly status\`. Prefer \`clivly status\`.\n`);
|
|
3470
|
+
return await runStatus({
|
|
3471
|
+
cwd: process.cwd(),
|
|
3472
|
+
apiKey: readSecretKeyEnv(process.env),
|
|
3473
|
+
apiUrl: flagValue(rest, "--api-url") ?? process.env.CLIVLY_API_URL,
|
|
3474
|
+
configPath: flagValue(rest, "--config"),
|
|
3475
|
+
only: ALIAS_STAGE_IDS[command],
|
|
3476
|
+
verbose: rest.includes("--verbose")
|
|
3477
|
+
});
|
|
2857
3478
|
case "dev": {
|
|
2858
3479
|
const apiKey = readSecretKeyEnv(process.env);
|
|
2859
3480
|
const apiUrl = flagValue(rest, "--api-url") ?? process.env.CLIVLY_API_URL ?? "https://api.clivly.com";
|
|
@@ -2876,14 +3497,11 @@ async function main(argv) {
|
|
|
2876
3497
|
openBrowser: !rest.includes("--no-browser"),
|
|
2877
3498
|
deps: defaultLoginDeps()
|
|
2878
3499
|
});
|
|
2879
|
-
case "--version":
|
|
2880
|
-
case "-v":
|
|
2881
|
-
process.stdout.write(`${readOwnVersion() ?? "unknown"}\n`);
|
|
2882
|
-
return 0;
|
|
2883
3500
|
case void 0:
|
|
3501
|
+
process.stdout.write(ROOT_HELP);
|
|
3502
|
+
return 0;
|
|
2884
3503
|
case "help":
|
|
2885
|
-
|
|
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");
|
|
3504
|
+
process.stdout.write(helpFor(rest[0]));
|
|
2887
3505
|
return 0;
|
|
2888
3506
|
default: {
|
|
2889
3507
|
process.stdout.write(`Unknown command: ${command}\n`);
|