@rebasepro/cli 0.25.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/bin/rebase.js +143 -4
- package/dist/{agent-setup-B5AKHOgt.js → agent-setup-D9mHRZ5R.js} +125 -3
- package/dist/agent-setup-D9mHRZ5R.js.map +1 -0
- package/dist/{api-keys-Tm7zvAPe.js → api-keys-CyJ26KEJ.js} +41 -10
- package/dist/api-keys-CyJ26KEJ.js.map +1 -0
- package/dist/{apps-BsU_ILbP.js → apps-CnLDV5b6.js} +6 -7
- package/dist/{apps-BsU_ILbP.js.map → apps-CnLDV5b6.js.map} +1 -1
- package/dist/{atlas-dev-database-OWtqnG7W.js → atlas-dev-database-BODqdCWt.js} +4 -4
- package/dist/{atlas-dev-database-OWtqnG7W.js.map → atlas-dev-database-BODqdCWt.js.map} +1 -1
- package/dist/{auth-Vl2hFKXP.js → auth-dII2jCO1.js} +10 -8
- package/dist/auth-dII2jCO1.js.map +1 -0
- package/dist/{branch-pointer-9DnwkFJJ.js → branch-pointer-BQUF6lYa.js} +1 -1
- package/dist/{build-BBgT8EJZ.js → build-Cza7ZQrp.js} +6 -7
- package/dist/{build-BBgT8EJZ.js.map → build-Cza7ZQrp.js.map} +1 -1
- package/dist/{bundle-DtCCCr4w.js → bundle-C6yEtMJ-.js} +53 -5
- package/dist/bundle-C6yEtMJ-.js.map +1 -0
- package/dist/bundle.d.ts +14 -0
- package/dist/{cloud-BpH0_bmV.js → cloud-BdnmqQaZ.js} +8528 -4342
- package/dist/cloud-BdnmqQaZ.js.map +1 -0
- package/dist/collections-dir-DlvDhime.js +69 -0
- package/dist/collections-dir-DlvDhime.js.map +1 -0
- package/dist/commands/agent-setup.d.ts +58 -0
- package/dist/commands/api-keys.d.ts +13 -0
- package/dist/commands/cloud/activity.d.ts +25 -0
- package/dist/commands/cloud/app-key.d.ts +18 -0
- package/dist/commands/cloud/auth.d.ts +1 -0
- package/dist/commands/cloud/billing-invoices.d.ts +39 -0
- package/dist/commands/cloud/claim.d.ts +7 -0
- package/dist/commands/cloud/context.d.ts +115 -6
- package/dist/commands/cloud/deploy-summary.d.ts +162 -0
- package/dist/commands/cloud/deploy.d.ts +64 -0
- package/dist/commands/cloud/env.d.ts +24 -0
- package/dist/commands/cloud/index.d.ts +13 -1
- package/dist/commands/cloud/init.d.ts +143 -0
- package/dist/commands/cloud/login-flow.d.ts +51 -0
- package/dist/commands/cloud/notifications.d.ts +28 -0
- package/dist/commands/cloud/orgs.d.ts +13 -0
- package/dist/commands/cloud/previews.d.ts +123 -0
- package/dist/commands/cloud/resources.d.ts +68 -14
- package/dist/commands/cloud/runtime-logs.d.ts +176 -0
- package/dist/commands/cloud/service-key.d.ts +15 -0
- package/dist/commands/cloud/token-capabilities.d.ts +61 -8
- package/dist/commands/cloud/tokens.d.ts +18 -3
- package/dist/commands/cloud/usage.d.ts +63 -0
- package/dist/commands/dev.d.ts +22 -0
- package/dist/commands/doctor.d.ts +1 -1
- package/dist/commands/generate-view.d.ts +94 -0
- package/dist/commands/generate_sdk.d.ts +19 -2
- package/dist/commands/init.d.ts +20 -0
- package/dist/commands/skills.d.ts +4 -3
- package/dist/commands/start.d.ts +10 -0
- package/dist/commands/storage.d.ts +4 -0
- package/dist/commands/upgrade.d.ts +12 -0
- package/dist/commands/verify.d.ts +96 -0
- package/dist/{consent-ClRHmcxf.js → consent-BD7F29T3.js} +2 -2
- package/dist/{consent-ClRHmcxf.js.map → consent-BD7F29T3.js.map} +1 -1
- package/dist/{console-CEGm0XNc.js → console-BXB6-8GT.js} +12 -6
- package/dist/console-BXB6-8GT.js.map +1 -0
- package/dist/{context-CyflUrKg.js → context-GUxkZm-S.js} +482 -26
- package/dist/context-GUxkZm-S.js.map +1 -0
- package/dist/{daemon-CknkDjd6.js → daemon-Cp7oNXth.js} +160 -5
- package/dist/daemon-Cp7oNXth.js.map +1 -0
- package/dist/{daemon-entry-CbLRrgzy.js → daemon-entry-zOC1revO.js} +6 -3
- package/dist/daemon-entry-zOC1revO.js.map +1 -0
- package/dist/{db-CRNpA5mH.js → db-KzlqddGD.js} +101 -54
- package/dist/db-KzlqddGD.js.map +1 -0
- package/dist/{derive-CsoFGAnK.js → derive-ae9UOoOB.js} +2 -2
- package/dist/{derive-CsoFGAnK.js.map → derive-ae9UOoOB.js.map} +1 -1
- package/dist/{dev-C0pbMmhS.js → dev-DTqVMgB3.js} +231 -44
- package/dist/dev-DTqVMgB3.js.map +1 -0
- package/dist/dev-db/daemon.d.ts +41 -0
- package/dist/dev-db/pull.d.ts +33 -5
- package/dist/dev-db/state.d.ts +9 -0
- package/dist/{dev-preflight-unHpiYO1.js → dev-preflight-Cxv3TiD1.js} +73 -27
- package/dist/dev-preflight-Cxv3TiD1.js.map +1 -0
- package/dist/{dev-server-B1UYifZJ.js → dev-server-OJsUGZEB.js} +14 -3
- package/dist/dev-server-OJsUGZEB.js.map +1 -0
- package/dist/{doctor-CATRdWm6.js → doctor-BRWOlqeG.js} +14 -12
- package/dist/doctor-BRWOlqeG.js.map +1 -0
- package/dist/{eject-DuasTr-F.js → eject-DABcDnPN.js} +3 -4
- package/dist/{eject-DuasTr-F.js.map → eject-DABcDnPN.js.map} +1 -1
- package/dist/{fold-static-hDHtDfTq.js → fold-static-BnAK-anQ.js} +3 -3
- package/dist/{fold-static-hDHtDfTq.js.map → fold-static-BnAK-anQ.js.map} +1 -1
- package/dist/generate-view-IFwCADvb.js +662 -0
- package/dist/generate-view-IFwCADvb.js.map +1 -0
- package/dist/{generate_sdk-Cvg5jjJF.js → generate_sdk-BvcWvoUh.js} +49 -13
- package/dist/generate_sdk-BvcWvoUh.js.map +1 -0
- package/dist/index.es.js +58 -40
- package/dist/index.es.js.map +1 -1
- package/dist/{init-BWAwHPtz.js → init-CaU6GhwI.js} +50 -62
- package/dist/init-CaU6GhwI.js.map +1 -0
- package/dist/invoked-command-CG_rIa_o.js +55 -0
- package/dist/invoked-command-CG_rIa_o.js.map +1 -0
- package/dist/last-dev-database-DpW5dfoX.js +2 -0
- package/dist/{manifest-DRp0UVTj.js → manifest-BtzDy7KQ.js} +36 -3
- package/dist/{manifest-DRp0UVTj.js.map → manifest-BtzDy7KQ.js.map} +1 -1
- package/dist/{normalize-imports-BoBVh5tU.js → normalize-imports-D0zXlM6g.js} +3 -3
- package/dist/{normalize-imports-BoBVh5tU.js.map → normalize-imports-D0zXlM6g.js.map} +1 -1
- package/dist/{path-flags-BFgG9V6y.js → path-flags-DNvtEi2-.js} +5 -4
- package/dist/path-flags-DNvtEi2-.js.map +1 -0
- package/dist/{prepare-DdnU70z8.js → prepare-CTw9NEkh.js} +5 -4
- package/dist/{prepare-DdnU70z8.js.map → prepare-CTw9NEkh.js.map} +1 -1
- package/dist/project-CasK56vN.js +701 -0
- package/dist/project-CasK56vN.js.map +1 -0
- package/dist/{pull-C3PXduzl.js → pull-DDMpsZ5r.js} +131 -24
- package/dist/pull-DDMpsZ5r.js.map +1 -0
- package/dist/refusal-ReeeGP8a.js +26 -0
- package/dist/refusal-ReeeGP8a.js.map +1 -0
- package/dist/resolve-D647F1LA.js +2 -0
- package/dist/{resources-BdNRDEAy.js → resources-CPSC5Kcu.js} +4 -5
- package/dist/{resources-BdNRDEAy.js.map → resources-CPSC5Kcu.js.map} +1 -1
- package/dist/{schema-B0-p6T1O.js → schema-BSXwZSiI.js} +9 -8
- package/dist/schema-BSXwZSiI.js.map +1 -0
- package/dist/{skills-DfnTeyRz.js → skills-BU2flMOy.js} +52 -8
- package/dist/skills-BU2flMOy.js.map +1 -0
- package/dist/{start-BmEZkS0n.js → start-mVb6upwY.js} +20 -7
- package/dist/start-mVb6upwY.js.map +1 -0
- package/dist/{state-CCB-FAQ9.js → state-CYdBvnwA.js} +3 -2
- package/dist/state-CYdBvnwA.js.map +1 -0
- package/dist/static-syntax-check.d.ts +64 -0
- package/dist/{status-BJ26yZOo.js → status-BREvtzJm.js} +8 -9
- package/dist/{status-BJ26yZOo.js.map → status-BREvtzJm.js.map} +1 -1
- package/dist/{storage-DKPUBTWG.js → storage-DtOXGflp.js} +159 -16
- package/dist/storage-DtOXGflp.js.map +1 -0
- package/dist/{telemetry-EMFRVRQi.js → telemetry-CgwJPVMO.js} +2 -2
- package/dist/{telemetry-EMFRVRQi.js.map → telemetry-CgwJPVMO.js.map} +1 -1
- package/dist/{telemetry-m9czTNGR.js → telemetry-DwK5RQJl.js} +4 -4
- package/dist/{telemetry-m9czTNGR.js.map → telemetry-DwK5RQJl.js.map} +1 -1
- package/dist/{upgrade-DjihWuZL.js → upgrade-B7sVwL8S.js} +26 -4
- package/dist/{upgrade-DjihWuZL.js.map → upgrade-B7sVwL8S.js.map} +1 -1
- package/dist/utils/args.d.ts +32 -3
- package/dist/utils/boot-retry.d.ts +41 -0
- package/dist/utils/collections-dir.d.ts +14 -0
- package/dist/utils/dev-preflight.d.ts +34 -1
- package/dist/utils/dev-server.d.ts +11 -0
- package/dist/utils/path-flags.d.ts +2 -1
- package/dist/utils/project.d.ts +5 -1
- package/dist/utils/tool-stdio.d.ts +1 -1
- package/dist/utils/unknown-command.d.ts +4 -0
- package/dist/verify-D7UsV_qe.js +730 -0
- package/dist/verify-D7UsV_qe.js.map +1 -0
- package/package.json +9 -7
- package/templates/eject/backend/src/index.ts +9 -1
- package/templates/generated-schemas/ecommerce.ts +3 -0
- package/templates/overlays/baas/ai-instructions.md +13 -0
- package/templates/resource-graphs/blank.json +25 -0
- package/templates/resource-graphs/blog.json +28 -0
- package/templates/resource-graphs/ecommerce.json +28 -0
- package/templates/resource-graphs/headless.json +22 -0
- package/templates/template/.claude/hooks/post-edit-collection.sh +99 -0
- package/templates/template/.claude/settings.json +17 -0
- package/templates/template/.env.example +15 -5
- package/templates/template/ai-instructions.md +21 -1
- package/templates/template/config/collections/presets/ecommerce/index.ts +23 -0
- package/templates/template/docker-compose.yml +4 -1
- package/templates/template/frontend/package.json +1 -0
- package/templates/template/frontend/src/App.tsx +10 -9
- package/templates/views/AppView.tsx.tmpl +138 -0
- package/templates/views/EntityView.tsx.tmpl +64 -0
- package/templates/views/index.ts.tmpl +8 -0
- package/dist/agent-setup-B5AKHOgt.js.map +0 -1
- package/dist/api-keys-Tm7zvAPe.js.map +0 -1
- package/dist/args-BX0YD14a.js +0 -266
- package/dist/args-BX0YD14a.js.map +0 -1
- package/dist/auth-Vl2hFKXP.js.map +0 -1
- package/dist/bundle-DtCCCr4w.js.map +0 -1
- package/dist/cloud-BpH0_bmV.js.map +0 -1
- package/dist/console-CEGm0XNc.js.map +0 -1
- package/dist/context-CyflUrKg.js.map +0 -1
- package/dist/daemon-CknkDjd6.js.map +0 -1
- package/dist/daemon-entry-CbLRrgzy.js.map +0 -1
- package/dist/db-CRNpA5mH.js.map +0 -1
- package/dist/dev-C0pbMmhS.js.map +0 -1
- package/dist/dev-preflight-unHpiYO1.js.map +0 -1
- package/dist/dev-server-B1UYifZJ.js.map +0 -1
- package/dist/doctor-CATRdWm6.js.map +0 -1
- package/dist/generate_sdk-Cvg5jjJF.js.map +0 -1
- package/dist/init-BWAwHPtz.js.map +0 -1
- package/dist/last-dev-database-c_dKz1S3.js +0 -2
- package/dist/path-flags-BFgG9V6y.js.map +0 -1
- package/dist/project-Wp2zoyeN.js +0 -349
- package/dist/project-Wp2zoyeN.js.map +0 -1
- package/dist/pull-C3PXduzl.js.map +0 -1
- package/dist/resolve-CNQjsatH.js +0 -2
- package/dist/schema-B0-p6T1O.js.map +0 -1
- package/dist/skills-DfnTeyRz.js.map +0 -1
- package/dist/start-BmEZkS0n.js.map +0 -1
- package/dist/state-CCB-FAQ9.js.map +0 -1
- package/dist/storage-DKPUBTWG.js.map +0 -1
package/dist/args-BX0YD14a.js
DELETED
|
@@ -1,266 +0,0 @@
|
|
|
1
|
-
import chalk from "chalk";
|
|
2
|
-
import arg from "arg";
|
|
3
|
-
//#region src/utils/redact.ts
|
|
4
|
-
/**
|
|
5
|
-
* Connection-string passwords, replaced before a line is printed.
|
|
6
|
-
*
|
|
7
|
-
* A refusal that repeats what was typed repeats a password with it, and these
|
|
8
|
-
* lines land in terminals, CI logs and issues. `user:***@` is the form every
|
|
9
|
-
* other message uses: the driver's `redactConnectionPasswords` in
|
|
10
|
-
* `@rebasepro/server-postgres`, which its entry does not export, and this
|
|
11
|
-
* mirrors. Covers the user-info password and a `password=` parameter.
|
|
12
|
-
*/
|
|
13
|
-
function redactConnectionPasswords(text) {
|
|
14
|
-
return text.replace(/(\b[a-z][a-z0-9+.-]*:\/\/[^\s/?#@'"]*):[^\s/?#'"]*@/gi, "$1:***@").replace(/(\bpassword\s*=\s*)('[^']*'|[^\s&'"]+)/gi, "$1***");
|
|
15
|
-
}
|
|
16
|
-
//#endregion
|
|
17
|
-
//#region src/utils/unknown-command.ts
|
|
18
|
-
/**
|
|
19
|
-
* What every command family says when it does not recognise a subcommand.
|
|
20
|
-
*
|
|
21
|
-
* Six families each did it differently, and the differences were not stylistic:
|
|
22
|
-
*
|
|
23
|
-
* rebase statsu "Unknown command: statsu" + the whole top-level help
|
|
24
|
-
* rebase auth foo "Unknown auth command: foo" + the whole auth help
|
|
25
|
-
* rebase apps foo "Unknown subcommand: foo" — which command's?
|
|
26
|
-
* rebase skills foo "Unknown skills subcommand: foo" + the whole help
|
|
27
|
-
* rebase telemetry x the help, silently, with exit code 1 and no error line
|
|
28
|
-
* rebase cloud debug x both a JSON error *and* the human one, in JSON mode
|
|
29
|
-
*
|
|
30
|
-
* Dumping a screen of help after an error is the wrong shape: the one line that
|
|
31
|
-
* says what happened scrolls off the top, and in a CI log it is buried in
|
|
32
|
-
* forty. None of them offered the correction, which for a typo is the entire
|
|
33
|
-
* answer — `statsu` is one transposition from `status`.
|
|
34
|
-
*
|
|
35
|
-
* So: one line, the near-miss when there is one, and where to read the rest.
|
|
36
|
-
*/
|
|
37
|
-
/**
|
|
38
|
-
* Damerau–Levenshtein distance, capped by the caller.
|
|
39
|
-
*
|
|
40
|
-
* The transposition is the reason this is not plain Levenshtein: `statsu` for
|
|
41
|
-
* `status` and `craete` for `create` are the two most common typing errors
|
|
42
|
-
* there are, and both are distance 2 without it — the same as two unrelated
|
|
43
|
-
* edits, which is too far to suggest anything at all.
|
|
44
|
-
*/
|
|
45
|
-
function editDistance(a, b) {
|
|
46
|
-
const rows = a.length + 1;
|
|
47
|
-
const cols = b.length + 1;
|
|
48
|
-
const d = Array.from({ length: rows }, () => new Array(cols).fill(0));
|
|
49
|
-
for (let i = 0; i < rows; i++) d[i][0] = i;
|
|
50
|
-
for (let j = 0; j < cols; j++) d[0][j] = j;
|
|
51
|
-
for (let i = 1; i < rows; i++) for (let j = 1; j < cols; j++) {
|
|
52
|
-
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
53
|
-
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
54
|
-
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
55
|
-
}
|
|
56
|
-
return d[a.length][b.length];
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* The one command the user probably meant, or nothing.
|
|
60
|
-
*
|
|
61
|
-
* Tight on purpose. A suggestion that is wrong is worse than none: it sends
|
|
62
|
-
* someone to read the help for a command that was never the answer, and on a
|
|
63
|
-
* family like `db` — where `push` and `pull` are one edit apart — a loose
|
|
64
|
-
* threshold would confidently propose the destructive neighbour of what they
|
|
65
|
-
* typed. So: one edit for a short word, two for a long one, and a prefix match
|
|
66
|
-
* always counts (`rebase cloud dep` for `deploy`).
|
|
67
|
-
*/
|
|
68
|
-
function suggestCommand(typed, known) {
|
|
69
|
-
const word = typed.toLowerCase();
|
|
70
|
-
if (!word) return void 0;
|
|
71
|
-
if (word.length >= 3) {
|
|
72
|
-
const prefixed = known.filter((name) => name.toLowerCase().startsWith(word));
|
|
73
|
-
if (prefixed.length === 1) return prefixed[0];
|
|
74
|
-
}
|
|
75
|
-
const budget = word.length <= 4 ? 1 : 2;
|
|
76
|
-
let best;
|
|
77
|
-
for (const candidate of known) {
|
|
78
|
-
const distance = editDistance(word, candidate.toLowerCase());
|
|
79
|
-
if (distance > budget) continue;
|
|
80
|
-
if (!best || distance < best.distance) best = {
|
|
81
|
-
name: candidate,
|
|
82
|
-
distance
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
return best?.name;
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* The family command a word names exactly, as `<family> <command>`, or nothing.
|
|
89
|
-
*
|
|
90
|
-
* `rebase deploy` is `rebase cloud deploy`: the word is a whole command one
|
|
91
|
-
* level down. Exact only — a near miss there is a guess about both the family
|
|
92
|
-
* and the command.
|
|
93
|
-
*/
|
|
94
|
-
function familyCommand(typed, families) {
|
|
95
|
-
const word = typed.toLowerCase();
|
|
96
|
-
for (const [family, commands] of Object.entries(families)) {
|
|
97
|
-
const match = commands.find((name) => name.toLowerCase() === word);
|
|
98
|
-
if (match) return `${family} ${match}`;
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
/**
|
|
102
|
-
* The line itself, without printing it — so callers that must answer in JSON
|
|
103
|
-
* (the cloud family, whose `fail()` writes a machine-readable envelope) use the
|
|
104
|
-
* same words as the ones that print.
|
|
105
|
-
*
|
|
106
|
-
* `family` is empty for the top level: `rebase --help`, not `rebase --help`.
|
|
107
|
-
* `families` are the command families below this level, by name, whose
|
|
108
|
-
* commands a word may be one of.
|
|
109
|
-
*/
|
|
110
|
-
function unknownCommandMessage(typed, known, family = "", families = {}) {
|
|
111
|
-
const what = family ? `${family} command` : "command";
|
|
112
|
-
const suggestion = typed ? suggestCommand(typed, known) ?? familyCommand(typed, families) : void 0;
|
|
113
|
-
const help = family ? `rebase ${family} --help` : "rebase --help";
|
|
114
|
-
return suggestion ? `Unknown ${what} "${typed}" — did you mean \`${suggestion}\`? Run \`${help}\` for the rest.` : `Unknown ${what} "${typed ?? ""}". Run \`${help}\` for the ones there are.`;
|
|
115
|
-
}
|
|
116
|
-
/**
|
|
117
|
-
* Print the line to stderr and exit 1.
|
|
118
|
-
*
|
|
119
|
-
* stderr, not stdout: a mistyped command is a failure, and the families with a
|
|
120
|
-
* `--json` mode guarantee that stdout holds only their envelope.
|
|
121
|
-
*/
|
|
122
|
-
function unknownCommand(typed, known, family = "", families = {}) {
|
|
123
|
-
console.error(chalk.red(`✗ ${unknownCommandMessage(typed, known, family, families)}`));
|
|
124
|
-
process.exit(1);
|
|
125
|
-
}
|
|
126
|
-
//#endregion
|
|
127
|
-
//#region src/utils/args.ts
|
|
128
|
-
/**
|
|
129
|
-
* Argument parsing for the commands that take positional arguments.
|
|
130
|
-
*
|
|
131
|
-
* Every command in the small group used to parse its own line the same way:
|
|
132
|
-
* `arg(spec, { argv: rawArgs.slice(4), permissive: true })`, then read `_[0]`
|
|
133
|
-
* and `_[1]`. Both halves of that are wrong in a way that costs data.
|
|
134
|
-
*
|
|
135
|
-
* - **`permissive: true` turns an unknown flag into a positional.** `arg`
|
|
136
|
-
* pushes an undeclared flag into `_` as a bare token, so `_[1]` is whatever
|
|
137
|
-
* came second on the line, flag or not. `rebase auth reset-password
|
|
138
|
-
* bob@example.com --debug` set Bob's password to the literal `--debug` — and
|
|
139
|
-
* `--debug` is what `bin/rebase.js` prints after *every* failure as the thing
|
|
140
|
-
* to re-run with, so the single most likely next keystroke after a failed
|
|
141
|
-
* reset was the one that reset the account to a two-word string.
|
|
142
|
-
* - **`slice(4)` assumes the command words are at fixed indices.** They are
|
|
143
|
-
* not: a flag before the command shifts everything, so `rebase --debug auth
|
|
144
|
-
* reset-password bob@example.com NewPass1!` read the email as
|
|
145
|
-
* `reset-password` and the password as `bob@example.com`.
|
|
146
|
-
*
|
|
147
|
-
* So: parse the *whole* line — `rawArgs` is `process.argv` — against a spec
|
|
148
|
-
* strictly, with no permissive mode. `arg` then consumes every flag wherever it
|
|
149
|
-
* appears and rejects the ones nobody declared, which leaves `_` holding the
|
|
150
|
-
* command words followed by the real positionals, in order and at a known
|
|
151
|
-
* offset. An unrecognised flag becomes an error naming the command's help,
|
|
152
|
-
* which is the only safe answer: the alternative is guessing that it was meant
|
|
153
|
-
* as a value.
|
|
154
|
-
*
|
|
155
|
-
* `commands/cloud/index.ts` resolves its positionals against its own spec for
|
|
156
|
-
* the same reason; this is that idea for the commands whose positionals are
|
|
157
|
-
* credentials rather than resource names.
|
|
158
|
-
*/
|
|
159
|
-
/**
|
|
160
|
-
* Flags accepted on top of whatever a command declares.
|
|
161
|
-
*
|
|
162
|
-
* `--debug` is read by `bin/rebase.js` off `process.argv` and never by a
|
|
163
|
-
* command, but it has to be *declared* somewhere or strict parsing rejects the
|
|
164
|
-
* exact flag the CLI tells people to add. `--help`/`-h` are answered by each
|
|
165
|
-
* command's dispatcher before any work happens.
|
|
166
|
-
*/
|
|
167
|
-
var GLOBAL_COMMAND_FLAGS = {
|
|
168
|
-
"--debug": Boolean,
|
|
169
|
-
"--help": Boolean,
|
|
170
|
-
"-h": "--help"
|
|
171
|
-
};
|
|
172
|
-
/**
|
|
173
|
-
* The declared long flag an undeclared one was probably meant to be: one edit
|
|
174
|
-
* or one swap away (`--form` → `--from`), or an abbreviation of exactly one
|
|
175
|
-
* (`--anon` → `--anonymize`).
|
|
176
|
-
*/
|
|
177
|
-
function closestDeclaredFlag(typed, declared) {
|
|
178
|
-
if (!typed.startsWith("--")) return void 0;
|
|
179
|
-
const near = suggestCommand(typed.slice(2), declared.filter((flag) => flag.startsWith("--")).map((flag) => flag.slice(2)));
|
|
180
|
-
return near ? `--${near}` : void 0;
|
|
181
|
-
}
|
|
182
|
-
/** Past this many, a refusal names the help page rather than listing every flag. */
|
|
183
|
-
var LISTED_FLAGS_MAX = 8;
|
|
184
|
-
/**
|
|
185
|
-
* The sentence an undeclared flag is refused with — the one `db backup`,
|
|
186
|
-
* `db restore` and `db branch` say, so one CLI answers a typo one way:
|
|
187
|
-
*
|
|
188
|
-
* `rebase db pull` has no option --anonymise — did you mean --anonymize?
|
|
189
|
-
* Nothing was run. See `rebase db pull --help`.
|
|
190
|
-
*
|
|
191
|
-
* With nothing close it lists what the command takes, when that list is short
|
|
192
|
-
* enough to read.
|
|
193
|
-
*
|
|
194
|
-
* Exported for the commands that refuse a flag outside `parseCommandArgs`.
|
|
195
|
-
*/
|
|
196
|
-
function unknownOptionMessage(command, typed, spec) {
|
|
197
|
-
const near = closestDeclaredFlag(typed, Object.keys({
|
|
198
|
-
...GLOBAL_COMMAND_FLAGS,
|
|
199
|
-
...spec
|
|
200
|
-
}));
|
|
201
|
-
const own = Object.keys(spec).filter((flag) => flag.startsWith("--") && !(flag in GLOBAL_COMMAND_FLAGS));
|
|
202
|
-
return `\`rebase ${command}\` has no option ${typed}${near ? ` — did you mean ${near}?` : own.length === 0 ? " — it takes no options." : own.length <= LISTED_FLAGS_MAX ? ` — it takes ${own.join(", ")}.` : "."} Nothing was run. See \`rebase ${command} --help\`.`;
|
|
203
|
-
}
|
|
204
|
-
/** Did the line ask for help? Answered before dispatch, never by a handler. */
|
|
205
|
-
function wantsHelp(rawArgs) {
|
|
206
|
-
return rawArgs.includes("--help") || rawArgs.includes("-h");
|
|
207
|
-
}
|
|
208
|
-
/**
|
|
209
|
-
* The command line was wrong — nothing ran, and there is no stack to want.
|
|
210
|
-
*
|
|
211
|
-
* `bin/rebase.js` ends every failure with "Re-run with --debug for the stack
|
|
212
|
-
* trace.", which is right when something broke inside a command and absurd for
|
|
213
|
-
* a typo: the stack points at `arg` and this file, neither of which the person
|
|
214
|
-
* who mistyped `--ouput` has any interest in. Worse, `--debug` is a flag, so
|
|
215
|
-
* the suggested next command is *another* command line — and the one thing we
|
|
216
|
-
* have just established is that the command line is what went wrong.
|
|
217
|
-
*
|
|
218
|
-
* Marked with a property rather than left to `instanceof`, because the reader
|
|
219
|
-
* is `bin/rebase.js`: it imports the bundle, so the class object it would test
|
|
220
|
-
* against is not the one this file compiled to.
|
|
221
|
-
*/
|
|
222
|
-
var UsageError = class extends Error {
|
|
223
|
-
isUsageError = true;
|
|
224
|
-
constructor(message) {
|
|
225
|
-
super(message);
|
|
226
|
-
this.name = "UsageError";
|
|
227
|
-
}
|
|
228
|
-
};
|
|
229
|
-
/**
|
|
230
|
-
* Resolve a command's flags and positionals from the full `process.argv`.
|
|
231
|
-
*
|
|
232
|
-
* `commandWords` is how many words name the command itself — 2 for
|
|
233
|
-
* `auth reset-password`, 1 for `start` — and is applied to the *parsed*
|
|
234
|
-
* positionals rather than to `argv`, so a flag placed before the command no
|
|
235
|
-
* longer shifts them.
|
|
236
|
-
*
|
|
237
|
-
* `command` names the command in error messages, e.g. `auth reset-password`.
|
|
238
|
-
*
|
|
239
|
-
* Throws on an unknown flag, on a positional that looks like a flag, and on
|
|
240
|
-
* more positionals than the command takes. `bin/rebase.js` turns each into a
|
|
241
|
-
* one-line `✗ …` and exit 1.
|
|
242
|
-
*/
|
|
243
|
-
function parseCommandArgs({ spec, rawArgs, commandWords, command, maxPositionals }) {
|
|
244
|
-
let parsed;
|
|
245
|
-
try {
|
|
246
|
-
parsed = arg({
|
|
247
|
-
...GLOBAL_COMMAND_FLAGS,
|
|
248
|
-
...spec
|
|
249
|
-
}, { argv: rawArgs.slice(2) });
|
|
250
|
-
} catch (err) {
|
|
251
|
-
if (err instanceof Error && err.code === "ARG_UNKNOWN_OPTION") throw new UsageError(unknownOptionMessage(command, (/option: (\S+)$/.exec(err.message)?.[1] ?? err.message).split("=")[0], spec));
|
|
252
|
-
throw err;
|
|
253
|
-
}
|
|
254
|
-
const positionals = parsed._.slice(commandWords);
|
|
255
|
-
for (const value of positionals) if (value.startsWith("-")) throw new UsageError(`\`${value}\` looks like an option, not a value — pass it with an explicit flag (\`rebase ${command} --help\`).`);
|
|
256
|
-
if (maxPositionals !== void 0 && positionals.length > maxPositionals) throw new UsageError(`rebase ${command} takes ${maxPositionals} argument${maxPositionals === 1 ? "" : "s"}, got ${positionals.length}: ${redactConnectionPasswords(positionals.join(" "))}`);
|
|
257
|
-
return {
|
|
258
|
-
flags: parsed,
|
|
259
|
-
positionals,
|
|
260
|
-
help: Boolean(parsed["--help"])
|
|
261
|
-
};
|
|
262
|
-
}
|
|
263
|
-
//#endregion
|
|
264
|
-
export { unknownCommand as a, suggestCommand as i, parseCommandArgs as n, unknownCommandMessage as o, wantsHelp as r, redactConnectionPasswords as s, UsageError as t };
|
|
265
|
-
|
|
266
|
-
//# sourceMappingURL=args-BX0YD14a.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"args-BX0YD14a.js","names":[],"sources":["../src/utils/redact.ts","../src/utils/unknown-command.ts","../src/utils/args.ts"],"sourcesContent":["/**\n * Connection-string passwords, replaced before a line is printed.\n *\n * A refusal that repeats what was typed repeats a password with it, and these\n * lines land in terminals, CI logs and issues. `user:***@` is the form every\n * other message uses: the driver's `redactConnectionPasswords` in\n * `@rebasepro/server-postgres`, which its entry does not export, and this\n * mirrors. Covers the user-info password and a `password=` parameter.\n */\nexport function redactConnectionPasswords(text: string): string {\n return text\n .replace(/(\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s/?#@'\"]*):[^\\s/?#'\"]*@/gi, \"$1:***@\")\n .replace(/(\\bpassword\\s*=\\s*)('[^']*'|[^\\s&'\"]+)/gi, \"$1***\");\n}\n","/**\n * What every command family says when it does not recognise a subcommand.\n *\n * Six families each did it differently, and the differences were not stylistic:\n *\n * rebase statsu \"Unknown command: statsu\" + the whole top-level help\n * rebase auth foo \"Unknown auth command: foo\" + the whole auth help\n * rebase apps foo \"Unknown subcommand: foo\" — which command's?\n * rebase skills foo \"Unknown skills subcommand: foo\" + the whole help\n * rebase telemetry x the help, silently, with exit code 1 and no error line\n * rebase cloud debug x both a JSON error *and* the human one, in JSON mode\n *\n * Dumping a screen of help after an error is the wrong shape: the one line that\n * says what happened scrolls off the top, and in a CI log it is buried in\n * forty. None of them offered the correction, which for a typo is the entire\n * answer — `statsu` is one transposition from `status`.\n *\n * So: one line, the near-miss when there is one, and where to read the rest.\n */\nimport chalk from \"chalk\";\n\n/**\n * Damerau–Levenshtein distance, capped by the caller.\n *\n * The transposition is the reason this is not plain Levenshtein: `statsu` for\n * `status` and `craete` for `create` are the two most common typing errors\n * there are, and both are distance 2 without it — the same as two unrelated\n * edits, which is too far to suggest anything at all.\n */\nfunction editDistance(a: string, b: string): number {\n const rows = a.length + 1;\n const cols = b.length + 1;\n const d: number[][] = Array.from({ length: rows }, () => new Array<number>(cols).fill(0));\n\n for (let i = 0; i < rows; i++) d[i][0] = i;\n for (let j = 0; j < cols; j++) d[0][j] = j;\n\n for (let i = 1; i < rows; i++) {\n for (let j = 1; j < cols; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n d[i][j] = Math.min(\n d[i - 1][j] + 1,\n d[i][j - 1] + 1,\n d[i - 1][j - 1] + cost\n );\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n return d[a.length][b.length];\n}\n\n/**\n * The one command the user probably meant, or nothing.\n *\n * Tight on purpose. A suggestion that is wrong is worse than none: it sends\n * someone to read the help for a command that was never the answer, and on a\n * family like `db` — where `push` and `pull` are one edit apart — a loose\n * threshold would confidently propose the destructive neighbour of what they\n * typed. So: one edit for a short word, two for a long one, and a prefix match\n * always counts (`rebase cloud dep` for `deploy`).\n */\nexport function suggestCommand(typed: string, known: readonly string[]): string | undefined {\n const word = typed.toLowerCase();\n if (!word) return undefined;\n\n // An abbreviation, but only when it names exactly one command. \"res\" is a\n // prefix of both `reset` and `restore`, and picking whichever comes first\n // in the list would be a coin toss dressed up as an answer.\n if (word.length >= 3) {\n const prefixed = known.filter(name => name.toLowerCase().startsWith(word));\n if (prefixed.length === 1) return prefixed[0];\n }\n\n const budget = word.length <= 4 ? 1 : 2;\n let best: { name: string; distance: number } | undefined;\n\n for (const candidate of known) {\n const distance = editDistance(word, candidate.toLowerCase());\n if (distance > budget) continue;\n if (!best || distance < best.distance) best = { name: candidate, distance };\n }\n\n return best?.name;\n}\n\n/**\n * The family command a word names exactly, as `<family> <command>`, or nothing.\n *\n * `rebase deploy` is `rebase cloud deploy`: the word is a whole command one\n * level down. Exact only — a near miss there is a guess about both the family\n * and the command.\n */\nfunction familyCommand(typed: string, families: Readonly<Record<string, readonly string[]>>): string | undefined {\n const word = typed.toLowerCase();\n for (const [family, commands] of Object.entries(families)) {\n const match = commands.find(name => name.toLowerCase() === word);\n if (match) return `${family} ${match}`;\n }\n return undefined;\n}\n\n/**\n * The line itself, without printing it — so callers that must answer in JSON\n * (the cloud family, whose `fail()` writes a machine-readable envelope) use the\n * same words as the ones that print.\n *\n * `family` is empty for the top level: `rebase --help`, not `rebase --help`.\n * `families` are the command families below this level, by name, whose\n * commands a word may be one of.\n */\nexport function unknownCommandMessage(\n typed: string | undefined,\n known: readonly string[],\n family = \"\",\n families: Readonly<Record<string, readonly string[]>> = {}\n): string {\n const what = family ? `${family} command` : \"command\";\n const suggestion = typed ? suggestCommand(typed, known) ?? familyCommand(typed, families) : undefined;\n const help = family ? `rebase ${family} --help` : \"rebase --help\";\n\n return suggestion\n ? `Unknown ${what} \"${typed}\" — did you mean \\`${suggestion}\\`? Run \\`${help}\\` for the rest.`\n : `Unknown ${what} \"${typed ?? \"\"}\". Run \\`${help}\\` for the ones there are.`;\n}\n\n/**\n * Print the line to stderr and exit 1.\n *\n * stderr, not stdout: a mistyped command is a failure, and the families with a\n * `--json` mode guarantee that stdout holds only their envelope.\n */\nexport function unknownCommand(\n typed: string | undefined,\n known: readonly string[],\n family = \"\",\n families: Readonly<Record<string, readonly string[]>> = {}\n): never {\n console.error(chalk.red(`✗ ${unknownCommandMessage(typed, known, family, families)}`));\n process.exit(1);\n}\n","/**\n * Argument parsing for the commands that take positional arguments.\n *\n * Every command in the small group used to parse its own line the same way:\n * `arg(spec, { argv: rawArgs.slice(4), permissive: true })`, then read `_[0]`\n * and `_[1]`. Both halves of that are wrong in a way that costs data.\n *\n * - **`permissive: true` turns an unknown flag into a positional.** `arg`\n * pushes an undeclared flag into `_` as a bare token, so `_[1]` is whatever\n * came second on the line, flag or not. `rebase auth reset-password\n * bob@example.com --debug` set Bob's password to the literal `--debug` — and\n * `--debug` is what `bin/rebase.js` prints after *every* failure as the thing\n * to re-run with, so the single most likely next keystroke after a failed\n * reset was the one that reset the account to a two-word string.\n * - **`slice(4)` assumes the command words are at fixed indices.** They are\n * not: a flag before the command shifts everything, so `rebase --debug auth\n * reset-password bob@example.com NewPass1!` read the email as\n * `reset-password` and the password as `bob@example.com`.\n *\n * So: parse the *whole* line — `rawArgs` is `process.argv` — against a spec\n * strictly, with no permissive mode. `arg` then consumes every flag wherever it\n * appears and rejects the ones nobody declared, which leaves `_` holding the\n * command words followed by the real positionals, in order and at a known\n * offset. An unrecognised flag becomes an error naming the command's help,\n * which is the only safe answer: the alternative is guessing that it was meant\n * as a value.\n *\n * `commands/cloud/index.ts` resolves its positionals against its own spec for\n * the same reason; this is that idea for the commands whose positionals are\n * credentials rather than resource names.\n */\nimport arg from \"arg\";\n\nimport { redactConnectionPasswords } from \"./redact\";\nimport { suggestCommand } from \"./unknown-command\";\n\n/**\n * Flags accepted on top of whatever a command declares.\n *\n * `--debug` is read by `bin/rebase.js` off `process.argv` and never by a\n * command, but it has to be *declared* somewhere or strict parsing rejects the\n * exact flag the CLI tells people to add. `--help`/`-h` are answered by each\n * command's dispatcher before any work happens.\n */\nexport const GLOBAL_COMMAND_FLAGS = {\n \"--debug\": Boolean,\n \"--help\": Boolean,\n \"-h\": \"--help\"\n} as const;\n\n/**\n * The declared long flag an undeclared one was probably meant to be: one edit\n * or one swap away (`--form` → `--from`), or an abbreviation of exactly one\n * (`--anon` → `--anonymize`).\n */\nfunction closestDeclaredFlag(typed: string, declared: readonly string[]): string | undefined {\n if (!typed.startsWith(\"--\")) return undefined;\n const near = suggestCommand(typed.slice(2), declared.filter(flag => flag.startsWith(\"--\")).map(flag => flag.slice(2)));\n return near ? `--${near}` : undefined;\n}\n\n/** Past this many, a refusal names the help page rather than listing every flag. */\nconst LISTED_FLAGS_MAX = 8;\n\n/**\n * The sentence an undeclared flag is refused with — the one `db backup`,\n * `db restore` and `db branch` say, so one CLI answers a typo one way:\n *\n * `rebase db pull` has no option --anonymise — did you mean --anonymize?\n * Nothing was run. See `rebase db pull --help`.\n *\n * With nothing close it lists what the command takes, when that list is short\n * enough to read.\n *\n * Exported for the commands that refuse a flag outside `parseCommandArgs`.\n */\nexport function unknownOptionMessage(command: string, typed: string, spec: Readonly<Record<string, unknown>>): string {\n const declared = Object.keys({ ...GLOBAL_COMMAND_FLAGS, ...spec });\n const near = closestDeclaredFlag(typed, declared);\n const own = Object.keys(spec).filter(flag => flag.startsWith(\"--\") && !(flag in GLOBAL_COMMAND_FLAGS));\n const takes = near\n ? ` — did you mean ${near}?`\n : own.length === 0\n ? \" — it takes no options.\"\n : own.length <= LISTED_FLAGS_MAX ? ` — it takes ${own.join(\", \")}.` : \".\";\n\n return `\\`rebase ${command}\\` has no option ${typed}${takes} Nothing was run. See \\`rebase ${command} --help\\`.`;\n}\n\nexport interface ParsedCommand<S extends arg.Spec> {\n /** The declared flags, as `arg` resolved them. */\n flags: arg.Result<S>;\n /** What is left after the command words — never a flag. */\n positionals: string[];\n /** `--help` or `-h` appeared anywhere on the line. */\n help: boolean;\n}\n\n/** Did the line ask for help? Answered before dispatch, never by a handler. */\nexport function wantsHelp(rawArgs: string[]): boolean {\n return rawArgs.includes(\"--help\") || rawArgs.includes(\"-h\");\n}\n\n/**\n * The command line was wrong — nothing ran, and there is no stack to want.\n *\n * `bin/rebase.js` ends every failure with \"Re-run with --debug for the stack\n * trace.\", which is right when something broke inside a command and absurd for\n * a typo: the stack points at `arg` and this file, neither of which the person\n * who mistyped `--ouput` has any interest in. Worse, `--debug` is a flag, so\n * the suggested next command is *another* command line — and the one thing we\n * have just established is that the command line is what went wrong.\n *\n * Marked with a property rather than left to `instanceof`, because the reader\n * is `bin/rebase.js`: it imports the bundle, so the class object it would test\n * against is not the one this file compiled to.\n */\nexport class UsageError extends Error {\n readonly isUsageError = true;\n\n constructor(message: string) {\n super(message);\n this.name = \"UsageError\";\n }\n}\n\n/**\n * Resolve a command's flags and positionals from the full `process.argv`.\n *\n * `commandWords` is how many words name the command itself — 2 for\n * `auth reset-password`, 1 for `start` — and is applied to the *parsed*\n * positionals rather than to `argv`, so a flag placed before the command no\n * longer shifts them.\n *\n * `command` names the command in error messages, e.g. `auth reset-password`.\n *\n * Throws on an unknown flag, on a positional that looks like a flag, and on\n * more positionals than the command takes. `bin/rebase.js` turns each into a\n * one-line `✗ …` and exit 1.\n */\nexport function parseCommandArgs<S extends arg.Spec>({\n spec,\n rawArgs,\n commandWords,\n command,\n maxPositionals\n}: {\n spec: S;\n rawArgs: string[];\n commandWords: number;\n command: string;\n maxPositionals?: number;\n}): ParsedCommand<S> {\n let parsed: arg.Result<S> & { \"--help\"?: boolean };\n try {\n const merged = {\n ...GLOBAL_COMMAND_FLAGS,\n ...spec\n };\n parsed = arg(merged, { argv: rawArgs.slice(2) }) as arg.Result<S> & { \"--help\"?: boolean };\n } catch (err) {\n if (err instanceof Error && (err as arg.ArgError).code === \"ARG_UNKNOWN_OPTION\") {\n // arg's wording: `unknown or unexpected option: --form`.\n const typed = /option: (\\S+)$/.exec(err.message)?.[1] ?? err.message;\n throw new UsageError(unknownOptionMessage(command, typed.split(\"=\")[0], spec));\n }\n throw err;\n }\n\n const positionals = parsed._.slice(commandWords);\n\n for (const value of positionals) {\n // Only reachable past a `--` separator or for a bare `-`, since anything\n // else beginning with `-` was either declared or already rejected above.\n // Still refused rather than accepted: a value that looks like a flag is\n // as likely to be a typo as an argument, and one of these positions is a\n // password.\n if (value.startsWith(\"-\")) {\n throw new UsageError(\n `\\`${value}\\` looks like an option, not a value — pass it with an explicit flag ` +\n `(\\`rebase ${command} --help\\`).`\n );\n }\n }\n\n if (maxPositionals !== undefined && positionals.length > maxPositionals) {\n // Redacted: a connection string passed where a flag's value belongs\n // (`rebase db pull \"$PROD\"`) is still a password.\n throw new UsageError(\n `rebase ${command} takes ${maxPositionals} argument${maxPositionals === 1 ? \"\" : \"s\"}, ` +\n `got ${positionals.length}: ${redactConnectionPasswords(positionals.join(\" \"))}`\n );\n }\n\n return {\n flags: parsed,\n positionals,\n help: Boolean(parsed[\"--help\"])\n };\n}\n"],"mappings":";;;;;;;;;;;;AASA,SAAgB,0BAA0B,MAAsB;CAC5D,OAAO,KACF,QAAQ,yDAAyD,SAAS,CAAC,CAC3E,QAAQ,4CAA4C,OAAO;AACpE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACgBA,SAAS,aAAa,GAAW,GAAmB;CAChD,MAAM,OAAO,EAAE,SAAS;CACxB,MAAM,OAAO,EAAE,SAAS;CACxB,MAAM,IAAgB,MAAM,KAAK,EAAE,QAAQ,KAAK,SAAS,IAAI,MAAc,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC;CAExF,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK,EAAE,EAAE,CAAC,KAAK;CACzC,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK,EAAE,EAAE,CAAC,KAAK;CAEzC,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KACtB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK;EAC3B,MAAM,OAAO,EAAE,IAAI,OAAO,EAAE,IAAI,KAAK,IAAI;EACzC,EAAE,EAAE,CAAC,KAAK,KAAK,IACX,EAAE,IAAI,EAAE,CAAC,KAAK,GACd,EAAE,EAAE,CAAC,IAAI,KAAK,GACd,EAAE,IAAI,EAAE,CAAC,IAAI,KAAK,IACtB;EACA,IAAI,IAAI,KAAK,IAAI,KAAK,EAAE,IAAI,OAAO,EAAE,IAAI,MAAM,EAAE,IAAI,OAAO,EAAE,IAAI,IAC9D,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,EAAE,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,CAA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B;AACJ;;;;;;;;;;;;;;;AAgBA,SAAgB,iBAAqC,EACjD,MACA,SACA,cACA,SACA,kBAOiB;CACjB,IAAI;CACJ,IAAI;EAKA,SAAS,IAAI;GAHT,GAAG;GACH,GAAG;EAEM,GAAQ,EAAE,MAAM,QAAQ,MAAM,CAAC,EAAE,CAAC;CACnD,SAAS,KAAK;EACV,IAAI,eAAe,SAAU,IAAqB,SAAS,sBAGvD,MAAM,IAAI,WAAW,qBAAqB,UAD5B,iBAAiB,KAAK,IAAI,OAAO,CAAC,GAAG,MAAM,IAAI,QACV,CAAM,MAAM,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC;EAEjF,MAAM;CACV;CAEA,MAAM,cAAc,OAAO,EAAE,MAAM,YAAY;CAE/C,KAAK,MAAM,SAAS,aAMhB,IAAI,MAAM,WAAW,GAAG,GACpB,MAAM,IAAI,WACN,KAAK,MAAM,iFACE,QAAQ,YACzB;CAIR,IAAI,mBAAmB,KAAA,KAAa,YAAY,SAAS,gBAGrD,MAAM,IAAI,WACN,UAAU,QAAQ,SAAS,eAAe,WAAW,mBAAmB,IAAI,KAAK,IAAI,QAC9E,YAAY,OAAO,IAAI,0BAA0B,YAAY,KAAK,GAAG,CAAC,GACjF;CAGJ,OAAO;EACH,OAAO;EACP;EACA,MAAM,QAAQ,OAAO,SAAS;CAClC;AACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"auth-Vl2hFKXP.js","names":[],"sources":["../src/commands/auth.ts"],"sourcesContent":["/**\n * CLI command: rebase auth <action>\n *\n * Subcommands:\n * reset-password — Reset a user's password\n */\nimport chalk from \"chalk\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { spawn } from \"child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n findEnvFile,\n readEnvFile,\n resolveTsx,\n exitDependenciesNotInstalled\n} from \"../utils/project\";\nimport { parseEnvBoolean } from \"@rebasepro/types\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { redactConnectionPasswords } from \"../utils/redact\";\nimport type { PreparedDatabase } from \"../dev-db/prepare\";\nimport type { DevDatabaseSource } from \"../dev-db/resolve\";\n\n/** The backend was reached and refused: not a reason to fall back to the database. */\nclass ApiAnswered extends Error {}\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const AUTH_SUBCOMMANDS = [\"reset-password\"] as const;\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { resolveBackendAddress } from \"./api-keys\";\n\n/** A user as the admin API returns it, reduced to what this command needs. */\nexport interface ResolvedUser {\n id: string;\n email: string;\n}\n\n/**\n * Pick the user with exactly this email out of a search response.\n *\n * `/api/admin/users?search=` is an `ILIKE '%…%'` over email **or display\n * name**, ordered by role count descending. This used to take row `[0]` and\n * reset it, then print the email it had been *given* as confirmation — so two\n * ordinary situations ended in a successful-looking reset of somebody else's\n * account:\n *\n * - a substring collision: `bob@example.com` also matches\n * `robert.bob@example.com`;\n * - a display name, which is user-controlled and accepted up to 255\n * characters with no constraint on its content, containing an address\n * belonging to someone else.\n *\n * The ordering makes it worse rather than better — `array_length(roles) DESC\n * NULLS LAST` puts the most privileged match first, so the account most likely\n * to be reset by mistake is an admin's.\n *\n * Returns `undefined` when nothing matched exactly, which the caller reports\n * rather than falling through to a guess. The direct-database fallback below\n * has always matched with `eq(usersTable.email, email)`; this is the same\n * definition, so the command no longer resets different accounts depending on\n * whether the backend happened to be running.\n */\nexport function selectUserForEmail(payload: unknown, email: string): ResolvedUser | undefined {\n const wanted = email.trim().toLowerCase();\n if (!wanted) return undefined;\n\n const rows: unknown[] = Array.isArray(payload)\n ? payload\n : (payload && typeof payload === \"object\" && Array.isArray((payload as { users?: unknown }).users)\n ? (payload as { users: unknown[] }).users\n : []);\n\n for (const row of rows) {\n if (!row || typeof row !== \"object\") continue;\n const record = row as Record<string, unknown>;\n const rowEmail = typeof record.email === \"string\" ? record.email.trim().toLowerCase() : undefined;\n if (!rowEmail || rowEmail !== wanted) continue;\n\n const id = typeof record.id === \"string\"\n ? record.id\n : (typeof record.uid === \"string\" ? record.uid : undefined);\n if (!id) continue;\n\n return { id, email: record.email as string };\n }\n\n return undefined;\n}\n\nexport async function authCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // `--help` is answered here and never reaches a handler. `cli.ts` only\n // rewrites the subcommand to `\"--help\"` when no subcommand was named, so\n // `rebase auth reset-password --help` used to *run the reset*: `--help`\n // became the email, the backend was contacted, `.tmp-reset-password.ts` was\n // written into the user's `backend/`, and a database UPDATE ran for a user\n // named `--help`. A flag whose whole job is to print text cannot be allowed\n // to reach code that writes.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printAuthHelp();\n return;\n }\n\n switch (subcommand) {\n case \"reset-password\":\n await resetPassword(rawArgs);\n break;\n default:\n unknownCommand(subcommand, AUTH_SUBCOMMANDS, \"auth\");\n }\n}\n\n/**\n * The flags `rebase auth reset-password` takes.\n *\n * `-p` was advertised in this command's own help and never declared here, so\n * `arg` — running permissively — pushed it into the positionals and the value\n * *after* it shifted out of reach: anyone following the help set the account's\n * password to the two-character string `-p`. Declared now, and `auth.test.ts`\n * asserts that the help and this spec list the same aliases.\n */\nexport const RESET_PASSWORD_FLAGS = {\n \"--email\": String,\n \"--password\": String,\n \"-e\": \"--email\",\n \"-p\": \"--password\"\n} as const;\n\n/**\n * Which account, and which password, this invocation names.\n *\n * Both may still be absent — the caller reports a missing email — but neither\n * can be a flag. `parseCommandArgs` parses the whole line strictly, so an\n * undeclared flag is an error rather than a positional. That is what stops\n * `rebase auth reset-password bob@example.com --debug` from setting Bob's\n * password to `--debug`, which is the flag the CLI itself prints after every\n * failure as the thing to re-run with.\n *\n * Exported so its tests can drive the real parser rather than a copy of it.\n */\nexport function resolveResetPasswordArgs(rawArgs: string[]): {\n email?: string;\n password?: string;\n} {\n const { flags, positionals } = parseCommandArgs({\n spec: RESET_PASSWORD_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"auth reset-password\",\n maxPositionals: 2\n });\n\n // Both spellings are supported: `<email> [password]` and `--email/--password`.\n return {\n email: flags[\"--email\"] || positionals[0],\n password: flags[\"--password\"] || positionals[1]\n };\n}\n\n/**\n * A password for a reset that was not given one.\n *\n * This used to be a constant, and `--help` printed it as the default. Reset is\n * the documented way back into an account nobody can sign in to — an admin,\n * usually — so the recovery path set every such account to a fixed string that\n * ships inside a public repository and a published npm package, and left it\n * there until somebody remembered to change it.\n *\n * base64url of 18 random bytes: 24 characters, ~144 bits, no shell-quoting\n * hazard, and nothing that reads like a placeholder somebody might keep.\n */\nexport function generatePassword(): string {\n return randomBytes(18).toString(\"base64url\");\n}\n\n/**\n * What a refusing backend said, from its `{ error: { message, code } }` body.\n *\n * The body used to be printed as it came, so a weak password read\n * `{\"error\":{\"message\":\"…\",\"code\":\"…\"}}`. A body that is not the envelope is\n * still shown, since it is the only account of the refusal there is.\n */\nasync function refusalReason(response: Response): Promise<string> {\n const text = await response.text().catch(() => \"\");\n try {\n const parsed: unknown = JSON.parse(text);\n const error = parsed && typeof parsed === \"object\" && \"error\" in parsed ? parsed.error : undefined;\n if (error && typeof error === \"object\" && \"message\" in error && typeof error.message === \"string\") {\n const code = \"code\" in error && typeof error.code === \"string\" ? ` (${error.code})` : \"\";\n return `${error.message}${code}`;\n }\n } catch {\n // Not JSON: the text is the answer.\n }\n return text.trim() || `${response.status} ${response.statusText}`.trim();\n}\n\nasync function resetPassword(rawArgs: string[]): Promise<void> {\n const { email, password: providedPassword } = resolveResetPasswordArgs(rawArgs);\n // Generated once, so both reset paths set and report the same thing.\n const wasGenerated = !providedPassword;\n const newPassword = providedPassword || generatePassword();\n\n if (!email) {\n console.error(chalk.red(\"✗ Email is required.\"));\n console.log(\"\");\n console.log(chalk.gray(\" Usage: rebase auth reset-password <email> [new-password]\"));\n console.log(chalk.gray(\" rebase auth reset-password --email user@example.com --password NewPass123!\"));\n process.exit(1);\n }\n\n const projectRoot = requireProjectRoot();\n\n // 1. Try API-first reset\n // Was a single-key regex, which did not match `export REBASE_SERVICE_KEY=…`\n // and kept a trailing `# comment` in the value. The command then fell\n // through to the direct-database path as though no key were configured.\n const envFile = findEnvFile(projectRoot);\n const envServiceKey: string | undefined = readEnvFile(projectRoot).REBASE_SERVICE_KEY;\n\n let serviceKey = process.env.REBASE_SERVICE_KEY || envServiceKey;\n\n const statePath = path.join(projectRoot, \".rebase\", \"state.json\");\n if (fs.existsSync(statePath)) {\n try {\n const state = JSON.parse(fs.readFileSync(statePath, \"utf8\")) as Record<string, unknown>;\n if (state && typeof state === \"object\" && typeof state.serviceKey === \"string\" && !serviceKey) {\n serviceKey = state.serviceKey;\n }\n } catch {\n // Ignore\n }\n }\n\n // Where the service key may go: a REBASE_BASE_URL the developer named, or\n // this project's backend while the pid that recorded it is alive — see\n // `resolveBackendAddress`. `.rebase/state.json`'s address on its own, and\n // `.rebase-dev-url`, outlive a killed `rebase dev`, and the port they name\n // may be another server's by now. With neither, the reset goes to the\n // database directly.\n const baseUrl = resolveBackendAddress(readEnvFile(projectRoot), projectRoot).url;\n\n if (baseUrl && serviceKey) {\n console.log(\"Trying API-first reset via running backend...\");\n try {\n const finalPass = newPassword;\n const cleanBaseUrl = baseUrl.replace(/\\/+$/, \"\");\n // Not `limit=1`: the search is fuzzy and ordered by role count, so\n // the exact match is not necessarily first — asking for one row can\n // make it unreachable. Ask for a page, then match exactly.\n const searchUrl = `${cleanBaseUrl}/api/admin/users?search=${encodeURIComponent(email)}&limit=50`;\n const searchRes = await fetch(searchUrl, {\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Accept\": \"application/json\"\n }\n });\n if (!searchRes.ok) {\n throw new ApiAnswered(`Failed to list users: ${searchRes.status} ${searchRes.statusText}`);\n }\n const searchData = await searchRes.json() as unknown;\n if (!searchData || typeof searchData !== \"object\") {\n throw new Error(\"Invalid response format from user search API.\");\n }\n\n const matched = selectUserForEmail(searchData, email);\n if (!matched) {\n throw new ApiAnswered(`No user has the email ${email}.`);\n }\n\n const resetUrl = `${cleanBaseUrl}/api/admin/users/${matched.id}/reset-password`;\n const resetRes = await fetch(resetUrl, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n },\n body: JSON.stringify({ password: finalPass })\n });\n\n if (!resetRes.ok) {\n throw new ApiAnswered(`Password reset refused: ${await refusalReason(resetRes)}`);\n }\n\n console.log(\"API reset successful.\");\n console.log(chalk.bold(\" 🔑 Rebase Auth — Reset Password (via API)\"));\n console.log(\"\");\n // The address as stored, not as typed — they differ in case often\n // enough that echoing the input hides which account was touched.\n console.log(` ${chalk.gray(\"Email:\")} ${matched.email}`);\n // Echoed only when we invented it. A password the operator typed\n // is already theirs; printing it again only adds scrollback.\n console.log(` ${chalk.gray(\"Password:\")} ${wasGenerated ? finalPass : \"*\".repeat(finalPass.length)}`);\n console.log(\"\");\n return;\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n // The backend answered and said no — a password too weak, a user\n // it does not have. That answer stands: writing the hash straight\n // into the database instead skipped the strength rule it had just\n // applied, and ended no sessions. Only a backend that could not be\n // reached is a reason to go round it.\n if (err instanceof ApiAnswered) {\n console.error(chalk.red(`✗ ${errMsg}`));\n process.exitCode = 1;\n return;\n }\n console.warn(chalk.yellow(\"API reset failed, falling back to direct database update...\"));\n console.warn(chalk.gray(` Details: ${errMsg}`));\n }\n }\n\n // 2. Direct-DB Fallback\n const backendDir = requireBackendDir(projectRoot);\n const tsxBin = resolveTsx(projectRoot);\n\n if (!tsxBin) {\n exitDependenciesNotInstalled(projectRoot);\n }\n\n // The database the `db` family would use, resolved — and, for a remembered\n // compose container that is stopped, started — the same way. A stock\n // scaffold leaves DATABASE_URL commented out and runs on the managed\n // database, which only exists in a child's environment when something puts\n // it there — without this the script connected with libpq's defaults,\n // localhost:5432 as the OS user. An external DATABASE_URL adds nothing\n // here: the child already reads it.\n let prepared: PreparedDatabase;\n try {\n const { ensureDockerDatabase } = await import(\"./db\");\n await ensureDockerDatabase(projectRoot, rawArgs);\n const { prepareDatabaseEnv } = await import(\"../dev-db/prepare\");\n prepared = await prepareDatabaseEnv(projectRoot, {\n onProgress: (message) => console.log(chalk.gray(` ${message}`))\n });\n } catch (err) {\n console.error(chalk.red(\"✗ Direct database update failed.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n\n // Opened here first, so a database that does not answer gets the banner\n // every other command prints — not the script's raw error and stack — and\n // no script is written for it.\n const { databaseUrlOf } = await import(\"./db\");\n const url = databaseUrlOf(prepared, readEnvFile(projectRoot));\n if (url) {\n const failure = await databaseOpenFailure(url, prepared.database.source);\n if (failure) {\n for (const line of failure) console.error(line);\n process.exit(1);\n }\n }\n\n try {\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n env.REBASE_RESET_EMAIL = email;\n env.REBASE_RESET_PASSWORD = newPassword;\n env.REBASE_ENV_FILE_PATH = envFile || path.join(projectRoot, \".env\");\n Object.assign(env, prepared.env);\n\n const scriptContent = resetPasswordScript(wasGenerated, parseEnvBoolean(process.env.REBASE_DEBUG) === true);\n\n const tmpScriptPath = path.join(backendDir, \".tmp-reset-password.ts\");\n fs.writeFileSync(tmpScriptPath, scriptContent, \"utf-8\");\n\n console.log(\"\");\n console.log(chalk.bold(\" 🔑 Rebase Auth — Reset Password (Direct DB Fallback)\"));\n console.log(\"\");\n console.log(` ${chalk.gray(\"Email:\")} ${email}`);\n console.log(` ${chalk.gray(\"Database:\")} ${prepared.description}`);\n if (!wasGenerated) {\n console.log(` ${chalk.gray(\"Password:\")} ${\"*\".repeat(newPassword.length)}`);\n }\n console.log(\"\");\n\n const child = spawn(tsxBin, [tmpScriptPath], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n\n // The script is written into the user's backend directory, so every\n // exit has to remove it. Without an `error` handler a failed spawn\n // raises an unhandled event, the process dies before `close`, and\n // `.tmp-reset-password.ts` is left behind to be committed.\n const cleanup = () => {\n try { fs.unlinkSync(tmpScriptPath); } catch { /* already gone */ }\n };\n\n return new Promise((resolve) => {\n child.on(\"error\", (err) => {\n cleanup();\n console.error(chalk.red(\"✗ Could not run the reset script.\"));\n console.error(chalk.gray(` ${err.message}`));\n process.exit(1);\n });\n child.on(\"close\", (code) => {\n cleanup();\n if (code !== 0) {\n process.exit(code ?? 1);\n }\n resolve();\n });\n });\n } catch (err) {\n console.error(chalk.red(\"✗ Direct database update failed.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\n/**\n * Why the database the fallback would reset in cannot be opened, as the lines\n * to print — or null when it opens.\n *\n * A stopped database, refused credentials and a database name the server does\n * not have get the boxed banner the other commands print; anything else is one\n * sentence. Either way the password was not reset and no script was written.\n */\nasync function databaseOpenFailure(url: string, source: DevDatabaseSource): Promise<string[] | null> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: url, connectionTimeoutMillis: 10_000 });\n client.on(\"error\", () => undefined);\n try {\n await client.connect();\n await client.query(\"SELECT 1\");\n return null;\n } catch (error) {\n const { connectionErrorText, connectionFailureBanner, connectionRefusedFixes } =\n await import(\"../dev-db/connection-banner\");\n const consequence = \"The password was not reset.\";\n return connectionFailureBanner(url, error, { consequence, fixes: connectionRefusedFixes(source) }) ?? [\n chalk.red(`✗ Could not open the database: ${redactConnectionPasswords(connectionErrorText(error))}`),\n chalk.gray(` ${consequence}`)\n ];\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/**\n * The script the direct-database fallback runs under the project's own tsx, so\n * it resolves the project's `@rebasepro/server-postgres` and schema.\n *\n * It ends the account's sessions in the transaction that sets the password,\n * as every door through the API does (`replaceUserPassword`): the refresh\n * tokens and outstanding reset links go, and `tokens_valid_after` voids the\n * access tokens already handed out. An operator resetting a phished account\n * with the backend down is the case this exists for, and a reset that left the\n * attacker's refresh token minting access tokens did not recover anything.\n *\n * It exits 0 only when a row was updated: a missing user and a thrown error are\n * both exit 1. `echoPassword` prints the new password, for a generated one;\n * `showStack` prints a failure's stack rather than its sentence (`--debug`).\n *\n * Exported so its tests can run it.\n */\nexport function resetPasswordScript(echoPassword: boolean, showStack = false): string {\n return `\nimport { createPostgresDatabaseConnection } from \"@rebasepro/server-postgres\";\nimport { hashPassword } from \"@rebasepro/server\";\nimport { getTableConfig } from \"drizzle-orm/pg-core\";\nimport * as dotenv from \"dotenv\";\nimport path from \"path\";\nimport fs from \"fs\";\n\ndotenv.config({ path: process.env.REBASE_ENV_FILE_PATH, quiet: true });\n\n// Lowercased, as every address is stored (\\`normalizeEmail\\`): matched as\n// typed, \"Ops@Acme.test\" found no row.\nconst email = process.env.REBASE_RESET_EMAIL!.trim().toLowerCase();\nconst newPassword = process.env.REBASE_RESET_PASSWORD!;\n\nconst quote = (identifier: string) => '\"' + identifier.replace(/\"/g, '\"\"') + '\"';\n\nasync function resetPassword() {\n const { pool } = createPostgresDatabaseConnection(process.env.DATABASE_URL!);\n const hash = await hashPassword(newPassword);\n\n let usersTable;\n try {\n const schemaPath = path.resolve(\"./src/schema.generated.ts\");\n if (fs.existsSync(schemaPath)) {\n const schema = await import(\"file://\" + schemaPath);\n usersTable = schema.users || schema.tables?.users;\n }\n } catch (e) {\n // ignore and fallback\n }\n\n if (!usersTable) {\n const pgServer = await import(\"@rebasepro/server-postgres\");\n usersTable = pgServer.users;\n }\n\n // The physical names, from the table object: the collection may map its\n // properties to other columns, and the statements below are plain SQL.\n const { name: tableName, schema: tableSchema } = getTableConfig(usersTable);\n const usersSchema = tableSchema || \"public\";\n const users = quote(usersSchema) + \".\" + quote(tableName);\n const idColumn = quote(usersTable.id.name);\n const emailColumn = quote(usersTable.email.name);\n const passwordColumn = quote((usersTable.passwordHash ?? usersTable.password_hash).name);\n // Where \\`ensureAuthTablesExist\\` puts the tables that hang off the users\n // table: beside it, or in \\`rebase\\` when it lives in \\`public\\`.\n const authSchema = usersSchema === \"public\" ? \"rebase\" : usersSchema;\n\n const client = await pool.connect();\n try {\n // A database nothing has booted against — or a managed one \\`db reset\\`\n // emptied — has no users table, and so no account to reset. Said as\n // that, not as pg's \\`relation … does not exist\\`.\n const usersTable = await client.query(\"SELECT to_regclass($1) IS NOT NULL AS present\", [users]);\n if (!usersTable.rows[0]?.present) {\n console.error(\"✗ \" + users + \" does not exist in this database, so it holds no account to reset.\");\n console.error(\" Nothing was changed. \\`rebase dev\\` creates it the first time it boots against this database.\");\n process.exit(1);\n }\n\n await client.query(\"BEGIN\");\n const updated = await client.query(\n \"UPDATE \" + users + \" SET \" + passwordColumn + \" = $1 WHERE \" + emailColumn + \" = $2 \" +\n \"RETURNING \" + idColumn + \" AS id, \" + emailColumn + \" AS email\",\n [hash, email]\n );\n if (updated.rows.length === 0) {\n await client.query(\"ROLLBACK\");\n // Nothing was updated, so nothing was reset. Exiting 0 here reported\n // success for a no-op, which is what a script would have believed.\n console.error(\"✗ User not found: \" + email);\n process.exit(1);\n }\n const uid = updated.rows[0].id;\n\n // A table or column the server has not created yet (it never booted\n // against this database) holds no session to end.\n const watermark = await client.query(\n \"SELECT 1 FROM information_schema.columns WHERE table_schema = $1 AND table_name = $2 AND column_name = 'tokens_valid_after'\",\n [usersSchema, tableName]\n );\n if (watermark.rows.length > 0) {\n await client.query(\"UPDATE \" + users + \" SET tokens_valid_after = NOW() WHERE \" + idColumn + \" = $1\", [uid]);\n }\n for (const table of [\"refresh_tokens\", \"password_reset_tokens\"]) {\n const qualified = quote(authSchema) + \".\" + quote(table);\n const present = await client.query(\"SELECT to_regclass($1) IS NOT NULL AS present\", [qualified]);\n if (present.rows[0]?.present) {\n await client.query(\"DELETE FROM \" + qualified + \" WHERE uid = $1\", [uid]);\n }\n }\n await client.query(\"COMMIT\");\n\n console.log(\"✅ Password reset for: \" + updated.rows[0].email);\n console.log(\" Every session of this account has ended.\");\n ${echoPassword ? 'console.log(\" Password: \" + newPassword);' : \"\"}\n process.exit(0);\n } catch (error) {\n await client.query(\"ROLLBACK\").catch(() => undefined);\n throw error;\n } finally {\n client.release();\n }\n}\n\n// A thrown error is a failed reset, and exits like one — a refused connection\n// that exits 0 reads as a reset to anything checking the exit code. Said as a\n// sentence: the stack is the script's own, and only --debug asks for it.\nconst describe = (error: unknown): string => {\n if (error instanceof AggregateError && !error.message && error.errors.length > 0) return describe(error.errors[0]);\n const message = error instanceof Error ? error.message : String(error);\n const code = error && typeof error === \"object\" && \"code\" in error && typeof error.code === \"string\" ? error.code : \"\";\n return code && !message.includes(code) ? message + \" (\" + code + \")\" : message;\n};\nresetPassword().catch((error) => {\n ${showStack ? \"console.error(error);\" : \"console.error(\\\"✗ The password was not reset: \\\" + describe(error));\"}\n process.exit(1);\n});\n`;\n}\n\nfunction printAuthHelp() {\n console.log(`\n${chalk.bold(\"rebase auth\")} — Authentication management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase auth ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"reset-password\")} Reset a user's password\n\n${chalk.green.bold(\"reset-password Options\")}\n ${chalk.blue(\"--email, -e\")} User's email address\n ${chalk.blue(\"--password, -p\")} New password (default: one is generated and printed)\n\n${chalk.green.bold(\"Examples\")}\n rebase auth reset-password user@example.com\n rebase auth reset-password --email user@example.com --password MyNewPass!\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,IAAM,cAAN,cAA0B,MAAM,CAAC;;AAGjC,IAAa,mBAAmB,CAAC,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCjD,SAAgB,mBAAmB,SAAkB,OAAyC;CAC1F,MAAM,SAAS,MAAM,KAAK,CAAC,CAAC,YAAY;CACxC,IAAI,CAAC,QAAQ,OAAO,KAAA;CAEpB,MAAM,OAAkB,MAAM,QAAQ,OAAO,IACvC,UACC,WAAW,OAAO,YAAY,YAAY,MAAM,QAAS,QAAgC,KAAK,IAC1F,QAAiC,QAClC,CAAC;CAEX,KAAK,M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