askdb 0.5.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may accept and charge a
167
+ fee for, the acceptance of support, warranty, indemnity, or
168
+ other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Yahya Gilany
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
200
+ implied. See the License for the specific language governing
201
+ permissions and limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,10 @@
1
+ AskDB
2
+ Copyright 2026 Yahya Gilany
3
+
4
+ This product includes software developed by Yahya Gilany and contributors.
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License");
7
+ you may not use this file except in compliance with the License.
8
+ You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
package/README.md ADDED
@@ -0,0 +1,91 @@
1
+ # askdb
2
+
3
+ Command-line frontend for [`@askdb/core`](https://www.npmjs.com/package/@askdb/core). Ask natural-language questions and get validated SQL from the configured dialect.
4
+
5
+ Published on npm as [`askdb`](https://www.npmjs.com/package/askdb) (unscoped); the `askdb` binary name is unchanged.
6
+
7
+ > **Status:** pre-1.0.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pnpm add -g askdb
13
+ # or run without installing:
14
+ pnpm dlx askdb --help
15
+ # e.g. scaffold config:
16
+ pnpm dlx askdb init
17
+ ```
18
+
19
+ The CLI delegates live introspection to AskDB connector packages; each connector owns any database driver it needs.
20
+
21
+ ## Quickstart
22
+
23
+ ```bash
24
+ export OPENAI_API_KEY=sk-...
25
+ askdb ask \
26
+ --schema fixtures/schemas/orders-users.schema \
27
+ --question "How many users signed up last week?"
28
+ ```
29
+
30
+ AskDB returns SQL for review. Run approved SQL outside AskDB under your own database roles, tenant policy, and audit logging.
31
+
32
+ ## Common flags
33
+
34
+ - `--schema <path>` — AskDB Schema v2 directory, bundled JSON, or schema JSON file.
35
+ - `--mode <mode>` — one of the supported modes (see `docs/contracts/modes-v1.md`).
36
+ - `--explain` — emit heuristic guardrail metadata alongside the SQL.
37
+ - `--log-level <level>` — Pino log level (silent, error, warn, info, debug, trace).
38
+
39
+ Run `askdb --help` for the full list.
40
+
41
+ ## Init
42
+
43
+ ```bash
44
+ askdb init
45
+ # writes ./askdb.config.ts only (refuses to overwrite unless --force)
46
+ ```
47
+
48
+ Use `--path` to write the template to a different file. Example `.env` keys and notes live in **comments** inside `askdb.config.ts`; create your own `.env` if you use `env("...")` with `dotenv`.
49
+
50
+ ## Enrichment UIs
51
+
52
+ ```bash
53
+ askdb enrich --schema my-app.schema
54
+ askdb studio --schema my-app.schema
55
+ ```
56
+
57
+ `askdb enrich` opens the terminal UI. `askdb studio` starts a local browser UI for browsing tables, editing Schema v2 enrichment, requesting AI suggestions, and generating sample NL-to-SQL output before shipping the schema.
58
+
59
+ ## Introspection
60
+
61
+ Postgres live and air-gapped introspection:
62
+
63
+ ```bash
64
+ askdb introspect --url "$DATABASE_URL" --out my-app.schema --schema-id my-app
65
+ askdb introspect --from-export ./pg-export-bundle --out my-app.schema --schema-id my-app
66
+ ```
67
+
68
+ Prisma schema-file introspection does not connect to the database:
69
+
70
+ ```bash
71
+ askdb introspect --engine prisma --prisma-schema ./prisma --out my-app.schema
72
+ askdb introspect --engine prisma --prisma-schema ./prisma/schema.prisma --print
73
+ askdb introspect --engine prisma --prisma-schema ./prisma --diff my-app.schema
74
+ ```
75
+
76
+ ## Environment
77
+
78
+ The CLI loads `.env` from the current working directory (via dotenv), then evaluates an optional AskDB config file (`askdb.config.*` or `.config/askdb.*`) via [`@askdb/config`](https://www.npmjs.com/package/@askdb/config) (`bootstrapAskDbEnv`), which installs the **runtime snapshot** used by `getAskDbRuntimeConfig()` — AskDB does **not** copy the full flattened map into `process.env`. Run `askdb init` to create **`askdb.config.ts`** with nested `defineConfig` and `env()` examples; optional `.env` guidance is in comments in that file (no `.env` is generated).
79
+
80
+ `askdb init` **skips** loading config so a broken template never blocks scaffolding.
81
+
82
+ | Variable | Purpose |
83
+ |---|---|
84
+ | `OPENAI_API_KEY` | Default LanguageModel provider key (often set via `askdb.config.ts`). |
85
+ | `ASKDB_SCHEMA_PATH` | Default schema file. |
86
+ | `DATABASE_URL` | Postgres connection string for `askdb introspect --url`. |
87
+ | `ASKDB_MOCK_SQL` | Bypass live model calls in tests/dev. |
88
+
89
+ ## License
90
+
91
+ Apache-2.0 © Yahya Gilany. See [LICENSE](./LICENSE) and [NOTICE](./NOTICE).
package/bin/askdb.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import "../dist/cli.js";
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
package/dist/cli.js ADDED
@@ -0,0 +1,250 @@
1
+ #!/usr/bin/env node
2
+ import { bootstrapAskDbEnv, getAskDbRuntimeConfig } from "@askdb/config";
3
+ import { randomUUID } from "node:crypto";
4
+ import { AskDbError, AskDbLogEvent, SchemaParseError, formatAskDbModesV1, formatSupportedAskDbLogLevels, isSupportedAskDbLogLevel, parseAskDbModeV1, SqlValidationError, ask, askDbAiKeyMissingMessage, createAskDbLanguageModelFromEnv, createAskDbLogger, loadSchema, resolveAskDbAiConfig, } from "@askdb/core";
5
+ import { postgresDialect } from "@askdb/postgres";
6
+ import { Command } from "commander";
7
+ import { runInitCli } from "./init.js";
8
+ import { runIntrospectCli } from "./introspect.js";
9
+ // `askdb init` writes templates and should not require a valid askdb.config.
10
+ if (process.argv[2] !== "init") {
11
+ bootstrapAskDbEnv({ cwd: process.cwd() });
12
+ }
13
+ if (process.argv[2] === "init") {
14
+ process.exit(runInitCli(process.argv.slice(3)));
15
+ }
16
+ if (process.argv[2] === "introspect") {
17
+ const exitCode = await runIntrospectCli(process.argv.slice(3));
18
+ process.exit(exitCode);
19
+ }
20
+ if (process.argv[2] === "enrich") {
21
+ process.exit(await runTuiCommand(process.argv.slice(3)));
22
+ }
23
+ if (process.argv[2] === "studio") {
24
+ process.exit(await runStudioCommand(process.argv.slice(3)));
25
+ }
26
+ if (process.argv[2] === "bundle") {
27
+ process.exit(await runTuiCommand(["bundle", ...process.argv.slice(3)]));
28
+ }
29
+ function printCliError(error) {
30
+ if (error instanceof SqlValidationError) {
31
+ console.error(`${error.name} [${error.rule}]: ${error.message}`);
32
+ if (error.hint) {
33
+ console.error(`Hint: ${error.hint}`);
34
+ }
35
+ return;
36
+ }
37
+ if (error instanceof AskDbError) {
38
+ console.error(`${error.name}: ${error.message}`);
39
+ return;
40
+ }
41
+ if (error instanceof Error) {
42
+ console.error(error.message);
43
+ return;
44
+ }
45
+ console.error(String(error));
46
+ }
47
+ async function runTuiCommand(args) {
48
+ const { runTuiCli } = await import("@askdb/tui");
49
+ return runTuiCli(args);
50
+ }
51
+ async function runStudioCommand(args) {
52
+ const { runStudioCli } = await import("@askdb/studio");
53
+ return runStudioCli(args);
54
+ }
55
+ function formatSchemaPathHint(schemaPath) {
56
+ return `Schema path: ${schemaPath}\nHint: Try \`fixtures/schemas/orders-users.schema/\` (v2 directory) as a known-good example.`;
57
+ }
58
+ function loadSchemaFromPath(schemaPath) {
59
+ try {
60
+ return loadSchema(schemaPath);
61
+ }
62
+ catch (e) {
63
+ const err = e;
64
+ const code = typeof err.code === "string" ? err.code : undefined;
65
+ if (code === "ENOENT") {
66
+ throw new AskDbError(`Schema path not found.\n${formatSchemaPathHint(schemaPath)}`, e);
67
+ }
68
+ if (code === "EACCES") {
69
+ throw new AskDbError(`Schema path is not readable (permission denied).\n${formatSchemaPathHint(schemaPath)}`, e);
70
+ }
71
+ if (e instanceof SchemaParseError) {
72
+ throw new AskDbError(`Failed to parse schema.\n${formatSchemaPathHint(schemaPath)}\nDetails: ${e.message}`, e);
73
+ }
74
+ const msg = e instanceof Error ? e.message : String(e);
75
+ throw new AskDbError(`Failed to load schema.\n${formatSchemaPathHint(schemaPath)}\nDetails: ${msg}`, e);
76
+ }
77
+ }
78
+ const SENSITIVE_SQL_WARNING_EVENT = "askdb.pipeline.sensitive_sql_warning";
79
+ function escapeRegExp(s) {
80
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
81
+ }
82
+ function findSensitiveReferencesInSql(sql, schema) {
83
+ const lower = sql.toLowerCase();
84
+ const refs = [];
85
+ for (const t of schema.tables) {
86
+ for (const c of t.columns) {
87
+ if (!t.sensitive && !c.sensitive)
88
+ continue;
89
+ const col = c.name.toLowerCase();
90
+ const table = t.name.toLowerCase();
91
+ const qualified = new RegExp(`\\b${escapeRegExp(table)}\\s*\\.\\s*${escapeRegExp(col)}\\b`, "i");
92
+ const unqualified = new RegExp(`\\b${escapeRegExp(col)}\\b`, "i");
93
+ if (qualified.test(lower) || unqualified.test(lower)) {
94
+ refs.push({ table: t.name, column: c.name });
95
+ }
96
+ }
97
+ }
98
+ const seen = new Set();
99
+ return refs.filter((r) => {
100
+ const k = `${r.table}.${r.column}`.toLowerCase();
101
+ if (seen.has(k))
102
+ return false;
103
+ seen.add(k);
104
+ return true;
105
+ });
106
+ }
107
+ function resolveAskDbLogLevel(opts) {
108
+ if (opts.logLevel !== undefined && opts.logLevel !== "") {
109
+ const l = opts.logLevel.toLowerCase();
110
+ if (!isSupportedAskDbLogLevel(l)) {
111
+ throw new Error(`Invalid --log-level: ${opts.logLevel} (expected one of ${formatSupportedAskDbLogLevels()})`);
112
+ }
113
+ return l;
114
+ }
115
+ const env = getAskDbRuntimeConfig().logging.level?.toLowerCase();
116
+ if (env && isSupportedAskDbLogLevel(env)) {
117
+ return env;
118
+ }
119
+ if (opts.verbose) {
120
+ return "info";
121
+ }
122
+ if (opts.logFile || opts.logStdout) {
123
+ return "info";
124
+ }
125
+ return "silent";
126
+ }
127
+ const program = new Command();
128
+ program.name("askdb").description("AskDB — natural language → PostgreSQL SELECT");
129
+ program
130
+ .command("init")
131
+ .description("Create askdb.config.ts (nested defineConfig + env() examples; .env guidance in comments only)")
132
+ .option("-f, --force", "Overwrite an existing file", false)
133
+ .option("--path <path>", "Output path for askdb.config.ts", "askdb.config.ts")
134
+ .action((opts) => {
135
+ const args = [];
136
+ if (opts.force)
137
+ args.push("--force");
138
+ if (opts.path && opts.path !== "askdb.config.ts")
139
+ args.push("--path", opts.path);
140
+ process.exit(runInitCli(args));
141
+ });
142
+ program
143
+ .command("enrich")
144
+ .description("Open the terminal UI for Schema v2 enrichment")
145
+ .allowUnknownOption(true);
146
+ program
147
+ .command("studio")
148
+ .description("Start the local browser UI for Schema v2 enrichment")
149
+ .allowUnknownOption(true);
150
+ program
151
+ .command("bundle")
152
+ .description("Bundle a Schema v2 directory into a single JSON file")
153
+ .allowUnknownOption(true);
154
+ program
155
+ .command("ask")
156
+ .description("Generate SQL from schema + question")
157
+ .requiredOption("-s, --schema <path>", "Path to AskDB Schema v2 directory, bundled JSON, or schema.json")
158
+ .requiredOption("-q, --question <text>", "Natural language question")
159
+ .option("--explain", "After SQL, print a JSON block describing heuristic guardrails satisfied (Phase 2 explainability)", false)
160
+ .option("-v, --verbose", "Emit structured JSON logs (info) to stderr", false)
161
+ .option("--log-level <level>", "Structured log level (trace|debug|info|warn|error|fatal|silent)")
162
+ .option("--log-file <path>", "Append structured JSON logs to this file")
163
+ .option("--log-stdout", "Mirror structured JSON logs to stdout", false)
164
+ .option("--correlation-id <id>", "Correlation ID for logs (overrides ASKDB_CORRELATION_ID)")
165
+ .option("--mock-sql <sql>", "Deterministic NL→SQL for tests (bypasses live model call). Also via ASKDB_MOCK_SQL.")
166
+ .option("--mode <id>", `Operating mode (${formatAskDbModesV1()}); default schema_only. Override with ASKDB_MODE`)
167
+ .option("--omit-sensitive-from-prompt", "Omit sensitive column/table names from NL→SQL DDL (default: include names, tagged as sensitive)", false)
168
+ .action(async (opts) => {
169
+ let logLevel;
170
+ let mode;
171
+ const runtime = getAskDbRuntimeConfig();
172
+ try {
173
+ logLevel = resolveAskDbLogLevel(opts);
174
+ mode = parseAskDbModeV1(opts.mode ?? runtime.modes.askdbMode);
175
+ }
176
+ catch (e) {
177
+ printCliError(e);
178
+ process.exitCode = 1;
179
+ return;
180
+ }
181
+ const correlationId = opts.correlationId ?? runtime.logging.correlationId ?? randomUUID();
182
+ const logger = createAskDbLogger({
183
+ correlationId,
184
+ level: logLevel,
185
+ logFile: opts.logFile ?? runtime.logging.logFile,
186
+ logStdout: opts.logStdout ?? runtime.logging.logStdout,
187
+ });
188
+ const mockSql = opts.mockSql ?? runtime.dev.mockSql;
189
+ const aiConfig = mockSql ? undefined : resolveAskDbAiConfig(runtime.ai.aiEnv);
190
+ if (!mockSql && !aiConfig) {
191
+ console.error(askDbAiKeyMissingMessage("NL→SQL generation"));
192
+ console.error("Tip: in tests, set ASKDB_MOCK_SQL to bypass live model calls.");
193
+ process.exitCode = 1;
194
+ return;
195
+ }
196
+ logger.info({
197
+ event: AskDbLogEvent.RunStart,
198
+ mode,
199
+ }, "askdb run start");
200
+ try {
201
+ const schema = loadSchemaFromPath(opts.schema);
202
+ const model = mockSql
203
+ ? // The model won't be used when `deps.generateText` is overridden.
204
+ undefined
205
+ : (await createAskDbLanguageModelFromEnv(runtime.ai.aiEnv));
206
+ const omitSensitiveFromPrompt = Boolean(opts.omitSensitiveFromPrompt) || runtime.modes.omitSensitiveFromPrompt;
207
+ const out = await ask({
208
+ question: opts.question,
209
+ schema,
210
+ model,
211
+ dialect: postgresDialect,
212
+ logger,
213
+ mode,
214
+ explain: Boolean(opts.explain),
215
+ omitSensitiveIdentifiersFromNlToSqlPrompt: omitSensitiveFromPrompt,
216
+ deps: mockSql !== undefined
217
+ ? {
218
+ // `ai.generateText` has a rich return type; for test-mode we only need `text`.
219
+ generateText: (async () => ({ text: mockSql })),
220
+ }
221
+ : undefined,
222
+ });
223
+ const sensitiveRefs = findSensitiveReferencesInSql(out.sql, schema);
224
+ if (sensitiveRefs.length > 0) {
225
+ const cols = sensitiveRefs.map((r) => `${r.table}.${r.column}`);
226
+ logger.info({
227
+ event: SENSITIVE_SQL_WARNING_EVENT,
228
+ sensitiveColumnCount: cols.length,
229
+ sensitiveColumns: cols,
230
+ }, "generated SQL references sensitive identifiers");
231
+ console.error(`Warning: generated SQL references sensitive columns: ${cols.join(", ")}\n` +
232
+ "Review carefully before sharing or running this SQL outside AskDB.");
233
+ }
234
+ console.log("-- sql --");
235
+ console.log(`${out.sql};`);
236
+ if (opts.explain) {
237
+ console.log("-- explain --");
238
+ console.log(JSON.stringify(out.explain ?? null, null, 2));
239
+ }
240
+ logger.info({ event: AskDbLogEvent.RunEnd, ok: true }, "askdb run end");
241
+ }
242
+ catch (error) {
243
+ const msg = error instanceof Error ? error.message : String(error);
244
+ logger.error({ event: AskDbLogEvent.RunError, errMessage: msg }, "askdb run error");
245
+ printCliError(error);
246
+ process.exitCode = 1;
247
+ }
248
+ });
249
+ await program.parseAsync(process.argv);
250
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AACzE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACL,UAAU,EACV,aAAa,EAIb,gBAAgB,EAChB,kBAAkB,EAClB,6BAA6B,EAC7B,wBAAwB,EACxB,gBAAgB,EAChB,kBAAkB,EAClB,GAAG,EACH,wBAAwB,EACxB,+BAA+B,EAC/B,iBAAiB,EACjB,UAAU,EACV,oBAAoB,GACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnD,6EAA6E;AAC7E,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,CAAC;IAC/B,iBAAiB,CAAC,EA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":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AA6HA,wBAAgB,UAAU,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CA4C1D"}
package/dist/init.js ADDED
@@ -0,0 +1,194 @@
1
+ import { existsSync, writeFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ const DEFAULT_CONFIG_PATH = "askdb.config.ts";
4
+ /**
5
+ * Single template: only `askdb.config.ts` is written. Guidance that used to live in a generated
6
+ * `.env` file lives in comments here. Use `env("NAME")` for any variable from a local `.env`
7
+ * (when loaded via `import "dotenv/config"`) or from the process environment.
8
+ */
9
+ const CONFIG_TEMPLATE = `import "dotenv/config";
10
+ import { defineConfig, env, type AskDbConfig } from "@askdb/config";
11
+
12
+ /**
13
+ * Nested AskDB configuration (grouped like Prisma's \`defineConfig\`).
14
+ *
15
+ * \`import "dotenv/config"\` loads a local \`.env\` when this file is evaluated (missing file is OK).
16
+ * First-party CLIs call \`bootstrapAskDbEnv\`, which loads \`.env\` then evaluates this file and installs the AskDB runtime snapshot.
17
+ *
18
+ * Use \`env("VAR")\` for values read from the environment (shell or \`.env\`). Missing values are OK at
19
+ * file load time; \`flattenAskDbConfig\` applies documented defaults for optional fields.
20
+ *
21
+ * \`satisfies AskDbConfig\` validates the nested shape at compile time.
22
+ *
23
+ * ---------------------------------------------------------------------------
24
+ * Optional \`.env\` (not generated by \`askdb init\`) — example keys you can set:
25
+ * ---------------------------------------------------------------------------
26
+ *
27
+ * # Local secrets (do not commit \`.env\`).
28
+ *
29
+ * # --- AI (OpenAI-compatible) ---
30
+ * # Required for live NL→SQL unless you use ASKDB_MOCK_SQL in tests.
31
+ * MY_OPENAI_API_KEY=
32
+ * # MY_OPENAI_BASE_URL=
33
+ *
34
+ * # Chat model id — optional; defaults are applied when unset (see \`@askdb/config\` / flattenAskDbConfig).
35
+ * MY_CHAT_MODEL=gpt-4o-mini
36
+ *
37
+ * # --- Postgres (live DB URL for introspection + connectors) ---
38
+ * MY_DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/postgres
39
+ * #
40
+ * # Pagila dev fixture (docker compose -f fixtures/pagila/docker-compose.yml up --build -d → port 5433):
41
+ * # MY_DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5433/pagila
42
+ *
43
+ * # Default Schema v2 output for \`askdb introspect\` when you omit --out (maps to ASKDB_INTROSPECT_OUT)
44
+ * MY_INTROSPECT_OUTPUT_DIR=./askdb/
45
+ *
46
+ * # Optional: different URL for introspection only — add in this file, e.g.
47
+ * # introspection.providerConfig.postgres.databaseUrl: env("MY_INTROSPECT_DATABASE_URL")
48
+ * # MY_INTROSPECT_DATABASE_URL=
49
+ *
50
+ * # --- Prisma schema-file introspection (optional) ---
51
+ * # When using \`askdb introspect --engine prisma\`, add a prisma branch below and e.g. env("MY_PRISMA_SCHEMA").
52
+ * # MY_PRISMA_SCHEMA=./prisma
53
+ *
54
+ * # --- RAG (optional; defaults below are mock embedder + in-memory store) ---
55
+ * # MY_RAG_EMBEDDER=mock
56
+ * # MY_PGVECTOR_URL=postgres://postgres:postgres@127.0.0.1:5434/askdb_rag
57
+ *
58
+ * # --- Logging / modes (optional) ---
59
+ * # MY_ASKDB_LOG_LEVEL=info
60
+ * # MY_ASKDB_CORRELATION_ID=
61
+ * # MY_ASKDB_MODE=schema_only # schema_only | bounded_results
62
+ * # MY_ASKDB_OMIT_SENSITIVE_FROM_PROMPT=true
63
+ *
64
+ * # --- Host defaults (optional) ---
65
+ * # MY_ASKDB_SCHEMA_PATH=fixtures/schemas/orders-users.schema
66
+ *
67
+ * You can rename keys freely — update the \`env("...")\` calls to match.
68
+ *
69
+ * For Postgres introspection, omit \`introspection.providerConfig.postgres.databaseUrl\` to reuse
70
+ * \`database.providerConfig.postgres.databaseUrl\` as \`DATABASE_URL\`.
71
+ */
72
+ export default defineConfig({
73
+ ai: {
74
+ // openai | azure | foundry (foundry maps to Azure-compatible env vars)
75
+ provider: "openai",
76
+ providerConfig: {
77
+ openai: {
78
+ // Optional until live NL→SQL; then use env("MY_OPENAI_API_KEY") or your own key name.
79
+ apiKey: "",
80
+ model: env("MY_CHAT_MODEL"),
81
+ },
82
+ },
83
+ },
84
+
85
+ database: {
86
+ // postgres (more dialects later)
87
+ provider: "postgres",
88
+ providerConfig: {
89
+ postgres: {
90
+ databaseUrl: env("MY_DATABASE_URL"),
91
+ },
92
+ },
93
+ },
94
+
95
+ introspection: {
96
+ // postgres | prisma
97
+ provider: "postgres",
98
+ providerConfig: {
99
+ postgres: {
100
+ // Omit databaseUrl to reuse database.providerConfig.postgres.databaseUrl (see flattenAskDbConfig).
101
+ },
102
+ },
103
+ outputDir: env("MY_INTROSPECT_OUTPUT_DIR"),
104
+ },
105
+
106
+ rag: {
107
+ // mock | openai | ai-sdk
108
+ embedder: "mock",
109
+ embedderConfig: {},
110
+ // file | memory | pgvector
111
+ store: "memory",
112
+ storeConfig: {
113
+ memory: {},
114
+ },
115
+ },
116
+ } satisfies AskDbConfig);
117
+ `;
118
+ export function runInitCli(argv) {
119
+ let opts;
120
+ try {
121
+ opts = parseOptions(argv);
122
+ }
123
+ catch (e) {
124
+ const msg = e instanceof Error ? e.message : String(e);
125
+ process.stderr.write(`${msg}\n`);
126
+ return 1;
127
+ }
128
+ if (opts.path === "--help" || opts.path === "-h") {
129
+ printHelp();
130
+ return 0;
131
+ }
132
+ const configTarget = resolve(process.cwd(), opts.path);
133
+ if (existsSync(configTarget) && !opts.force) {
134
+ process.stderr.write(`Refusing to overwrite existing file:\n` +
135
+ ` - ${configTarget}\n` +
136
+ `Use \`askdb init --force\` to overwrite.\n`);
137
+ return 1;
138
+ }
139
+ try {
140
+ writeFileSync(configTarget, CONFIG_TEMPLATE, { encoding: "utf8" });
141
+ }
142
+ catch (e) {
143
+ const msg = e instanceof Error ? e.message : String(e);
144
+ process.stderr.write(`Failed to write init template: ${msg}\n`);
145
+ return 1;
146
+ }
147
+ process.stdout.write(`Wrote:\n` +
148
+ ` - ${configTarget}\n` +
149
+ "Next steps:\n" +
150
+ " 1. Create a `.env` (optional) or export variables to match the `env(\"...\")` calls in this file — see the header comment for examples.\n" +
151
+ " 2. For live NL→SQL, set an OpenAI-compatible key (or use ASKDB_MOCK_SQL in tests).\n" +
152
+ " 3. For a Schema v2 directory from Postgres/Prisma: `askdb introspect ...` (see --help). With MY_INTROSPECT_OUTPUT_DIR / ASKDB_INTROSPECT_OUT you can omit `--out` when a default output dir is set.\n" +
153
+ " 4. With an existing schema artifact: `askdb ask --schema <path> --question \"...\"`.\n");
154
+ return 0;
155
+ }
156
+ function parseOptions(argv) {
157
+ const opts = { force: false, path: DEFAULT_CONFIG_PATH };
158
+ for (let i = 0; i < argv.length; i += 1) {
159
+ const arg = argv[i];
160
+ switch (arg) {
161
+ case "--force":
162
+ case "-f":
163
+ opts.force = true;
164
+ break;
165
+ case "--path": {
166
+ const value = argv[++i];
167
+ if (!value || value.startsWith("--")) {
168
+ throw new Error(`${arg} requires a value.`);
169
+ }
170
+ opts.path = value;
171
+ break;
172
+ }
173
+ case "--help":
174
+ case "-h":
175
+ opts.path = "--help";
176
+ return opts;
177
+ default:
178
+ throw new Error(`Unknown option: ${arg}`);
179
+ }
180
+ }
181
+ return opts;
182
+ }
183
+ function printHelp() {
184
+ process.stdout.write([
185
+ "askdb init - Create askdb.config.ts (nested defineConfig template with env() examples and .env guidance in comments)",
186
+ "",
187
+ "Usage:",
188
+ " askdb init Create ./askdb.config.ts (refuses to overwrite unless --force)",
189
+ " askdb init --force Overwrite an existing askdb.config.ts",
190
+ " askdb init --path <file> Write the template to a custom file path",
191
+ "",
192
+ ].join("\n"));
193
+ }
194
+ //# sourceMappingURL=init.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.js","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEp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ACrB,OAAO,IAAI,CAAC;YACd;gBACE,MAAM,IAAI,KAAK,CAAC,mBAAmB,GAAG,EAAE,CAAC,CAAC;QAC9C,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,SAAS;IAChB,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB;QACE,sHAAsH;QACtH,EAAE;QACF,QAAQ;QACR,gGAAgG;QAChG,uEAAuE;QACvE,0EAA0E;QAC1E,EAAE;KACH,CAAC,IAAI,CAAC,IAAI,CAAC,CACb,CAAC;AACJ,CAAC"}
@@ -0,0 +1,2 @@
1
+ export declare function runIntrospectCli(argv: readonly string[]): Promise<number>;
2
+ //# sourceMappingURL=introspect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"introspect.d.ts","sourceRoot":"","sources":["../src/introspect.ts"],"names":[],"mappings":"AAiDA,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAkB/E"}
@@ -0,0 +1,331 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { basename, join } from "node:path";
4
+ import { createAskDbLogger, formatSupportedAskDbLogLevels, isSupportedAskDbLogLevel, } from "@askdb/core";
5
+ import { getAskDbRuntimeConfig } from "@askdb/config";
6
+ import { introspect, toV2SchemaJson, } from "@askdb/introspect";
7
+ import { createPostgresConnector, createPostgresCatalogQueryRunner, } from "@askdb/postgres";
8
+ import { createPrismaConnector } from "@askdb/prisma";
9
+ const INTROSPECT_EVENTS = {
10
+ started: "askdb.introspect.started",
11
+ completed: "askdb.introspect.completed",
12
+ warning: "askdb.introspect.warning",
13
+ error: "askdb.introspect.error",
14
+ };
15
+ export async function runIntrospectCli(argv) {
16
+ try {
17
+ if (argv.includes("--version") || argv.includes("-V")) {
18
+ process.stdout.write(`${readPackageVersion()}\n`);
19
+ return 0;
20
+ }
21
+ if (argv.length === 0 || argv.includes("--help") || argv.includes("-h")) {
22
+ printHelp();
23
+ return 0;
24
+ }
25
+ if (argv[0] === "templates") {
26
+ return runTemplatesCommand(argv.slice(1));
27
+ }
28
+ return await runIntrospectCommand(argv);
29
+ }
30
+ catch (error) {
31
+ process.stderr.write(`${formatError(error)}\n`);
32
+ return 1;
33
+ }
34
+ }
35
+ function runTemplatesCommand(argv) {
36
+ const opts = parseOptions(argv);
37
+ const engine = resolveEngine(opts.engine);
38
+ if (engine === "prisma") {
39
+ throw new Error("Prisma introspection reads schema files and does not provide SQL templates.");
40
+ }
41
+ const bundle = createPostgresConnector().templates();
42
+ const body = bundle.templates
43
+ .map((tpl) => [`-- ${tpl.name}`, tpl.sql, ""].join("\n"))
44
+ .join("\n");
45
+ process.stdout.write(body);
46
+ return 0;
47
+ }
48
+ async function runIntrospectCommand(argv) {
49
+ const opts = parseOptions(argv);
50
+ const engine = resolveEngine(opts.engine);
51
+ const rt = getAskDbRuntimeConfig();
52
+ const envMap = rt.ai.aiEnv;
53
+ if (engine === "postgres" && !opts.url && !opts.fromExport) {
54
+ const dbUrl = envMap.DATABASE_URL?.trim();
55
+ if (dbUrl) {
56
+ opts.url = dbUrl;
57
+ }
58
+ else {
59
+ throw new Error("Provide either --url <postgres-url> or --from-export <bundle-dir>.");
60
+ }
61
+ }
62
+ if (engine === "postgres" && opts.prismaSchema) {
63
+ throw new Error("Use --prisma-schema only with --engine prisma.");
64
+ }
65
+ if (engine === "prisma" && !opts.prismaSchema) {
66
+ const fromRt = envMap.ASKDB_PRISMA_SCHEMA?.trim();
67
+ if (fromRt) {
68
+ opts.prismaSchema = fromRt;
69
+ }
70
+ }
71
+ if (engine === "prisma" && !opts.prismaSchema) {
72
+ throw new Error("Provide --prisma-schema <schema.prisma|schema-dir> with --engine prisma, or set ASKDB_PRISMA_SCHEMA.");
73
+ }
74
+ if (engine === "prisma" && (opts.url || opts.fromExport)) {
75
+ throw new Error("Use --prisma-schema with --engine prisma, not --url or --from-export.");
76
+ }
77
+ if (opts.url && opts.fromExport) {
78
+ throw new Error("Use only one input mode: --url or --from-export.");
79
+ }
80
+ if (!opts.print && !opts.diff && !opts.out) {
81
+ const fromRt = envMap.ASKDB_INTROSPECT_OUT?.trim();
82
+ if (fromRt) {
83
+ opts.out = fromRt;
84
+ }
85
+ }
86
+ if (!opts.print && !opts.diff && !opts.out) {
87
+ throw new Error("Provide one output mode: --out <dir>, --print, or --diff <existing-dir> (or set ASKDB_INTROSPECT_OUT to default --out).");
88
+ }
89
+ if ([opts.print, Boolean(opts.diff), Boolean(opts.out)].filter(Boolean).length > 1) {
90
+ throw new Error("Use only one output mode: --out, --print, or --diff.");
91
+ }
92
+ const schemaId = opts.schemaId ?? inferSchemaId(opts.out ?? opts.diff) ?? "introspected";
93
+ const logLevel = resolveLogLevel(opts, rt);
94
+ const correlationId = opts.correlationId ?? rt.logging.correlationId ?? randomUUID();
95
+ const logger = createAskDbLogger({
96
+ correlationId,
97
+ level: logLevel,
98
+ logFile: opts.logFile ?? rt.logging.logFile,
99
+ logStdout: opts.logStdout ?? rt.logging.logStdout,
100
+ });
101
+ const runConfig = buildRunConfig(opts, engine, schemaId);
102
+ logger.info({
103
+ event: INTROSPECT_EVENTS.started,
104
+ mode: runConfig.mode,
105
+ engine,
106
+ schemaId,
107
+ outputMode: opts.print ? "print" : opts.diff ? "diff" : "out",
108
+ }, "askdb introspection started");
109
+ try {
110
+ const result = await runWithOutput(runConfig, opts, schemaId);
111
+ for (const warning of result.warnings) {
112
+ logger.info({ event: INTROSPECT_EVENTS.warning, warning }, "askdb introspection warning");
113
+ }
114
+ logger.info({
115
+ event: INTROSPECT_EVENTS.completed,
116
+ ok: true,
117
+ warningCount: result.warnings.length,
118
+ isEmpty: result.isEmpty,
119
+ }, "askdb introspection completed");
120
+ return 0;
121
+ }
122
+ catch (error) {
123
+ logger.error({ event: INTROSPECT_EVENTS.error, errMessage: formatError(error) }, "askdb introspection failed");
124
+ throw error;
125
+ }
126
+ }
127
+ async function runWithOutput(runConfig, opts, schemaId) {
128
+ if (opts.print) {
129
+ const result = await introspect(runConfig.input, undefined, {
130
+ connector: runConfig.connector,
131
+ });
132
+ process.stdout.write(`${JSON.stringify(toV2SchemaJson(result.schema, schemaId), null, 2)}\n`);
133
+ return result;
134
+ }
135
+ if (opts.diff) {
136
+ const result = await introspect(runConfig.input, undefined, {
137
+ connector: runConfig.connector,
138
+ });
139
+ const generated = `${JSON.stringify(toV2SchemaJson(result.schema, schemaId), null, 2)}\n`;
140
+ const existingPath = join(opts.diff, "schema.json");
141
+ const existing = existsSync(existingPath) ? readFileSync(existingPath, "utf8") : "";
142
+ process.stdout.write(`${JSON.stringify({ changed: generated !== existing, schemaJsonPath: existingPath }, null, 2)}\n`);
143
+ return result;
144
+ }
145
+ const outDir = opts.out;
146
+ return introspect(runConfig.input, {
147
+ outDir,
148
+ schemaId,
149
+ existingArtifactDir: existsSync(join(outDir, "schema.json")) ? outDir : undefined,
150
+ }, { connector: runConfig.connector });
151
+ }
152
+ function buildRunConfig(opts, engine, schemaId) {
153
+ if (engine === "prisma") {
154
+ return {
155
+ mode: "prisma-schema",
156
+ input: {
157
+ schemaPath: opts.prismaSchema,
158
+ schemaId,
159
+ filters: buildFilters(opts),
160
+ },
161
+ connector: createPrismaConnector(),
162
+ };
163
+ }
164
+ const filters = buildFilters(opts);
165
+ if (opts.fromExport) {
166
+ return {
167
+ mode: "from-export",
168
+ input: { mode: "from-export", bundlePath: opts.fromExport, filters },
169
+ connector: createPostgresConnector(),
170
+ };
171
+ }
172
+ return {
173
+ mode: "live",
174
+ input: {
175
+ mode: "live",
176
+ runner: createPostgresCatalogQueryRunner(opts.url),
177
+ filters,
178
+ },
179
+ connector: createPostgresConnector(),
180
+ };
181
+ }
182
+ function buildFilters(opts) {
183
+ const filters = {};
184
+ if (opts.schemas)
185
+ filters.schemas = opts.schemas;
186
+ if (opts.excludeSchemas)
187
+ filters.excludeSchemas = opts.excludeSchemas;
188
+ if (opts.tables)
189
+ filters.tables = opts.tables;
190
+ return Object.keys(filters).length > 0 ? filters : undefined;
191
+ }
192
+ function parseOptions(argv) {
193
+ const opts = {};
194
+ for (let i = 0; i < argv.length; i += 1) {
195
+ const arg = argv[i];
196
+ switch (arg) {
197
+ case "--url":
198
+ opts.url = readValue(argv, ++i, arg);
199
+ break;
200
+ case "--from-export":
201
+ opts.fromExport = readValue(argv, ++i, arg);
202
+ break;
203
+ case "--prisma-schema":
204
+ opts.prismaSchema = readValue(argv, ++i, arg);
205
+ break;
206
+ case "--out":
207
+ opts.out = readValue(argv, ++i, arg);
208
+ break;
209
+ case "--print":
210
+ opts.print = true;
211
+ break;
212
+ case "--diff":
213
+ opts.diff = readValue(argv, ++i, arg);
214
+ break;
215
+ case "--engine":
216
+ opts.engine = readValue(argv, ++i, arg);
217
+ break;
218
+ case "--schema-id":
219
+ opts.schemaId = readValue(argv, ++i, arg);
220
+ break;
221
+ case "--schemas":
222
+ opts.schemas = parseList(readValue(argv, ++i, arg));
223
+ break;
224
+ case "--exclude-schemas":
225
+ opts.excludeSchemas = parseList(readValue(argv, ++i, arg));
226
+ break;
227
+ case "--tables":
228
+ opts.tables = [...(opts.tables ?? []), ...parseList(readValue(argv, ++i, arg))];
229
+ break;
230
+ case "-v":
231
+ case "--verbose":
232
+ opts.verbose = true;
233
+ break;
234
+ case "--log-level":
235
+ opts.logLevel = readValue(argv, ++i, arg);
236
+ break;
237
+ case "--log-file":
238
+ opts.logFile = readValue(argv, ++i, arg);
239
+ break;
240
+ case "--log-stdout":
241
+ opts.logStdout = true;
242
+ break;
243
+ case "--correlation-id":
244
+ opts.correlationId = readValue(argv, ++i, arg);
245
+ break;
246
+ default:
247
+ throw new Error(`Unknown option: ${arg}`);
248
+ }
249
+ }
250
+ return opts;
251
+ }
252
+ function readValue(argv, index, flag) {
253
+ const value = argv[index];
254
+ if (!value || value.startsWith("--")) {
255
+ throw new Error(`${flag} requires a value.`);
256
+ }
257
+ return value;
258
+ }
259
+ function parseList(value) {
260
+ return value
261
+ .split(",")
262
+ .map((part) => part.trim())
263
+ .filter(Boolean);
264
+ }
265
+ function resolveEngine(engine = "postgres") {
266
+ if (engine === "postgres" || engine === "prisma") {
267
+ return engine;
268
+ }
269
+ throw new Error(`Unsupported introspection engine '${engine}' (expected 'postgres' or 'prisma').`);
270
+ }
271
+ function inferSchemaId(path) {
272
+ if (!path)
273
+ return undefined;
274
+ const name = basename(path);
275
+ return name.endsWith(".schema") ? name.slice(0, -".schema".length) : name;
276
+ }
277
+ function resolveLogLevel(opts, rt) {
278
+ if (opts.logLevel !== undefined && opts.logLevel !== "") {
279
+ const level = opts.logLevel.toLowerCase();
280
+ if (!isSupportedAskDbLogLevel(level)) {
281
+ throw new Error(`Invalid --log-level: ${opts.logLevel} (expected one of ${formatSupportedAskDbLogLevels()})`);
282
+ }
283
+ return level;
284
+ }
285
+ const env = rt.logging.level?.toLowerCase();
286
+ if (env && isSupportedAskDbLogLevel(env))
287
+ return env;
288
+ if (opts.verbose || opts.logFile || opts.logStdout)
289
+ return "info";
290
+ return "silent";
291
+ }
292
+ function readPackageVersion() {
293
+ const pkgPath = new URL("../package.json", import.meta.url);
294
+ const parsed = JSON.parse(readFileSync(pkgPath, "utf8"));
295
+ return typeof parsed.version === "string" ? parsed.version : "0.0.0";
296
+ }
297
+ function printHelp() {
298
+ process.stdout.write([
299
+ "askdb introspect - Schema introspection for AskDB",
300
+ "",
301
+ "Usage:",
302
+ " askdb introspect --out <dir> (uses DATABASE_URL from env/.env)",
303
+ " askdb introspect --url <postgres-url> --out <dir>",
304
+ " askdb introspect --from-export <bundle-dir> --out <dir>",
305
+ " askdb introspect --engine prisma --prisma-schema <schema.prisma|schema-dir> --out <dir>",
306
+ " askdb introspect --engine prisma --prisma-schema <schema.prisma|schema-dir> --print",
307
+ " askdb introspect --engine prisma --prisma-schema <schema.prisma|schema-dir> --diff <existing-dir>",
308
+ " askdb introspect --from-export <bundle-dir> --print",
309
+ " askdb introspect --from-export <bundle-dir> --diff <existing-dir>",
310
+ " askdb introspect templates --engine postgres",
311
+ "",
312
+ "Defaults (after askdb.config bootstrap):",
313
+ " ASKDB_INTROSPECT_OUT Used as --out when you omit --out, --print, and --diff.",
314
+ " ASKDB_PRISMA_SCHEMA Used as --prisma-schema when --engine prisma and the flag is omitted.",
315
+ "",
316
+ "Options:",
317
+ " --schema-id <id>",
318
+ " --prisma-schema <schema.prisma|schema-dir>",
319
+ " --schemas <a,b>",
320
+ " --exclude-schemas <a,b>",
321
+ " --tables <glob[,glob]>",
322
+ " --log-level <level>",
323
+ " --log-file <path>",
324
+ " --correlation-id <id>",
325
+ "",
326
+ ].join("\n"));
327
+ }
328
+ function formatError(error) {
329
+ return error instanceof Error ? error.message : String(error);
330
+ }
331
+ //# sourceMappingURL=introspect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"introspect.js","sourceRoot":"","sources":["../src/introspect.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EACL,iBAAiB,EACjB,6BAA6B,EAC7B,wBAAwB,GAEzB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAEL,UAAU,EACV,cAAc,GAGf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,uBAAuB,EACvB,gCAAgC,GACjC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAEtD,MAAM,iBAAiB,GAAG;IACxB,OAAO,EAAE,0BAA0B;IACnC,SAAS,EAAE,4BAA4B;IACvC,OAAO,EAAE,0BAA0B;IACnC,KAAK,EAAE,wBAAwB;CACvB,CAAC;AAqBX,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,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,OAAO,OAAO,MAAM,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC;AACvE,CAAC;AAED,SAAS,SAAS;IAChB,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB;QACE,mDAAmD;QACnD,EAAE;QACF,QAAQ;QACR,yFAAyF;QACzF,qDAAqD;QACrD,2DAA2D;QAC3D,2FAA2F;QAC3F,uFAAuF;QACvF,qGAAqG;QACrG,uDAAuD;QACvD,qEAAqE;QACrE,gDAAgD;QAChD,EAAE;QACF,0CAA0C;QAC1C,iFAAiF;QACjF,+FAA+F;QAC/F,EAAE;QACF,UAAU;QACV,oBAAoB;QACpB,8CAA8C;QAC9C,mBAAmB;QACnB,2BAA2B;QAC3B,0BAA0B;QAC1B,uBAAuB;QACvB,qBAAqB;QACrB,yBAAyB;QACzB,EAAE;KACH,CAAC,IAAI,CAAC,IAAI,CAAC,CACb,CAAC;AACJ,CAAC;AAED,SAAS,WAAW,CAAC,KAAc;IACjC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC"}
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "askdb",
3
+ "version": "0.5.0-beta.1",
4
+ "description": "AskDB CLI: ask natural-language questions and get validated SQL from the configured dialect.",
5
+ "keywords": [
6
+ "askdb",
7
+ "cli",
8
+ "nl-to-sql",
9
+ "natural-language-to-sql",
10
+ "postgres",
11
+ "postgresql",
12
+ "ai",
13
+ "llm",
14
+ "sql"
15
+ ],
16
+ "homepage": "https://github.com/Ygilany/AskDB#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/Ygilany/AskDB/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/Ygilany/AskDB.git",
23
+ "directory": "apps/cli"
24
+ },
25
+ "license": "Apache-2.0",
26
+ "author": "Yahya Gilany",
27
+ "type": "module",
28
+ "bin": {
29
+ "askdb": "./bin/askdb.js"
30
+ },
31
+ "files": [
32
+ "bin",
33
+ "dist",
34
+ "README.md",
35
+ "LICENSE",
36
+ "NOTICE"
37
+ ],
38
+ "engines": {
39
+ "node": ">=20"
40
+ },
41
+ "dependencies": {
42
+ "@ai-sdk/openai": "^1.3.21",
43
+ "commander": "^13.1.0",
44
+ "pg": "^8.14.1",
45
+ "@askdb/config": "0.3.0-beta.1",
46
+ "@askdb/postgres": "0.2.0-beta.1",
47
+ "@askdb/core": "0.5.0-beta.0",
48
+ "@askdb/tui": "0.2.0-beta.1",
49
+ "@askdb/introspect": "0.3.0-beta.1",
50
+ "@askdb/studio": "0.2.0-beta.1",
51
+ "@askdb/prisma": "0.2.0-beta.1"
52
+ },
53
+ "devDependencies": {
54
+ "typescript": "^5.7.3",
55
+ "vitest": "^3.0.9"
56
+ },
57
+ "scripts": {
58
+ "build": "tsc -p tsconfig.build.json",
59
+ "lint": "tsc -p tsconfig.build.json --noEmit",
60
+ "test": "vitest run --config ../../vitest.config.ts"
61
+ }
62
+ }