codestation-mcp 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/codestation-mcp.mjs +804 -1591
  2. package/package.json +1 -1
@@ -1,901 +1,4 @@
1
1
  #!/usr/bin/env node
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __esm = (fn, res, err) => function __init() {
5
- if (err) throw err[0];
6
- try {
7
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
- } catch (e) {
9
- throw err = [e], e;
10
- }
11
- };
12
- var __export = (target, all) => {
13
- for (var name2 in all)
14
- __defProp(target, name2, { get: all[name2], enumerable: true });
15
- };
16
-
17
- // lib/tools/sql/types.ts
18
- var SQL_DIALECTS, VALUE_TYPES, CONDITION_OPERATORS;
19
- var init_types = __esm({
20
- "lib/tools/sql/types.ts"() {
21
- "use strict";
22
- SQL_DIALECTS = ["PostgreSQL", "MySQL", "SQLite", "SQL Server"];
23
- VALUE_TYPES = ["String", "Number", "Boolean", "NULL"];
24
- CONDITION_OPERATORS = ["=", "!=", ">", ">=", "<", "<=", "LIKE", "NOT LIKE", "IN", "NOT IN", "IS NULL", "IS NOT NULL"];
25
- }
26
- });
27
-
28
- // lib/tools/sql/literals.ts
29
- function readDialect(value) {
30
- if (typeof value !== "string" || !SQL_DIALECTS.includes(value)) {
31
- throw new Error("Choose PostgreSQL, MySQL, SQLite, or SQL Server.");
32
- }
33
- return value;
34
- }
35
- function sqlText(value, label) {
36
- if (typeof value !== "string") throw new Error(`${label} must be text.`);
37
- if (value.length > SQL_TEXT_LIMIT) throw new Error(`${label} exceeds the 200,000-character limit.`);
38
- return value;
39
- }
40
- function quoteIdentifier(name2, dialect, qualified2 = false) {
41
- readDialect(dialect);
42
- if (typeof name2 !== "string") throw new Error("Identifiers must be text.");
43
- const parts = qualified2 ? name2.split(".") : [name2];
44
- const maximumParts = dialect === "SQL Server" ? 4 : dialect === "PostgreSQL" ? 3 : 2;
45
- if (parts.some((part) => dialect === "PostgreSQL" ? new TextEncoder().encode(part).length > 63 : dialect === "MySQL" ? [...part].length > 64 : part.length > 128)) {
46
- throw new Error("Identifiers exceed the supported length: PostgreSQL 63 UTF-8 bytes, MySQL 64 characters, SQLite/SQL Server 128 UTF-16 units.");
47
- }
48
- if (parts.length > maximumParts || parts.some((part) => part.length > 128 || !/^[\p{L}_][\p{L}\p{M}\p{N}_$]*$/u.test(part))) {
49
- throw new Error(`Use raw identifiers of 1\u2013128 characters: start with a letter or underscore, then letters, marks, numbers, underscore, or $. This dialect allows at most ${maximumParts} table qualification parts.`);
50
- }
51
- return parts.map((part) => dialect === "MySQL" ? `\`${part}\`` : dialect === "SQL Server" ? `[${part}]` : `"${part}"`).join(".");
52
- }
53
- function stringLiteral(value, dialect) {
54
- if (value.includes("\0")) throw new Error("SQL strings cannot contain a NUL character.");
55
- if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value)) {
56
- throw new Error("SQL strings must contain valid Unicode, without unpaired surrogates.");
57
- }
58
- let escaped = value;
59
- if (dialect === "MySQL") escaped = escaped.replace(/\\/g, "\\\\").replace(/\x1a/g, "\\Z");
60
- escaped = escaped.replace(/'/g, "''");
61
- return `${dialect === "SQL Server" ? "N" : ""}'${escaped}'`;
62
- }
63
- function sqlLiteral(literal, dialect) {
64
- readDialect(dialect);
65
- if (!literal || typeof literal !== "object" || Array.isArray(literal) || !VALUE_TYPES.includes(literal.type)) {
66
- throw new Error("Choose String, Number, Boolean, or NULL for each value.");
67
- }
68
- const value = sqlText(literal.value, "Literal value");
69
- if (literal.type === "NULL") return "NULL";
70
- if (literal.type === "String") return stringLiteral(value, dialect);
71
- if (literal.type === "Boolean") {
72
- if (!/^(true|false)$/i.test(value)) throw new Error("Boolean values must be true or false.");
73
- const truth = value.toLowerCase() === "true";
74
- return dialect === "SQL Server" ? truth ? "1" : "0" : truth ? "TRUE" : "FALSE";
75
- }
76
- if (!/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(value) || !Number.isFinite(Number(value))) {
77
- throw new Error("Number values must be finite decimal numbers, with an optional exponent and no SQL expressions.");
78
- }
79
- if (Number(value) === 0 && /[1-9]/.test(value.split(/[eE]/)[0])) throw new Error("Number is too small to represent as a finite nonzero number.");
80
- return value;
81
- }
82
- function jsonLiteral(value, dialect) {
83
- if (value === null) return sqlLiteral({ type: "NULL", value: "" }, dialect);
84
- if (typeof value === "string") return sqlLiteral({ type: "String", value }, dialect);
85
- if (typeof value === "boolean") return sqlLiteral({ type: "Boolean", value: String(value) }, dialect);
86
- if (typeof value === "number") {
87
- if (!Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value)) {
88
- throw new Error("JSON numbers must be finite and integers must be safe; quote precision-sensitive numbers as strings.");
89
- }
90
- return sqlLiteral({ type: "Number", value: String(value) }, dialect);
91
- }
92
- throw new Error("JSON SQL values must be strings, numbers, booleans, or null; nested arrays and objects are unsupported.");
93
- }
94
- var SQL_TEXT_LIMIT;
95
- var init_literals = __esm({
96
- "lib/tools/sql/literals.ts"() {
97
- "use strict";
98
- init_types();
99
- SQL_TEXT_LIMIT = 2e5;
100
- }
101
- });
102
-
103
- // lib/tools/sql/lexer.ts
104
- function dollarDelimiter(text3) {
105
- return /^(?:\$\$|\$[\p{L}_][\p{L}\p{M}\p{N}_]*\$)/u.exec(text3)?.[0];
106
- }
107
- function lexSql(sql, dialect) {
108
- if (typeof sql !== "string" || !sql.trim()) throw new SqlSyntaxError("Enter SQL to process.");
109
- if (sql.length > 2e5) throw new SqlSyntaxError("SQL exceeds the 200,000-character limit.");
110
- const tokens = [];
111
- let i = 0, line = 1, column = 1, depth = 0, statements = 0;
112
- const fail = (message) => {
113
- throw new SqlSyntaxError(message, { line, column });
114
- };
115
- const push = (kind, end) => {
116
- const text3 = sql.slice(i, end);
117
- tokens.push({ kind, text: text3, start: i, end, line, column });
118
- for (let j = i; j < end; j++) {
119
- if (sql[j] === "\n" || sql[j] === "\r" && sql[j + 1] !== "\n") {
120
- line++;
121
- column = 1;
122
- } else column++;
123
- }
124
- i = end;
125
- if (tokens.length > 5e4) fail("SQL exceeds the 50,000-token limit.");
126
- };
127
- while (i < sql.length) {
128
- const ch = sql[i];
129
- if (/\s/.test(ch)) {
130
- let j = i + 1;
131
- while (j < sql.length && /\s/.test(sql[j])) j++;
132
- push("space", j);
133
- continue;
134
- }
135
- if (ch === "\0") fail("SQL contains an unsupported NUL character.");
136
- if (sql.startsWith("--", i) && (dialect !== "MySQL" || i + 2 === sql.length || /[\s\x00-\x1f]/.test(sql[i + 2])) || ch === "#" && dialect === "MySQL") {
137
- let j = i + 1;
138
- while (j < sql.length && !/[\r\n]/.test(sql[j])) j++;
139
- push("comment", j);
140
- continue;
141
- }
142
- if (sql.startsWith("/*", i)) {
143
- const protectedComment = sql[i + 2] === "!" || sql[i + 2] === "+";
144
- if (sql[i + 2] === "!" && dialect !== "MySQL") fail("Executable comments are supported only for MySQL.");
145
- let nesting = 1, j = i + 2;
146
- while (j < sql.length && nesting) {
147
- if (sql.startsWith("/*", j)) {
148
- if (dialect !== "PostgreSQL" && dialect !== "SQL Server") fail("Nested block comments are unsupported for the selected dialect.");
149
- if (++nesting > 128) fail("SQL comment nesting exceeds the 128-level limit.");
150
- j += 2;
151
- } else if (sql.startsWith("*/", j)) {
152
- nesting--;
153
- j += 2;
154
- } else j++;
155
- }
156
- if (nesting) fail("Unterminated SQL block comment.");
157
- push(protectedComment ? "protected" : "comment", j);
158
- continue;
159
- }
160
- if (dialect === "PostgreSQL" && ch === "$") {
161
- const delimiter = dollarDelimiter(sql.slice(i));
162
- if (delimiter) {
163
- const end = sql.indexOf(delimiter, i + delimiter.length);
164
- if (end < 0) fail("Unterminated PostgreSQL dollar-quoted string.");
165
- push("string", end + delimiter.length);
166
- continue;
167
- }
168
- }
169
- const prefixed = (dialect === "PostgreSQL" && /[eE]/.test(ch) || (dialect === "SQL Server" || dialect === "MySQL") && /[nN]/.test(ch)) && sql[i + 1] === "'";
170
- const quote = prefixed ? "'" : ch;
171
- if (quote === "'" || quote === '"' || quote === "`" || quote === "[") {
172
- if (quote === "`" && dialect !== "MySQL" && dialect !== "SQLite") fail("Backtick identifiers are unsupported for the selected dialect.");
173
- if (quote === "[" && dialect !== "SQL Server" && dialect !== "SQLite") {
174
- push("symbol", i + 1);
175
- continue;
176
- }
177
- const closing = quote === "[" ? "]" : quote;
178
- const kind = quote === "'" || quote === '"' && dialect === "MySQL" ? "string" : "identifier";
179
- const escapes = kind === "string" && dialect === "MySQL" || prefixed && dialect === "PostgreSQL";
180
- let j = i + (prefixed ? 2 : 1), closed = false;
181
- while (j < sql.length) {
182
- if (escapes && sql[j] === "\\") {
183
- j += 2;
184
- continue;
185
- }
186
- if (sql[j] === closing) {
187
- if (sql[j + 1] === closing) {
188
- j += 2;
189
- continue;
190
- }
191
- j++;
192
- closed = true;
193
- break;
194
- }
195
- j++;
196
- }
197
- if (!closed) fail(kind === "string" ? "Unterminated SQL string literal." : "Unterminated quoted SQL identifier.");
198
- push(kind, j);
199
- continue;
200
- }
201
- if (/[A-Za-z_\u0080-\uffff]/.test(ch) || ch === "@" && dialect === "SQL Server" || ch === "#" && dialect === "SQL Server") {
202
- let j = i + 1;
203
- while (j < sql.length && /[A-Za-z0-9_$@#\u0080-\uffff]/.test(sql[j])) j++;
204
- push("word", j);
205
- continue;
206
- }
207
- if (/[0-9]/.test(ch) || ch === "." && /[0-9]/.test(sql[i + 1] ?? "")) {
208
- const number = /^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(sql.slice(i))[0];
209
- push("number", i + number.length);
210
- continue;
211
- }
212
- if (ch === "(") {
213
- if (++depth > 128) fail("SQL nesting exceeds the 128-level limit.");
214
- }
215
- if (ch === ")") {
216
- if (--depth < 0) fail("Unexpected closing parenthesis.");
217
- }
218
- if (ch === ";" && ++statements > 200) fail("SQL exceeds the 200-statement limit.");
219
- const operator = /^(?:->>|->|#>>|#>|::|>=|<=|<>|!=|\|\||&&|:=|!~\*|!~|~\*|<<|>>)/.exec(sql.slice(i))?.[0];
220
- if (operator === "::" && dialect !== "PostgreSQL") fail("PostgreSQL :: casts are unsupported for the selected dialect.");
221
- push("symbol", i + (operator?.length ?? 1));
222
- }
223
- if (depth) throw new SqlSyntaxError("Unclosed SQL parenthesis.", { line, column });
224
- if (!tokens.some((t) => t.kind !== "space" && t.kind !== "comment")) throw new SqlSyntaxError("Enter a SQL statement, not only comments.");
225
- return tokens;
226
- }
227
- function significantTokens(tokens) {
228
- return tokens.filter((t) => t.kind !== "space" && t.kind !== "comment");
229
- }
230
- function identifierValue(token) {
231
- if (!token || token.kind !== "word" && token.kind !== "identifier") throw new SqlSyntaxError("A named SQL identifier is required.", token);
232
- if (token.kind === "word") return token.text;
233
- const end = token.text[0] === "[" ? "]" : token.text[0];
234
- return token.text.slice(1, -1).split(end + end).join(end);
235
- }
236
- var SqlSyntaxError, TokenCursor;
237
- var init_lexer = __esm({
238
- "lib/tools/sql/lexer.ts"() {
239
- "use strict";
240
- SqlSyntaxError = class extends Error {
241
- constructor(message, location) {
242
- super(message);
243
- this.name = "SqlSyntaxError";
244
- this.line = location?.line;
245
- this.column = location?.column;
246
- this.stack = `${this.name}: ${message}`;
247
- }
248
- };
249
- TokenCursor = class {
250
- constructor(tokens) {
251
- this.tokens = tokens;
252
- this.index = 0;
253
- }
254
- peek() {
255
- return this.tokens[this.index];
256
- }
257
- is(text3) {
258
- return this.peek()?.text.toUpperCase() === text3.toUpperCase();
259
- }
260
- take() {
261
- const token = this.tokens[this.index++];
262
- if (!token) this.fail("Unexpected end of SQL.");
263
- return token;
264
- }
265
- accept(text3) {
266
- if (!this.is(text3)) return false;
267
- this.index++;
268
- return true;
269
- }
270
- expect(text3) {
271
- if (!this.accept(text3)) this.fail("Unexpected SQL syntax in the supported statement subset.");
272
- }
273
- identifier() {
274
- return identifierValue(this.take());
275
- }
276
- qualifiedIdentifier() {
277
- const parts = [this.identifier()];
278
- while (this.accept(".")) parts.push(this.identifier());
279
- if (parts.length > 3) this.fail("SQL identifiers may have at most three qualification parts.");
280
- return parts.join(".");
281
- }
282
- fail(message) {
283
- throw new SqlSyntaxError(message, this.peek() ?? this.tokens[this.tokens.length - 1]);
284
- }
285
- };
286
- }
287
- });
288
-
289
- // lib/tools/sql/parser.ts
290
- async function parseSql(sql, dialect) {
291
- dialect = readDialect(dialect);
292
- lexSql(sql, dialect);
293
- const parserModule = await engines[dialect]();
294
- try {
295
- const exported = parserModule;
296
- const Parser = exported.Parser ?? exported.default?.Parser;
297
- if (!Parser) throw new SqlSyntaxError("The local dialect parser could not initialize.");
298
- const ast = new Parser().astify(sql);
299
- const statements = Array.isArray(ast) ? ast : [ast];
300
- if (!statements.length || statements.length > 200) throw new SqlSyntaxError("SQL must contain between 1 and 200 statements.");
301
- if (statements.some((statement) => typeof statement.type !== "string")) throw new SqlSyntaxError("The selected parser returned an unsupported statement form.");
302
- if (dialect === "SQL Server") {
303
- const pending = [...statements];
304
- while (pending.length) {
305
- const value = pending.pop();
306
- if (!value || typeof value !== "object") continue;
307
- const record2 = value;
308
- if (record2.type === "select" && record2.limit) throw new SqlSyntaxError("LIMIT is unsupported for SQL Server; use its native TOP or OFFSET/FETCH syntax.");
309
- pending.push(...Object.values(record2).filter((child) => child && typeof child === "object"));
310
- }
311
- }
312
- return statements;
313
- } catch (error) {
314
- if (error instanceof SqlSyntaxError) throw error;
315
- const location = error?.location?.start;
316
- const safeLocation = typeof location?.line === "number" && typeof location.column === "number" ? { line: location.line, column: location.column } : void 0;
317
- throw new SqlSyntaxError(`SQL is invalid or unsupported by the ${dialect} parser's supported syntax subset.`, safeLocation);
318
- }
319
- }
320
- var engines;
321
- var init_parser = __esm({
322
- "lib/tools/sql/parser.ts"() {
323
- "use strict";
324
- init_lexer();
325
- init_literals();
326
- init_lexer();
327
- engines = {
328
- PostgreSQL: () => import("node-sql-parser/build/postgresql"),
329
- MySQL: () => import("node-sql-parser/build/mysql"),
330
- SQLite: () => import("node-sql-parser/build/sqlite"),
331
- "SQL Server": () => import("node-sql-parser/build/transactsql")
332
- };
333
- }
334
- });
335
-
336
- // lib/tools/sql/ddl.ts
337
- var ddl_exports = {};
338
- __export(ddl_exports, {
339
- ddlOutput: () => ddlOutput,
340
- parseDdl: () => parseDdl
341
- });
342
- function key(name2, dialect) {
343
- return dialect === "PostgreSQL" ? name2 : name2.toLowerCase();
344
- }
345
- function name(cursor, dialect) {
346
- const token = cursor.take(), value = identifierValue(token);
347
- if (value.length > 128) cursor.fail("DDL identifiers are limited to 128 characters.");
348
- return dialect === "PostgreSQL" && token.kind === "word" ? value.toLowerCase() : value;
349
- }
350
- function qualified(cursor, dialect) {
351
- const parts = [name(cursor, dialect)];
352
- while (cursor.accept(".")) parts.push(name(cursor, dialect));
353
- if (parts.length > 3) cursor.fail("Table names may have at most three qualification parts.");
354
- if (parts.some((part) => part.includes("."))) cursor.fail("Quoted identifiers containing dots are unsupported; use explicit qualification parts.");
355
- return parts.join(".");
356
- }
357
- function columns(cursor, dialect) {
358
- cursor.expect("(");
359
- const values = [];
360
- do {
361
- values.push(name(cursor, dialect));
362
- } while (cursor.accept(","));
363
- cursor.expect(")");
364
- if (new Set(values.map((value) => key(value, dialect))).size !== values.length) cursor.fail("Duplicate columns in a key constraint.");
365
- return values;
366
- }
367
- function parenthesized(cursor, allowEmpty = false) {
368
- cursor.expect("(");
369
- let depth = 1;
370
- const result2 = [];
371
- while (depth) {
372
- const token = cursor.take();
373
- if (token.text === "(") depth++;
374
- if (token.text === ")") depth--;
375
- if (depth) result2.push(token);
376
- }
377
- if (!result2.length && !allowEmpty) cursor.fail("Empty parenthesized SQL definition is unsupported.");
378
- return result2;
379
- }
380
- function reference(cursor, dialect, localColumns) {
381
- cursor.expect("REFERENCES");
382
- const referencedTable = qualified(cursor, dialect), referencedColumns = columns(cursor, dialect);
383
- if (localColumns.length !== referencedColumns.length) cursor.fail("Foreign-key column counts do not match the referenced column counts.");
384
- let match = false;
385
- const actions = /* @__PURE__ */ new Set();
386
- while (cursor.is("MATCH") || cursor.is("ON")) {
387
- if (cursor.accept("MATCH")) {
388
- if (match) cursor.fail("Duplicate foreign-key MATCH clause.");
389
- match = true;
390
- if (!cursor.accept("SIMPLE") && !cursor.accept("FULL") && !cursor.accept("PARTIAL")) cursor.fail("Unsupported foreign-key MATCH clause.");
391
- } else {
392
- cursor.expect("ON");
393
- const action = cursor.take().text.toUpperCase();
394
- if (action !== "DELETE" && action !== "UPDATE" || actions.has(action)) cursor.fail("Invalid or duplicate foreign-key action.");
395
- actions.add(action);
396
- if (cursor.accept("SET")) {
397
- if (!cursor.accept("NULL") && !cursor.accept("DEFAULT")) cursor.fail("Unsupported foreign-key SET action.");
398
- } else if (cursor.accept("NO")) cursor.expect("ACTION");
399
- else if (!cursor.accept("CASCADE") && !cursor.accept("RESTRICT")) cursor.fail("Unsupported foreign-key action.");
400
- }
401
- }
402
- return { columns: localColumns, referencedTable, referencedColumns };
403
- }
404
- function dataType(cursor, dialect, sql) {
405
- const start = cursor.peek()?.start;
406
- if (start === void 0) cursor.fail("A declared column type is required.");
407
- const first = name(cursor, dialect).toUpperCase();
408
- while (cursor.accept(".")) name(cursor, dialect);
409
- if (first === "DOUBLE") cursor.accept("PRECISION");
410
- if (first === "CHARACTER" || first === "CHAR" || first === "BIT") cursor.accept("VARYING");
411
- if (first === "NATIONAL") {
412
- if (!cursor.accept("VARCHAR") && !cursor.accept("CHAR") && !cursor.accept("CHARACTER")) cursor.fail("Unsupported NATIONAL column type.");
413
- cursor.accept("VARYING");
414
- }
415
- if (cursor.is("(")) {
416
- const args = parenthesized(cursor);
417
- if (args.some((token, i) => i % 2 === 1 ? token.text !== "," : token.kind !== "number" && token.kind !== "string" && token.text.toUpperCase() !== "MAX") || args.length % 2 === 0) cursor.fail("Unsupported column-type parameters.");
418
- }
419
- if (first === "TIMESTAMP" || first === "TIME") {
420
- if (cursor.accept("WITH") || cursor.accept("WITHOUT")) {
421
- cursor.expect("TIME");
422
- cursor.expect("ZONE");
423
- }
424
- }
425
- if (dialect === "MySQL") {
426
- cursor.accept("UNSIGNED");
427
- cursor.accept("ZEROFILL");
428
- }
429
- if (dialect === "PostgreSQL") while (cursor.accept("[")) {
430
- if (cursor.peek()?.kind === "number") cursor.take();
431
- cursor.expect("]");
432
- }
433
- const end = cursor.tokens[cursor.index - 1].end;
434
- return sql.slice(start, end).trim();
435
- }
436
- function parseDefinition(tokens, table, dialect, sql) {
437
- const cursor = new TokenCursor(tokens);
438
- if (cursor.accept("CONSTRAINT")) name(cursor, dialect);
439
- if (cursor.accept("PRIMARY")) {
440
- cursor.expect("KEY");
441
- if (dialect === "SQL Server") {
442
- cursor.accept("CLUSTERED");
443
- cursor.accept("NONCLUSTERED");
444
- }
445
- if (table.primaryKeys.length) cursor.fail("A table may declare only one primary key.");
446
- table.primaryKeys = columns(cursor, dialect);
447
- } else if (cursor.accept("FOREIGN")) {
448
- cursor.expect("KEY");
449
- const localColumns = columns(cursor, dialect);
450
- table.foreignKeys.push(reference(cursor, dialect, localColumns));
451
- } else if (cursor.accept("UNIQUE")) {
452
- columns(cursor, dialect);
453
- } else if (cursor.accept("CHECK")) {
454
- parenthesized(cursor);
455
- } else {
456
- const columnName = name(cursor, dialect);
457
- if (table.columns.some((column2) => key(column2.name, dialect) === key(columnName, dialect))) cursor.fail("Duplicate column identifiers in CREATE TABLE.");
458
- const declaredType = dataType(cursor, dialect, sql);
459
- const column = { name: columnName, dataType: declaredType, primaryKey: false, nullable: true };
460
- let explicitNullability = false, hasDefault = false, hasReference = false, primary = false;
461
- while (cursor.peek()) {
462
- if (cursor.accept("CONSTRAINT")) {
463
- name(cursor, dialect);
464
- continue;
465
- }
466
- if (cursor.accept("PRIMARY")) {
467
- cursor.expect("KEY");
468
- if (primary || table.primaryKeys.length) cursor.fail("A table may declare only one primary key.");
469
- primary = true;
470
- table.primaryKeys = [columnName];
471
- column.primaryKey = true;
472
- } else if (cursor.accept("NOT")) {
473
- cursor.expect("NULL");
474
- if (explicitNullability) cursor.fail("Duplicate column nullability declaration.");
475
- explicitNullability = true;
476
- column.nullable = false;
477
- } else if (cursor.accept("NULL")) {
478
- if (explicitNullability) cursor.fail("Duplicate column nullability declaration.");
479
- explicitNullability = true;
480
- column.nullable = true;
481
- } else if (cursor.is("REFERENCES")) {
482
- if (hasReference) cursor.fail("Duplicate inline foreign-key declaration.");
483
- hasReference = true;
484
- table.foreignKeys.push(reference(cursor, dialect, [columnName]));
485
- } else if (cursor.accept("DEFAULT")) {
486
- if (hasDefault) cursor.fail("Duplicate column DEFAULT declaration.");
487
- hasDefault = true;
488
- const start = cursor.index;
489
- if (cursor.is("(")) parenthesized(cursor);
490
- else {
491
- if (cursor.is("+") || cursor.is("-")) cursor.take();
492
- cursor.take();
493
- if (cursor.is("(")) parenthesized(cursor, true);
494
- while (cursor.accept("::")) qualified(cursor, dialect);
495
- }
496
- if (cursor.index === start) cursor.fail("A DEFAULT expression is required.");
497
- } else if (cursor.accept("UNIQUE")) {
498
- } else if (cursor.accept("CHECK")) parenthesized(cursor);
499
- else if (cursor.accept("COLLATE")) qualified(cursor, dialect);
500
- else if (cursor.accept("AUTO_INCREMENT")) {
501
- if (dialect !== "MySQL") cursor.fail("AUTO_INCREMENT is supported only for MySQL.");
502
- } else if (cursor.accept("AUTOINCREMENT")) {
503
- if (dialect !== "SQLite" || !primary || declaredType.toUpperCase() !== "INTEGER") cursor.fail("SQLite AUTOINCREMENT requires an INTEGER PRIMARY KEY.");
504
- } else if (cursor.accept("IDENTITY")) {
505
- if (dialect !== "SQL Server") cursor.fail("IDENTITY is supported only for SQL Server.");
506
- if (cursor.is("(")) parenthesized(cursor);
507
- } else cursor.fail("Unsupported column constraint or definition; no schema details were discarded.");
508
- }
509
- table.columns.push(column);
510
- }
511
- if (cursor.peek()) cursor.fail("Unsupported table constraint options; no schema details were discarded.");
512
- }
513
- async function parseDdl(sql, dialect) {
514
- dialect = readDialect(dialect);
515
- const tokens = significantTokens(lexSql(sql, dialect)), cursor = new TokenCursor(tokens);
516
- const tables = [];
517
- let totalColumns = 0, totalRelationships = 0;
518
- const serverValidationTokens = [];
519
- while (cursor.peek()) {
520
- const tableStart = cursor.index;
521
- cursor.expect("CREATE");
522
- if (cursor.accept("TEMP") || cursor.accept("TEMPORARY")) {
523
- if (dialect === "SQL Server") cursor.fail("SQL Server temporary tables use a # table name.");
524
- }
525
- cursor.expect("TABLE");
526
- if (cursor.accept("IF")) {
527
- if (dialect === "SQL Server") cursor.fail("IF NOT EXISTS is unsupported for SQL Server CREATE TABLE.");
528
- cursor.expect("NOT");
529
- cursor.expect("EXISTS");
530
- }
531
- const table = { name: qualified(cursor, dialect), columns: [], primaryKeys: [], foreignKeys: [] };
532
- if (tables.some((existing) => key(existing.name, dialect) === key(table.name, dialect))) cursor.fail("Duplicate CREATE TABLE identifiers.");
533
- cursor.expect("(");
534
- const openIndex = cursor.index - 1;
535
- const definitions = [];
536
- let segment = [], depth = 0;
537
- while (cursor.peek() && !(cursor.is(")") && depth === 0)) {
538
- const token = cursor.take();
539
- if (token.text === "," && depth === 0) {
540
- if (!segment.length) cursor.fail("Empty CREATE TABLE definition.");
541
- definitions.push(segment);
542
- segment = [];
543
- } else {
544
- if (token.text === "(") depth++;
545
- else if (token.text === ")") depth--;
546
- segment.push(token);
547
- }
548
- }
549
- if (!segment.length) cursor.fail("CREATE TABLE needs nonempty named columns and no trailing comma.");
550
- definitions.push(segment);
551
- cursor.expect(")");
552
- const closeIndex = cursor.index - 1;
553
- for (const definition of definitions) parseDefinition(definition, table, dialect, sql);
554
- if (!table.columns.length) cursor.fail("CREATE TABLE needs at least one named column.");
555
- const local = new Set(table.columns.map((column) => key(column.name, dialect)));
556
- for (const primaryKey of table.primaryKeys) if (!local.has(key(primaryKey, dialect))) cursor.fail("A primary-key column is not declared in its table.");
557
- for (const foreignKey of table.foreignKeys) for (const column of foreignKey.columns) if (!local.has(key(column, dialect))) cursor.fail("A foreign-key column is not declared in its table.");
558
- for (const column of table.columns) {
559
- column.primaryKey = table.primaryKeys.some((primaryKey) => key(primaryKey, dialect) === key(column.name, dialect));
560
- if (column.primaryKey && (dialect !== "SQLite" || table.primaryKeys.length === 1 && column.dataType.toUpperCase() === "INTEGER")) column.nullable = false;
561
- }
562
- tables.push(table);
563
- totalColumns += table.columns.length;
564
- totalRelationships += table.foreignKeys.length;
565
- if (tables.length > 50 || totalColumns > 500 || totalRelationships > 200) cursor.fail("DDL is limited to 50 tables, 500 columns and 200 foreign-key relationships.");
566
- if (cursor.peek() && !cursor.accept(";")) cursor.fail("Only CREATE TABLE statements are supported; table options, ALTER and other statements are unsupported.");
567
- if (dialect === "SQL Server") {
568
- serverValidationTokens.push(...tokens.slice(tableStart, openIndex + 1));
569
- const retained = [];
570
- for (const definition of definitions) {
571
- let start = 0;
572
- if (definition[0]?.text.toUpperCase() === "CONSTRAINT") start = 2;
573
- if (definition[start]?.text.toUpperCase() === "FOREIGN") continue;
574
- const referenceIndex = definition.findIndex((token) => token.kind === "word" && token.text.toUpperCase() === "REFERENCES");
575
- if (referenceIndex < 0) retained.push(definition);
576
- else {
577
- const refCursor = new TokenCursor(definition);
578
- refCursor.index = referenceIndex;
579
- reference(refCursor, dialect, ["column"]);
580
- const refStart = definition[referenceIndex - 2]?.text.toUpperCase() === "CONSTRAINT" ? referenceIndex - 2 : referenceIndex;
581
- retained.push([...definition.slice(0, refStart), ...definition.slice(refCursor.index)]);
582
- }
583
- }
584
- retained.forEach((definition, index) => {
585
- if (index) serverValidationTokens.push({ ...tokens[openIndex], text: "," });
586
- serverValidationTokens.push(...definition);
587
- });
588
- serverValidationTokens.push(tokens[closeIndex], { ...tokens[closeIndex], text: ";" });
589
- }
590
- }
591
- await parseSql(dialect === "SQL Server" ? serverValidationTokens.map((token) => token.text).join(" ") : sql, dialect);
592
- const relationships = tables.flatMap((table) => table.foreignKeys.map((foreignKey) => ({ fromTable: table.name, fromColumns: foreignKey.columns, toTable: foreignKey.referencedTable, toColumns: foreignKey.referencedColumns })));
593
- for (const relationship of relationships) {
594
- const target = tables.find((table) => key(table.name, dialect) === key(relationship.toTable, dialect));
595
- if (target && relationship.toColumns.some((column) => !target.columns.some((candidate) => key(candidate.name, dialect) === key(column, dialect)))) throw new SqlSyntaxError("A foreign key references a missing column in a locally declared table.");
596
- if (target) relationship.toTable = target.name;
597
- }
598
- return { tables, relationships };
599
- }
600
- async function ddlOutput(sql, dialect) {
601
- const schema = await parseDdl(sql, dialect);
602
- const columns2 = schema.tables.flatMap((table) => table.columns.map((column) => `${table.name}.${column.name}: ${column.dataType}${column.primaryKey ? " [PK]" : ""}${column.nullable === false ? " NOT NULL" : ""}`));
603
- const primaryKeys = schema.tables.filter((table) => table.primaryKeys.length).map((table) => `${table.name}: (${table.primaryKeys.join(", ")})`);
604
- const relationships = schema.relationships.map((link) => `${link.fromTable} (${link.fromColumns.join(", ")}) \u2192 ${link.toTable} (${link.toColumns.join(", ")})`);
605
- return { schema, rows: [
606
- { label: "Entity relationship diagram", value: [`Tables: ${schema.tables.map((table) => table.name).join(", ")}`, ...relationships].join("\n") },
607
- { label: "Parsed tables", value: schema.tables.map((table) => table.name).join("\n") },
608
- { label: "Columns", value: columns2.join("\n") },
609
- { label: "Primary keys", value: primaryKeys.join("\n") || "None declared" },
610
- { label: "Foreign-key relationships", value: relationships.join("\n") || "None declared" }
611
- ], warnings: ["Relationships come only from explicitly declared foreign keys. External referenced tables are retained. This does not verify database objects or referential integrity."] };
612
- }
613
- var init_ddl = __esm({
614
- "lib/tools/sql/ddl.ts"() {
615
- "use strict";
616
- init_lexer();
617
- init_literals();
618
- init_parser();
619
- }
620
- });
621
-
622
- // lib/tools/sql/transforms.ts
623
- var transforms_exports = {};
624
- __export(transforms_exports, {
625
- formatSqlTool: () => formatSqlTool,
626
- insertOutput: () => insertOutput,
627
- minifySqlTool: () => minifySqlTool,
628
- parseInsertData: () => parseInsertData,
629
- validateSqlTool: () => validateSqlTool
630
- });
631
- async function validateSqlTool(sql, dialect) {
632
- dialect = readDialect(dialect);
633
- try {
634
- await parseSql(sql, dialect);
635
- return { rows: [{ label: "Valid/Invalid status", value: "Valid" }, { label: "Syntax error message", value: "None" }, { label: "Error location", value: "None" }], warnings: [parserWarning] };
636
- } catch (error) {
637
- const safe = error instanceof SqlSyntaxError ? error : new SqlSyntaxError("The selected dialect parser could not process this SQL.");
638
- return { rows: [{ label: "Valid/Invalid status", value: "Invalid" }, { label: "Syntax error message", value: safe.message }, { label: "Error location", value: safe.line && safe.column ? `Line ${safe.line}, Column ${safe.column}` : "Unavailable" }], warnings: [parserWarning] };
639
- }
640
- }
641
- async function minifySqlTool(sql, dialect) {
642
- dialect = readDialect(dialect);
643
- const tokens = lexSql(sql, dialect);
644
- const surviving = significantTokens(tokens);
645
- const containsContinuation = dialect === "PostgreSQL" && surviving.some((token, i) => i > 0 && token.kind === "string" && surviving[i - 1].kind === "string" && /[\r\n]/.test(sql.slice(surviving[i - 1].end, token.start)));
646
- const knownParserExtension = containsContinuation || tokens.some((token) => token.kind === "protected" || token.kind === "comment" && token.text.slice(2).includes("/*"));
647
- await parseSql(sql, dialect).catch(async (error) => {
648
- if (!(error instanceof SqlSyntaxError)) throw error;
649
- if (dialect === "SQL Server" && surviving[0]?.text.toUpperCase() === "CREATE" && surviving.some((token) => token.kind === "word" && token.text.toUpperCase() === "REFERENCES")) {
650
- const { parseDdl: parseDdl2 } = await Promise.resolve().then(() => (init_ddl(), ddl_exports));
651
- await parseDdl2(sql, dialect);
652
- return;
653
- }
654
- if (!knownParserExtension) throw error;
655
- });
656
- let output2 = "", pending = "", previous;
657
- for (const token of tokens) {
658
- if (token.kind === "space") {
659
- pending += token.text;
660
- continue;
661
- }
662
- if (token.kind === "comment") {
663
- pending += token.text.includes("\n") || token.text.includes("\r") ? "\n" : " ";
664
- continue;
665
- }
666
- if (previous && pending) {
667
- const continuation = /[\r\n]/.test(pending) && (dialect === "PostgreSQL" && previous.kind === "string" && token.kind === "string" || dialect === "SQL Server");
668
- output2 += continuation ? "\n" : " ";
669
- }
670
- output2 += token.text;
671
- previous = token;
672
- pending = "";
673
- }
674
- return { rows: [{ label: "Minified SQL", value: output2 }], warnings: ["Formatting whitespace and ordinary comments are removed conservatively. Executable/hint comments and newline-sensitive PostgreSQL string continuation are preserved. This is not a database syntax check."] };
675
- }
676
- async function formatSqlTool(sql, dialect) {
677
- dialect = readDialect(dialect);
678
- const sourceTokens = significantTokens(lexSql(sql, dialect));
679
- let warning;
680
- try {
681
- await parseSql(sql, dialect);
682
- } catch (error) {
683
- if (!(error instanceof SqlSyntaxError)) throw error;
684
- const continuation = dialect === "PostgreSQL" && sourceTokens.some((token, index) => index > 0 && token.kind === "string" && sourceTokens[index - 1].kind === "string" && /[\r\n]/.test(sql.slice(sourceTokens[index - 1].end, token.start)));
685
- const specialComments = lexSql(sql, dialect).some((token) => token.kind === "protected" || token.kind === "comment" && token.text.slice(2).includes("/*"));
686
- if (dialect === "SQL Server" && sourceTokens[0]?.text.toUpperCase() === "CREATE" && sourceTokens.some((token) => token.kind === "word" && token.text.toUpperCase() === "REFERENCES")) {
687
- const { parseDdl: parseDdl2 } = await Promise.resolve().then(() => (init_ddl(), ddl_exports));
688
- await parseDdl2(sql, dialect);
689
- } else if (continuation || specialComments) warning = "Layout preserves this dialect extension, but the local parser could not validate its complete syntax. This result is not syntax-validation proof.";
690
- else throw error;
691
- }
692
- const { format } = await import("sql-formatter");
693
- let output2;
694
- try {
695
- output2 = format(sql, { language: formatterLanguages[dialect], tabWidth: 2 });
696
- } catch (error) {
697
- const message = error instanceof Error ? error.message : "";
698
- const position = /\bline (\d+) column (\d+)\b/i.exec(message);
699
- throw new SqlSyntaxError("The selected dialect formatter cannot process this syntax. Check syntax or unsupported dialect extensions.", position ? { line: Number(position[1]), column: Number(position[2]) } : void 0);
700
- }
701
- const targetTokens = significantTokens(lexSql(output2, dialect));
702
- if (sourceTokens.length !== targetTokens.length || sourceTokens.some((token, i) => token.kind !== targetTokens[i].kind || token.text !== targetTokens[i].text)) {
703
- throw new SqlSyntaxError("Formatting would change SQL tokens; this dialect syntax is unsupported by the formatter.");
704
- }
705
- const fixes = [];
706
- if (dialect === "PostgreSQL") for (let i = 1; i < sourceTokens.length; i++) {
707
- const before = sourceTokens[i - 1], current = sourceTokens[i];
708
- if (before.kind === "string" && current.kind === "string") {
709
- const sourceGap = sql.slice(before.end, current.start);
710
- const targetGap = output2.slice(targetTokens[i - 1].end, targetTokens[i].start);
711
- if (/[\r\n]/.test(sourceGap) !== /[\r\n]/.test(targetGap)) {
712
- fixes.push({ start: targetTokens[i - 1].end, end: targetTokens[i].start, value: sourceGap });
713
- }
714
- }
715
- }
716
- for (const fix of fixes.reverse()) output2 = output2.slice(0, fix.start) + fix.value + output2.slice(fix.end);
717
- return { rows: [{ label: "Formatted SQL", value: output2 }], ...warning ? { warnings: [warning] } : {} };
718
- }
719
- function canonicalNumber(text3) {
720
- const match = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(text3);
721
- let digits = (match[2] + (match[3] ?? "")).replace(/^0+/, "");
722
- if (!digits) return "0";
723
- let exponent = Number(match[4] ?? 0) - (match[3]?.length ?? 0);
724
- while (digits.endsWith("0")) {
725
- digits = digits.slice(0, -1);
726
- exponent++;
727
- }
728
- return `${match[1] === "-" ? "-" : ""}${digits}e${exponent}`;
729
- }
730
- function exactNumber(text3, token) {
731
- const value = Number(text3);
732
- if (!Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value) || canonicalNumber(text3) !== canonicalNumber(String(value))) {
733
- throw new SqlSyntaxError("A SQL number cannot be represented safely as a JavaScript/JSON number; conversion would lose precision.", token);
734
- }
735
- return value;
736
- }
737
- function decodeString(token, dialect) {
738
- let text3 = token.text;
739
- if (text3[0] === "$") {
740
- const tag = dollarDelimiter(text3);
741
- return text3.slice(tag.length, -tag.length);
742
- }
743
- const prefix = /^[eEnN]'/.test(text3) ? text3[0].toUpperCase() : "";
744
- if (prefix) text3 = text3.slice(1);
745
- const quote = text3[0];
746
- text3 = text3.slice(1, -1).split(quote + quote).join(quote);
747
- if (dialect !== "MySQL" && !(dialect === "PostgreSQL" && prefix === "E")) return text3;
748
- let output2 = "";
749
- for (let i = 0; i < text3.length; i++) {
750
- if (text3[i] !== "\\") {
751
- output2 += text3[i];
752
- continue;
753
- }
754
- const next = text3[++i];
755
- if (next === void 0) throw new SqlSyntaxError("Incomplete SQL string escape.", token);
756
- const common = { "0": "\0", b: "\b", f: "\f", n: "\n", r: "\r", t: " ", v: "\v", "\\": "\\", "'": "'", '"': '"' };
757
- if (dialect === "MySQL") {
758
- const mysql = { "0": "\0", b: "\b", n: "\n", r: "\r", t: " ", Z: "", "\\": "\\", "'": "'", '"': '"', "%": "\\%", "_": "\\_" };
759
- output2 += mysql[next] ?? next;
760
- continue;
761
- }
762
- if (/[0-7]/.test(next)) {
763
- const digits = /^[0-7]{1,3}/.exec(text3.slice(i))[0], value = parseInt(digits, 8);
764
- if (value > 127) throw new SqlSyntaxError("Non-ASCII PostgreSQL byte escapes need a database encoding and are unsupported.", token);
765
- if (value === 0) throw new SqlSyntaxError("PostgreSQL string literals cannot contain a zero byte.", token);
766
- output2 += String.fromCharCode(value);
767
- i += digits.length - 1;
768
- } else if (next === "x") {
769
- const digits = /^[0-9a-fA-F]{1,2}/.exec(text3.slice(i + 1))?.[0];
770
- if (!digits) throw new SqlSyntaxError("Invalid PostgreSQL hexadecimal string escape.", token);
771
- const value = parseInt(digits, 16);
772
- if (value > 127) throw new SqlSyntaxError("Non-ASCII PostgreSQL byte escapes need a database encoding and are unsupported.", token);
773
- if (value === 0) throw new SqlSyntaxError("PostgreSQL string literals cannot contain a zero byte.", token);
774
- output2 += String.fromCharCode(value);
775
- i += digits.length;
776
- } else if (next === "u" || next === "U") {
777
- const length = next === "u" ? 4 : 8, digits = text3.slice(i + 1, i + 1 + length);
778
- if (!new RegExp(`^[0-9a-fA-F]{${length}}$`).test(digits)) throw new SqlSyntaxError("Invalid PostgreSQL Unicode string escape.", token);
779
- const value = parseInt(digits, 16);
780
- if (value === 0 || value > 1114111 || value >= 55296 && value <= 57343) throw new SqlSyntaxError("Unsupported Unicode code point in PostgreSQL escape.", token);
781
- output2 += String.fromCodePoint(value);
782
- i += length;
783
- } else output2 += common[next] ?? next;
784
- }
785
- return output2;
786
- }
787
- function readCell(cursor, dialect, sql) {
788
- let token = cursor.take();
789
- if (token.kind === "string") {
790
- let value = decodeString(token, dialect);
791
- while (cursor.peek()?.kind === "string") {
792
- const next = cursor.peek();
793
- if (dialect !== "PostgreSQL" || !/[\r\n]/.test(sql.slice(token.end, next.start)) || next.text[0] !== "'") cursor.fail("Adjacent string literals are unsupported except PostgreSQL newline continuation.");
794
- cursor.take();
795
- value += decodeString(next, dialect);
796
- token = next;
797
- }
798
- return value;
799
- }
800
- let sign = "";
801
- if (token.text === "+" || token.text === "-") {
802
- sign = token.text;
803
- token = cursor.take();
804
- }
805
- if (token.kind === "number") return exactNumber(sign + token.text, token);
806
- if (sign) cursor.fail("Unary signs require a numeric literal.");
807
- if (token.text.toUpperCase() === "NULL") return null;
808
- if (token.text.toUpperCase() === "TRUE" || token.text.toUpperCase() === "FALSE") {
809
- if (dialect === "SQL Server") cursor.fail("SQL Server Boolean values must be numeric 1/0 literals.");
810
- return token.text.toUpperCase() === "TRUE";
811
- }
812
- cursor.fail("INSERT conversion supports literal VALUES only; expressions, functions, casts, DEFAULT and SELECT are unsupported.");
813
- }
814
- function nameKey(name2, dialect) {
815
- return dialect === "PostgreSQL" ? name2 : name2.toLowerCase();
816
- }
817
- function readName(cursor, dialect) {
818
- const token = cursor.take(), name2 = identifierValue(token);
819
- if (name2.length > 128) cursor.fail("INSERT identifiers are limited to 128 characters.");
820
- return dialect === "PostgreSQL" && token.kind === "word" ? name2.toLowerCase() : name2;
821
- }
822
- function readQualifiedName(cursor, dialect) {
823
- const parts = [readName(cursor, dialect)];
824
- while (cursor.accept(".")) parts.push(readName(cursor, dialect));
825
- const maximumParts = dialect === "SQL Server" ? 4 : dialect === "PostgreSQL" ? 3 : 2;
826
- if (parts.length > maximumParts) cursor.fail("The table identifier has unsupported qualification for the selected dialect.");
827
- if (parts.some((part) => part.includes("."))) cursor.fail("Quoted table identifiers containing dots are unsupported; use explicit qualification parts.");
828
- return parts.join(".");
829
- }
830
- async function parseInsertData(sql, dialect) {
831
- dialect = readDialect(dialect);
832
- const cursor = new TokenCursor(significantTokens(lexSql(sql, dialect)));
833
- let columns2, table, statements = 0;
834
- const rows = [];
835
- while (cursor.peek()) {
836
- if (++statements > 200) cursor.fail("SQL exceeds the 200-statement limit.");
837
- cursor.expect("INSERT");
838
- cursor.expect("INTO");
839
- const currentTable = readQualifiedName(cursor, dialect);
840
- cursor.expect("(");
841
- const currentColumns = [];
842
- do {
843
- currentColumns.push(readName(cursor, dialect));
844
- } while (cursor.accept(","));
845
- cursor.expect(")");
846
- if (currentColumns.length > 500) cursor.fail("INSERT conversion is limited to 500 columns.");
847
- if (new Set(currentColumns.map((name2) => nameKey(name2, dialect))).size !== currentColumns.length) cursor.fail("Duplicate INSERT column names are unsupported.");
848
- if (columns2 && (currentTable !== table || currentColumns.length !== columns2.length || currentColumns.some((name2, i) => name2 !== columns2[i]))) cursor.fail("All INSERT statements must use the same exact table identifier and identical ordered column names.");
849
- columns2 ??= currentColumns;
850
- table ??= currentTable;
851
- cursor.expect("VALUES");
852
- do {
853
- cursor.expect("(");
854
- const row = [];
855
- do {
856
- row.push(readCell(cursor, dialect, sql));
857
- } while (cursor.accept(","));
858
- cursor.expect(")");
859
- if (row.length !== columns2.length) cursor.fail("INSERT row arity does not match the named columns.");
860
- rows.push(row);
861
- if (rows.length > 1e4) cursor.fail("INSERT conversion is limited to 10,000 rows.");
862
- } while (cursor.accept(","));
863
- if (cursor.peek() && !cursor.accept(";")) cursor.fail("INSERT modifiers, conflict/duplicate clauses, RETURNING, and additional expressions are unsupported.");
864
- }
865
- if (!columns2 || !rows.length) throw new SqlSyntaxError("Enter INSERT statements with named columns and literal VALUES.");
866
- return { columns: columns2, rows };
867
- }
868
- async function insertOutput(toolId, sql, dialect) {
869
- const { columns: columns2, rows } = await parseInsertData(sql, dialect);
870
- const keySize = columns2.reduce((total, column) => total + JSON.stringify(column).length + 10, 0);
871
- let projectedSize = columns2.join(",").length + 100;
872
- for (const row of rows) {
873
- projectedSize += keySize + row.reduce((total, value) => total + JSON.stringify(value).length + 6, 0);
874
- if (projectedSize > 2e6) throw new SqlSyntaxError("INSERT conversion exceeds the 2,000,000-character output budget.");
875
- }
876
- if (toolId === "sql-to-json") return { rows: [{ label: "JSON array of objects", value: JSON.stringify(rows.map((row) => Object.fromEntries(columns2.map((column, i) => [column, row[i]]))), null, 2) }] };
877
- if (toolId === "sql-to-csv") {
878
- const csv = (value) => value === null ? "" : typeof value === "string" ? `"${value.replace(/"/g, '""')}"` : String(value);
879
- return { rows: [{ label: "CSV text", value: [columns2.map(csv).join(","), ...rows.map((row) => row.map(csv).join(","))].join("\r\n") }], warnings: ["CSV has no intrinsic null type: SQL NULL is an unquoted empty cell; empty strings are quoted empty cells. A CSV reader may discard this distinction."] };
880
- }
881
- if (toolId === "sql-to-markdown") {
882
- const markdown = (value) => value === null ? "NULL" : String(value).replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\r\n|\r|\n/g, "<br>");
883
- const line = (values) => `| ${values.map(markdown).join(" | ")} |`;
884
- return { rows: [{ label: "Markdown table", value: [line(columns2), line(columns2.map(() => "---")), ...rows.map(line)].join("\n") }] };
885
- }
886
- throw new SqlSyntaxError("Unsupported SQL INSERT conversion tool.");
887
- }
888
- var formatterLanguages, parserWarning;
889
- var init_transforms = __esm({
890
- "lib/tools/sql/transforms.ts"() {
891
- "use strict";
892
- init_lexer();
893
- init_parser();
894
- init_literals();
895
- formatterLanguages = { PostgreSQL: "postgresql", MySQL: "mysql", SQLite: "sqlite", "SQL Server": "transactsql" };
896
- parserWarning = "Acceptance is limited to the selected dialect's local parser subset; this does not check database objects, permissions, or execution semantics.";
897
- }
898
- });
899
2
 
900
3
  // mcp/cli.ts
901
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -927,7 +30,9 @@ var PRO_TOOLS = /* @__PURE__ */ new Set([
927
30
  "codestation_timezone_convert",
928
31
  "codestation_business_days",
929
32
  "codestation_regex_test",
930
- "codestation_json_schema"
33
+ "codestation_json_schema",
34
+ "codestation_json_to_typescript",
35
+ "codestation_json_to_zod"
931
36
  ]);
932
37
  var CACHE_DIR = path.join(os.homedir(), ".codestation");
933
38
  var CACHE_FILE = path.join(CACHE_DIR, "license.json");
@@ -943,14 +48,14 @@ function readCachedLicense() {
943
48
  }
944
49
  return null;
945
50
  }
946
- function saveCachedLicense(key2, isPro) {
51
+ function saveCachedLicense(key, isPro) {
947
52
  try {
948
53
  if (process.env.NODE_ENV === "test") return;
949
54
  if (!fs.existsSync(CACHE_DIR)) {
950
55
  fs.mkdirSync(CACHE_DIR, { recursive: true });
951
56
  }
952
57
  const cache = {
953
- key: key2,
58
+ key,
954
59
  verifiedAt: Date.now(),
955
60
  isPro
956
61
  };
@@ -960,12 +65,12 @@ function saveCachedLicense(key2, isPro) {
960
65
  }
961
66
  function validateLicenseKey(rawKey) {
962
67
  if (!rawKey) return false;
963
- const key2 = rawKey.trim();
964
- if (!key2) return false;
965
- if (/^CS-PRO-[A-Za-z0-9_-]+$/i.test(key2) || key2.startsWith("cspro_")) {
68
+ const key = rawKey.trim();
69
+ if (!key) return false;
70
+ if (/^CS-PRO-[A-Za-z0-9_-]+$/i.test(key) || key.startsWith("cspro_")) {
966
71
  return true;
967
72
  }
968
- if (key2 === "PRO_DEMO_KEY" || key2 === "CS-PRO-DEV") {
73
+ if (key === "PRO_DEMO_KEY" || key === "CS-PRO-DEV") {
969
74
  return true;
970
75
  }
971
76
  return false;
@@ -1077,7 +182,7 @@ function generateJsonSchema(value) {
1077
182
  if (node === null) return { type: "null" };
1078
183
  if (Array.isArray(node)) return { type: "array", items: node.length ? infer(node[0]) : {} };
1079
184
  if (typeof node === "object") {
1080
- const properties = Object.fromEntries(Object.entries(node).map(([key2, child]) => [key2, infer(child)]));
185
+ const properties = Object.fromEntries(Object.entries(node).map(([key, child]) => [key, infer(child)]));
1081
186
  return { type: "object", properties, required: Object.keys(properties), additionalProperties: false };
1082
187
  }
1083
188
  return { type: typeof node === "number" && Number.isInteger(node) ? "integer" : typeof node };
@@ -1096,7 +201,7 @@ function decodeJwt(value) {
1096
201
  throw new Error("JWT header and payload must contain valid Base64URL-encoded JSON.");
1097
202
  }
1098
203
  }
1099
- function testRegex(pattern, flags, text3) {
204
+ function testRegex(pattern, flags, text2) {
1100
205
  let regex;
1101
206
  try {
1102
207
  regex = new RegExp(pattern, flags);
@@ -1105,11 +210,11 @@ function testRegex(pattern, flags, text3) {
1105
210
  }
1106
211
  const matches = [];
1107
212
  if (!regex.global) {
1108
- const match = regex.exec(text3);
213
+ const match = regex.exec(text2);
1109
214
  if (match) matches.push({ match: match[0], index: match.index, groups: match.groups ?? {}, captures: match.slice(1) });
1110
215
  } else {
1111
216
  let match;
1112
- while ((match = regex.exec(text3)) !== null) {
217
+ while ((match = regex.exec(text2)) !== null) {
1113
218
  matches.push({ match: match[0], index: match.index, groups: match.groups ?? {}, captures: match.slice(1) });
1114
219
  if (match[0] === "") regex.lastIndex += 1;
1115
220
  }
@@ -1117,7 +222,7 @@ function testRegex(pattern, flags, text3) {
1117
222
  return JSON.stringify({ count: matches.length, matches }, null, 2);
1118
223
  }
1119
224
  function utf8Decode(bytes2) {
1120
- let result2 = "";
225
+ let result = "";
1121
226
  for (let i = 0; i < bytes2.length; ) {
1122
227
  const first = bytes2[i++];
1123
228
  let code;
@@ -1126,13 +231,13 @@ function utf8Decode(bytes2) {
1126
231
  else if (first >= 224 && first <= 239 && i + 1 < bytes2.length) code = (first & 15) << 12 | (bytes2[i++] & 63) << 6 | bytes2[i++] & 63;
1127
232
  else if (first >= 240 && first <= 244 && i + 2 < bytes2.length) code = (first & 7) << 18 | (bytes2[i++] & 63) << 12 | (bytes2[i++] & 63) << 6 | bytes2[i++] & 63;
1128
233
  else throw new Error("Invalid UTF-8 data");
1129
- if (code <= 65535) result2 += String.fromCharCode(code);
234
+ if (code <= 65535) result += String.fromCharCode(code);
1130
235
  else {
1131
236
  const n = code - 65536;
1132
- result2 += String.fromCharCode(55296 | n >> 10, 56320 | n & 1023);
237
+ result += String.fromCharCode(55296 | n >> 10, 56320 | n & 1023);
1133
238
  }
1134
239
  }
1135
- return result2;
240
+ return result;
1136
241
  }
1137
242
  var BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1138
243
  function decodeBase64(value) {
@@ -1249,16 +354,16 @@ function sha1(input) {
1249
354
  return [h0, h1, h2, h3, h4].map((value) => (value >>> 0).toString(16).padStart(8, "0")).join("");
1250
355
  }
1251
356
  async function hash(input, algorithm = "SHA-256") {
1252
- const result2 = await requireCrypto().subtle.digest(algorithm, webBytes(input));
1253
- return hex(new Uint8Array(result2));
357
+ const result = await requireCrypto().subtle.digest(algorithm, webBytes(input));
358
+ return hex(new Uint8Array(result));
1254
359
  }
1255
360
  var sha256 = (input) => hash(input, "SHA-256");
1256
361
  var sha384 = (input) => hash(input, "SHA-384");
1257
362
  var sha512 = (input) => hash(input, "SHA-512");
1258
363
  async function hmac(input, secret, algorithm = "SHA-256") {
1259
364
  const crypto2 = requireCrypto();
1260
- const key2 = await crypto2.subtle.importKey("raw", webBytes(secret), { name: "HMAC", hash: algorithm }, false, ["sign"]);
1261
- return hex(new Uint8Array(await crypto2.subtle.sign("HMAC", key2, webBytes(input))));
365
+ const key = await crypto2.subtle.importKey("raw", webBytes(secret), { name: "HMAC", hash: algorithm }, false, ["sign"]);
366
+ return hex(new Uint8Array(await crypto2.subtle.sign("HMAC", key, webBytes(input))));
1262
367
  }
1263
368
  var hmacSha256 = (input, secret) => hmac(input, secret, "SHA-256");
1264
369
  var hmacSha512 = (input, secret) => hmac(input, secret, "SHA-512");
@@ -1339,9 +444,9 @@ var LOREM_WORDS = [
1339
444
  "est",
1340
445
  "laborum"
1341
446
  ].map((word) => word.trim());
1342
- function assertText(value, name2 = "text") {
1343
- if (typeof value !== "string") throw new TypeError(`${name2} must be a string.`);
1344
- if (value.length > MAX_TEXT_LENGTH) throw new RangeError(`${name2} must be at most ${MAX_TEXT_LENGTH.toLocaleString()} characters.`);
447
+ function assertText(value, name = "text") {
448
+ if (typeof value !== "string") throw new TypeError(`${name} must be a string.`);
449
+ if (value.length > MAX_TEXT_LENGTH) throw new RangeError(`${name} must be at most ${MAX_TEXT_LENGTH.toLocaleString()} characters.`);
1345
450
  return value;
1346
451
  }
1347
452
  function parseLines(value) {
@@ -1430,8 +535,8 @@ function buildUnified(operations) {
1430
535
  added += 1;
1431
536
  return { type: "addition", text: operation.text, oldLine: null, newLine: newLine++ };
1432
537
  });
1433
- const text3 = ["--- left", "+++ right", ...lines.map((line) => `${line.type === "context" ? " " : line.type === "deletion" ? "-" : "+"}${line.text}`)].join("\n");
1434
- return { lines, text: text3, added, removed };
538
+ const text2 = ["--- left", "+++ right", ...lines.map((line) => `${line.type === "context" ? " " : line.type === "deletion" ? "-" : "+"}${line.text}`)].join("\n");
539
+ return { lines, text: text2, added, removed };
1435
540
  }
1436
541
  function buildSideBySide(operations) {
1437
542
  const rows = [];
@@ -1498,16 +603,16 @@ var HOUR = 60 * MINUTE;
1498
603
  var DAY = 24 * HOUR;
1499
604
  var MIN_DATE = -621355968e5;
1500
605
  var MAX_DATE = 253402300799999;
1501
- function integer(value, name2, min, max) {
1502
- if (!Number.isInteger(value) || value < min || value > max) throw new RangeError(`${name2} must be an integer between ${min} and ${max}.`);
606
+ function integer(value, name, min, max) {
607
+ if (!Number.isInteger(value) || value < min || value > max) throw new RangeError(`${name} must be an integer between ${min} and ${max}.`);
1503
608
  return value;
1504
609
  }
1505
- function inputText(value, name2 = "Date", max = 256) {
1506
- if (typeof value !== "string") throw new TypeError(`${name2} must be text.`);
1507
- const text3 = value.trim();
1508
- if (!text3) throw new Error(`${name2} cannot be empty.`);
1509
- if (text3.length > max) throw new RangeError(`${name2} must be at most ${max} characters.`);
1510
- return text3;
610
+ function inputText(value, name = "Date", max = 256) {
611
+ if (typeof value !== "string") throw new TypeError(`${name} must be text.`);
612
+ const text2 = value.trim();
613
+ if (!text2) throw new Error(`${name} cannot be empty.`);
614
+ if (text2.length > max) throw new RangeError(`${name} must be at most ${max} characters.`);
615
+ return text2;
1511
616
  }
1512
617
  function isGregorianLeapYear(year) {
1513
618
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
@@ -1543,9 +648,9 @@ function timestampToDate(value, unit = "seconds") {
1543
648
  timestampUnit(unit);
1544
649
  let number;
1545
650
  if (typeof value === "string") {
1546
- const text3 = inputText(value, "Timestamp");
1547
- if (!/^[+-]?\d+(?:\.\d+)?$/.test(text3)) throw new Error("Timestamp must be a decimal number, without exponent notation.");
1548
- number = Number(text3);
651
+ const text2 = inputText(value, "Timestamp");
652
+ if (!/^[+-]?\d+(?:\.\d+)?$/.test(text2)) throw new Error("Timestamp must be a decimal number, without exponent notation.");
653
+ number = Number(text2);
1549
654
  } else if (typeof value === "number") number = value;
1550
655
  else throw new TypeError("Timestamp must be a number or numeric text.");
1551
656
  if (!Number.isFinite(number)) throw new RangeError("Timestamp must be finite.");
@@ -1629,9 +734,9 @@ function parseDateTime(value, options = {}) {
1629
734
  if (options.timeZone !== void 0) validateTimeZone(options.timeZone);
1630
735
  if (value instanceof Date) return checkedDate(value.getTime());
1631
736
  if (typeof value === "number") return timestampToDate(value, options.timestampUnit ?? "milliseconds");
1632
- const text3 = inputText(value);
1633
- if (/^[+-]?\d+(?:\.\d+)?$/.test(text3)) return timestampToDate(text3, options.timestampUnit ?? "milliseconds");
1634
- const match = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?([Zz]|[+-]\d{2}:?\d{2})?)?$/.exec(text3);
737
+ const text2 = inputText(value);
738
+ if (/^[+-]?\d+(?:\.\d+)?$/.test(text2)) return timestampToDate(text2, options.timestampUnit ?? "milliseconds");
739
+ const match = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?([Zz]|[+-]\d{2}:?\d{2})?)?$/.exec(text2);
1635
740
  if (!match) throw new Error("Use YYYY-MM-DD, an ISO date/time with up to 3 fractional digits, or an explicit numeric timestamp.");
1636
741
  return partsToDate({
1637
742
  year: Number(match[1]),
@@ -1764,11 +869,11 @@ function parseField(expression, spec) {
1764
869
  };
1765
870
  if (expression.length > 128) fail("field exceeds the 128-character limit.");
1766
871
  if (!expression) fail("field cannot be empty.");
1767
- const endpoint = (text3) => {
872
+ const endpoint = (text2) => {
1768
873
  let value;
1769
- if (/^\d+$/.test(text3)) value = Number(text3);
1770
- else if (spec.name === "month" && MONTH_NAMES.includes(text3.toUpperCase())) value = MONTH_NAMES.indexOf(text3.toUpperCase()) + 1;
1771
- else if (spec.name === "dayOfWeek" && WEEKDAY_NAMES.includes(text3.toUpperCase())) value = WEEKDAY_NAMES.indexOf(text3.toUpperCase());
874
+ if (/^\d+$/.test(text2)) value = Number(text2);
875
+ else if (spec.name === "month" && MONTH_NAMES.includes(text2.toUpperCase())) value = MONTH_NAMES.indexOf(text2.toUpperCase()) + 1;
876
+ else if (spec.name === "dayOfWeek" && WEEKDAY_NAMES.includes(text2.toUpperCase())) value = WEEKDAY_NAMES.indexOf(text2.toUpperCase());
1772
877
  else return fail("use integer values, permitted month/weekday names, *, ranges, lists or steps.");
1773
878
  if (!Number.isSafeInteger(value) || value < spec.min || value > spec.max) fail(`value must be between ${spec.min} and ${spec.max}.`);
1774
879
  return value;
@@ -1816,6 +921,12 @@ function parseCron(expression) {
1816
921
  const [minute, hour, dayOfMonth, month, dayOfWeek] = fields.slice(hasSeconds ? 1 : 0);
1817
922
  return { expression, hasSeconds, fields, second, minute, hour, dayOfMonth, month, dayOfWeek, dayMode: dayOfMonth.wildcard || dayOfWeek.wildcard ? "and" : "or" };
1818
923
  }
924
+ function matchesCronDate(cron, year, month, day) {
925
+ if (!cron.month.values.includes(month)) return false;
926
+ const dom = cron.dayOfMonth.values.includes(day);
927
+ const dow = cron.dayOfWeek.values.includes(new Date(Date.UTC(year, month - 1, day)).getUTCDay());
928
+ return cron.dayMode === "and" ? dom && dow : dom || dow;
929
+ }
1819
930
 
1820
931
  // lib/tools/cron/explain.ts
1821
932
  var FULL_MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
@@ -1837,622 +948,222 @@ function explainCron(cron) {
1837
948
  return `${timing}; ${days}${months}.`;
1838
949
  }
1839
950
 
1840
- // lib/tools/sql/builders.ts
1841
- init_types();
1842
- init_literals();
1843
-
1844
- // lib/tools/json-data/json.ts
1845
- import { Validator, format as schemaFormats } from "@cfworker/json-schema";
1846
- var MAX_INPUT = 1e6;
1847
- var MAX_NODES = 5e4;
1848
- var MAX_DEPTH = 100;
1849
- var sourceKeys = /* @__PURE__ */ new WeakMap();
1850
- var own = (value, key2) => Object.prototype.hasOwnProperty.call(value, key2);
1851
- var keys = (value) => sourceKeys.get(value) ?? Object.keys(value);
1852
- var jsonObjectKeys = keys;
1853
- function checkInput(input) {
1854
- if (input.length > MAX_INPUT) throw new Error("Input exceeds the 1,000,000-character limit. Split it into smaller documents.");
1855
- }
1856
- var JsonError = class extends Error {
1857
- constructor(input, offset, reason) {
1858
- const lines = input.slice(0, offset).split(/\r\n|\r|\n/);
1859
- const line = lines.length;
1860
- const column = lines[lines.length - 1].length + 1;
1861
- super(`${reason} (line ${line}, column ${column}).`);
1862
- this.line = line;
1863
- this.column = column;
1864
- }
1865
- };
1866
- function decimalIdentity(raw) {
1867
- const match = /^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(raw);
1868
- let digits = (match[2] + (match[3] ?? "")).replace(/^0+/, "");
1869
- if (!digits) return "0";
1870
- let exponent = Number(match[4] ?? 0) - (match[3]?.length ?? 0);
1871
- const trailing = /0+$/.exec(digits)?.[0].length ?? 0;
1872
- if (trailing) {
1873
- digits = digits.slice(0, -trailing);
1874
- exponent += trailing;
1875
- }
1876
- return `${match[1]}${digits}e${exponent}`;
1877
- }
1878
- function readJson(input, preserveNumbers = false) {
1879
- checkInput(input);
1880
- let position = 0;
1881
- let nodes = 0;
1882
- const tokens = [];
1883
- const fail = (reason, at = position) => {
1884
- throw new JsonError(input, at, reason);
1885
- };
1886
- const white = () => {
1887
- while (position < input.length && /[ \t\r\n]/.test(input[position])) position++;
1888
- };
1889
- const punctuation = () => {
1890
- const raw = input[position++];
1891
- tokens.push({ raw, kind: "punctuation" });
1892
- return raw;
1893
- };
1894
- const string = () => {
1895
- const start = position++;
1896
- while (position < input.length) {
1897
- const char = input[position++];
1898
- if (char === '"') {
1899
- const raw = input.slice(start, position);
1900
- try {
1901
- const value2 = JSON.parse(raw);
1902
- tokens.push({ raw, kind: "literal" });
1903
- return value2;
1904
- } catch {
1905
- return fail("Invalid JSON string or escape sequence", start);
951
+ // lib/tools/json-to-types.ts
952
+ function toPascalCase(str) {
953
+ const clean = str.replace(/[^a-zA-Z0-9]/g, " ");
954
+ return clean.split(/\s+/).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("") || "NestedType";
955
+ }
956
+ function isValidIdentifier(name) {
957
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
958
+ }
959
+ function formatKey(key) {
960
+ return isValidIdentifier(key) ? key : JSON.stringify(key);
961
+ }
962
+ function jsonToTypescript(jsonInput, rootName = "Root") {
963
+ let parsed;
964
+ try {
965
+ parsed = JSON.parse(jsonInput);
966
+ } catch (err) {
967
+ throw new Error(`Invalid JSON: ${err instanceof Error ? err.message : String(err)}`);
968
+ }
969
+ const interfaces = [];
970
+ const createdNames = /* @__PURE__ */ new Set();
971
+ function getUniqueName(base) {
972
+ let name = toPascalCase(base);
973
+ let counter = 1;
974
+ while (createdNames.has(name)) {
975
+ counter += 1;
976
+ name = `${toPascalCase(base)}${counter}`;
977
+ }
978
+ createdNames.add(name);
979
+ return name;
980
+ }
981
+ function resolveType(val, keyHint) {
982
+ if (val === null) return "null";
983
+ if (val === void 0) return "undefined";
984
+ const type = typeof val;
985
+ if (type === "string" || type === "number" || type === "boolean") {
986
+ return type;
987
+ }
988
+ if (Array.isArray(val)) {
989
+ if (val.length === 0) return "unknown[]";
990
+ const itemTypes = /* @__PURE__ */ new Set();
991
+ const sampleObjects = [];
992
+ for (const item of val) {
993
+ if (item && typeof item === "object" && !Array.isArray(item)) {
994
+ sampleObjects.push(item);
995
+ } else {
996
+ itemTypes.add(resolveType(item, `${keyHint}Item`));
1906
997
  }
1907
998
  }
1908
- if (char.charCodeAt(0) < 32) fail("Unescaped control character in JSON string", position - 1);
1909
- if (char === "\\") {
1910
- const escaped = input[position++];
1911
- if (escaped === "u") {
1912
- if (!/^[\da-fA-F]{4}$/.test(input.slice(position, position + 4))) fail("Unicode escapes require four hexadecimal digits", position);
1913
- position += 4;
1914
- } else if (!escaped || !'"\\/bfnrt'.includes(escaped)) fail("Invalid JSON escape sequence", position - 1);
1915
- }
1916
- }
1917
- return fail("Unterminated JSON string", start);
1918
- };
1919
- const value = (depth) => {
1920
- white();
1921
- if (depth > MAX_DEPTH) fail(`JSON nesting exceeds the ${MAX_DEPTH}-level limit`);
1922
- if (++nodes > MAX_NODES) fail(`JSON exceeds the ${MAX_NODES.toLocaleString("en-US")}-node limit`);
1923
- const char = input[position];
1924
- if (char === '"') return string();
1925
- if (char === "{" || char === "[") {
1926
- const isArray = punctuation() === "[";
1927
- const close = isArray ? "]" : "}";
1928
- const result2 = isArray ? [] : /* @__PURE__ */ Object.create(null);
1929
- const ordered = [];
1930
- white();
1931
- if (input[position] !== close) {
1932
- while (true) {
1933
- white();
1934
- if (isArray) result2.push(value(depth + 1));
1935
- else {
1936
- if (input[position] !== '"') fail("Expected a double-quoted object property name");
1937
- const keyPosition = position;
1938
- const key2 = string();
1939
- if (!preserveNumbers && own(result2, key2)) fail(`Duplicate object key ${JSON.stringify(key2)} is ambiguous for this transformation; no values were discarded`, keyPosition);
1940
- white();
1941
- if (input[position] !== ":") fail("Expected ':' after object property name");
1942
- punctuation();
1943
- result2[key2] = value(depth + 1);
1944
- ordered.push(key2);
999
+ if (sampleObjects.length > 0) {
1000
+ const merged = {};
1001
+ for (const obj of sampleObjects) {
1002
+ for (const [k, v] of Object.entries(obj)) {
1003
+ if (!merged[k]) merged[k] = { types: /* @__PURE__ */ new Set(), count: 0 };
1004
+ merged[k].count += 1;
1005
+ merged[k].types.add(resolveType(v, k));
1945
1006
  }
1946
- white();
1947
- if (input[position] === close) break;
1948
- if (input[position] !== ",") fail(`Expected ',' or '${close}'`);
1949
- punctuation();
1950
1007
  }
1008
+ const lines = [];
1009
+ for (const [k, meta] of Object.entries(merged)) {
1010
+ const isOptional = meta.count < sampleObjects.length;
1011
+ const typeStr = Array.from(meta.types).join(" | ") || "unknown";
1012
+ const formattedKey = formatKey(k) + (isOptional ? "?" : "");
1013
+ lines.push(` ${formattedKey}: ${typeStr};`);
1014
+ }
1015
+ const interfaceName = getUniqueName(`${keyHint}Item`);
1016
+ interfaces.unshift({
1017
+ name: interfaceName,
1018
+ body: `export interface ${interfaceName} {
1019
+ ${lines.join("\n")}
1020
+ }`
1021
+ });
1022
+ itemTypes.add(interfaceName);
1951
1023
  }
1952
- punctuation();
1953
- if (!isArray) sourceKeys.set(result2, ordered);
1954
- return result2;
1955
- }
1956
- const start = position;
1957
- const literal = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(input.slice(position))?.[0];
1958
- if (!literal) fail(position === input.length ? "Expected a JSON value; input is empty or incomplete" : "Expected a JSON value");
1959
- position += literal.length;
1960
- tokens.push({ raw: literal, kind: "literal" });
1961
- if (literal === "true") return true;
1962
- if (literal === "false") return false;
1963
- if (literal === "null") return null;
1964
- const number = Number(literal);
1965
- if (!preserveNumbers && (!Number.isFinite(number) || Number.isInteger(number) && !Number.isSafeInteger(number) || decimalIdentity(literal) !== decimalIdentity(String(number)))) {
1966
- fail(`Number ${literal.slice(0, 80)} cannot be represented without precision loss. Use a quoted string, or the source-preserving JSON Formatter/Minifier`, start);
1967
- }
1968
- return number;
1969
- };
1970
- const parsed = value(0);
1971
- white();
1972
- if (position !== input.length) fail("Unexpected characters after JSON value");
1973
- return { value: parsed, tokens };
1974
- }
1975
- function parseJson(input) {
1976
- return readJson(input).value;
1977
- }
1978
-
1979
- // lib/tools/json-data/csv.ts
1980
- function csvError(message, row, column) {
1981
- return new Error(`Row ${row}, column ${column}: ${message}`);
1982
- }
1983
- function checkDelimiter(delimiter) {
1984
- if (delimiter.length !== 1 || /["\r\n]/.test(delimiter)) {
1985
- throw new Error("Choose a single delimiter other than a quote or line break.");
1986
- }
1987
- }
1988
- function readRecords(input, delimiter) {
1989
- checkDelimiter(delimiter);
1990
- if (input.length === 0) throw new Error("Input is empty. Enter CSV data first.");
1991
- const records = [];
1992
- let values = [];
1993
- let field = "";
1994
- let state = "start";
1995
- let endedRecord = false;
1996
- const finishField = () => {
1997
- values.push(field);
1998
- field = "";
1999
- state = "start";
2000
- };
2001
- const finishRecord = () => {
2002
- finishField();
2003
- records.push({ values, row: records.length + 1 });
2004
- values = [];
2005
- };
2006
- for (let index = 0; index < input.length; index++) {
2007
- const character = input[index];
2008
- endedRecord = false;
2009
- if (state === "quoted") {
2010
- if (character === '"') {
2011
- if (input[index + 1] === '"') {
2012
- field += '"';
2013
- index++;
2014
- } else state = "closed";
2015
- } else field += character;
2016
- continue;
2017
- }
2018
- if (character === delimiter) {
2019
- finishField();
2020
- continue;
2021
- }
2022
- if (character === "\r" || character === "\n") {
2023
- if (character === "\r" && input[index + 1] === "\n") index++;
2024
- finishRecord();
2025
- endedRecord = true;
2026
- continue;
2027
- }
2028
- if (state === "closed") {
2029
- throw csvError("Unexpected text after a closing quote; expected a delimiter or line break.", records.length + 1, values.length + 1);
2030
- }
2031
- if (character === '"') {
2032
- if (state !== "start") throw csvError("A quote must start a field; escape embedded quotes inside a quoted field.", records.length + 1, values.length + 1);
2033
- state = "quoted";
2034
- } else {
2035
- field += character;
2036
- state = "plain";
2037
- }
2038
- }
2039
- if (state === "quoted") throw csvError("Unclosed quoted field.", records.length + 1, values.length + 1);
2040
- if (!endedRecord) finishRecord();
2041
- return records;
2042
- }
2043
- function rectangular(records) {
2044
- if (!records.length) throw new Error("Input is empty. Enter at least one nonblank CSV row.");
2045
- const width = records[0].values.length;
2046
- for (const record2 of records) {
2047
- if (record2.values.length !== width) {
2048
- throw csvError(`Expected ${width} columns but found ${record2.values.length}.`, record2.row, Math.min(width, record2.values.length) + 1);
2049
- }
2050
- }
2051
- return records.map((record2) => record2.values);
2052
- }
2053
- function parseCsv(input, delimiter = ",") {
2054
- return rectangular(readRecords(input, delimiter));
2055
- }
2056
-
2057
- // lib/tools/sql/builders.ts
2058
- function list(value, label, maximum) {
2059
- if (!Array.isArray(value)) throw new Error(`${label} must be a structured list.`);
2060
- if (value.length > maximum) throw new Error(`${label} exceeds the ${maximum}-item limit.`);
2061
- return value;
2062
- }
2063
- function record(value, label) {
2064
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object.`);
2065
- return value;
2066
- }
2067
- function identifiers(value, dialect, label = "Columns", allowEmpty = false) {
2068
- const names = list(value, label, 100).map((name2) => sqlText(name2, label));
2069
- if (!allowEmpty && !names.length) throw new Error(`${label} must contain at least one column.`);
2070
- names.forEach((name2) => quoteIdentifier(name2, dialect));
2071
- if (new Set(names.map((name2) => dialect === "PostgreSQL" ? name2 : name2.toLocaleLowerCase("en-US"))).size !== names.length) throw new Error(`${label} cannot contain duplicate column names.`);
2072
- return names;
2073
- }
2074
- function result(label, value, warnings) {
2075
- if (value.length > 2e6) throw new Error("Generated SQL exceeds the 2,000,000-character output limit.");
2076
- return { rows: [{ label, value }], ...warnings?.length ? { warnings } : {} };
2077
- }
2078
- function buildConditions(value, dialect, logicalOperator = "AND") {
2079
- if (logicalOperator !== "AND" && logicalOperator !== "OR") throw new Error("Logical operator must be AND or OR.");
2080
- let outputLength = 0;
2081
- const checkedLiteral = (literal) => {
2082
- const output2 = sqlLiteral(literal, dialect);
2083
- outputLength += output2.length;
2084
- if (outputLength > 2e6) throw new Error("Generated SQL exceeds the 2,000,000-character output limit.");
2085
- return output2;
2086
- };
2087
- return list(value, "Conditions", 100).map((item, index) => {
2088
- const condition = record(item, `Condition ${index + 1}`);
2089
- const column = quoteIdentifier(sqlText(condition.column, "Condition column"), dialect);
2090
- const operator = condition.operator;
2091
- if (typeof operator !== "string" || !CONDITION_OPERATORS.includes(operator)) throw new Error("Choose a supported condition operator.");
2092
- const values = list(condition.values, "Condition values", 100);
2093
- if (operator === "IS NULL" || operator === "IS NOT NULL") {
2094
- if (values.length) throw new Error(`${operator} must have no values.`);
2095
- return `${column} ${operator}`;
2096
- }
2097
- const multiple = operator === "IN" || operator === "NOT IN";
2098
- if (!values.length || !multiple && values.length !== 1) throw new Error(multiple ? `${operator} requires at least one value.` : `${operator} requires exactly one value.`);
2099
- const literals = values.map((item2) => {
2100
- const literal = record(item2, "Condition value");
2101
- if (literal.type === "NULL") throw new Error("Use IS NULL or IS NOT NULL to compare NULL values.");
2102
- if ((operator === "LIKE" || operator === "NOT LIKE") && literal.type !== "String") throw new Error("LIKE and NOT LIKE require a String value.");
2103
- return checkedLiteral(literal);
2104
- });
2105
- return `${column} ${operator} ${multiple ? `(${literals.join(", ")})` : literals[0]}`;
2106
- }).join(` ${logicalOperator} `);
2107
- }
2108
- function insert(table, columns2, rows, dialect) {
2109
- if (!rows.length) throw new Error("No rows. Provide at least one data row.");
2110
- if (rows.length > 1e3) throw new Error("Rows exceed the 1,000-row limit.");
2111
- return `INSERT INTO ${table} (${columns2.map((column) => quoteIdentifier(column, dialect)).join(", ")})
2112
- VALUES
2113
- ${rows.map((row) => {
2114
- if (row.length !== columns2.length) throw new Error("Every row must have exactly one value per column.");
2115
- return ` (${row.join(", ")})`;
2116
- }).join(",\n")};`;
2117
- }
2118
- async function runBuilder(toolId, values) {
2119
- const dialect = readDialect(values.dialect);
2120
- let outputLength = 0;
2121
- const checkedLiteral = (literal) => {
2122
- const output2 = sqlLiteral(literal, dialect);
2123
- outputLength += output2.length;
2124
- if (outputLength > 2e6) throw new Error("Generated SQL exceeds the 2,000,000-character output limit.");
2125
- return output2;
2126
- };
2127
- if (toolId === "sql-escape-helper") {
2128
- return result("Escaped SQL literal", sqlLiteral({ type: values.valueType, value: sqlText(values.value, "Value") }, dialect));
2129
- }
2130
- if (toolId === "sql-where-builder") {
2131
- const logicalOperator = values.logicalOperator;
2132
- if (logicalOperator !== "AND" && logicalOperator !== "OR") throw new Error("Logical operator must be AND or OR.");
2133
- const conditions2 = buildConditions(values.conditions, dialect, logicalOperator);
2134
- if (!conditions2) throw new Error("Provide at least one condition.");
2135
- return result("SQL WHERE clause", `WHERE ${conditions2}`);
2136
- }
2137
- const table = quoteIdentifier(sqlText(values.table, "Table"), dialect, true);
2138
- if (toolId === "json-to-sql") {
2139
- const parsed = parseJson(sqlText(values.json, "JSON"));
2140
- const rows = list(parsed, "JSON rows", 1e3);
2141
- if (!rows.length) throw new Error("No rows. Provide a nonempty JSON array of objects.");
2142
- const objects = rows.map((row, index) => record(row, `JSON row ${index + 1}`));
2143
- const columns2 = identifiers(jsonObjectKeys(objects[0]), dialect);
2144
- const keys2 = new Set(columns2);
2145
- const literals = objects.map((object, index) => {
2146
- const rowKeys = jsonObjectKeys(object);
2147
- if (rowKeys.length !== columns2.length || rowKeys.some((key2) => !keys2.has(key2))) throw new Error(`JSON row ${index + 1} must have exactly the same keys as the first row.`);
2148
- return columns2.map((column) => jsonLiteral(object[column], dialect));
2149
- });
2150
- return result("SQL INSERT statements", insert(table, columns2, literals, dialect));
2151
- }
2152
- if (toolId === "csv-to-sql") {
2153
- const csv = sqlText(values.csv, "CSV").replace(/^\uFEFF/, "");
2154
- const records = parseCsv(csv);
2155
- const columns2 = identifiers(records[0], dialect, "CSV headers");
2156
- if (records.length > 1001) throw new Error("CSV data exceeds the 1,000-row limit.");
2157
- return result("SQL INSERT statements", insert(table, columns2, records.slice(1).map((row) => row.map((value) => sqlLiteral({ type: "String", value }, dialect))), dialect));
2158
- }
2159
- if (toolId === "sql-insert-generator") {
2160
- const columns2 = identifiers(values.columns, dialect);
2161
- const rows = list(values.rows, "Rows", 1e3).map((row) => {
2162
- const cells = list(row, "Row values", 100);
2163
- if (cells.length !== columns2.length) throw new Error("Every row must have exactly one value per column.");
2164
- return cells.map((cell) => checkedLiteral(record(cell, "Row value")));
2165
- });
2166
- return result("SQL INSERT statement", insert(table, columns2, rows, dialect));
2167
- }
2168
- const conditions = buildConditions(values.conditions, dialect);
2169
- const where = conditions ? `
2170
- WHERE ${conditions}` : "";
2171
- if (toolId === "sql-update-generator") {
2172
- const assignments = list(values.assignments, "Assignments", 100).map((item) => record(item, "Assignment"));
2173
- const columns2 = identifiers(assignments.map((item) => item.column), dialect, "Assignment columns");
2174
- const set = assignments.map((item, index) => `${quoteIdentifier(columns2[index], dialect)} = ${checkedLiteral(record(item.value, "Assignment value"))}`).join(",\n ");
2175
- return result("SQL UPDATE statement", `UPDATE ${table}
2176
- SET ${set}${where};`, conditions ? void 0 : ["This UPDATE has no WHERE clause and may affect every row."]);
2177
- }
2178
- if (toolId === "sql-delete-generator") {
2179
- return result("SQL DELETE statement", `DELETE FROM ${table}${where};`, conditions ? void 0 : ["This DELETE has no WHERE clause and may delete every row."]);
2180
- }
2181
- if (toolId === "sql-select-builder") {
2182
- const columns2 = identifiers(values.columns, dialect, "Columns", true);
2183
- const orders = list(values.orderBy, "ORDER BY", 100).map((item) => record(item, "Order"));
2184
- identifiers(orders.map((order) => order.column), dialect, "ORDER BY columns", true);
2185
- const orderSql = orders.map((order) => {
2186
- if (order.direction !== "ASC" && order.direction !== "DESC") throw new Error("ORDER BY direction must be ASC or DESC.");
2187
- return `${quoteIdentifier(sqlText(order.column, "ORDER BY column"), dialect)} ${order.direction}`;
2188
- });
2189
- const limit = values.limit === void 0 ? "" : sqlText(values.limit, "Limit");
2190
- if (limit && (!/^[1-9]\d{0,6}$/.test(limit) || Number(limit) > 1e6)) throw new Error("Limit must be a positive integer from 1 to 1,000,000.");
2191
- const top = limit && dialect === "SQL Server" ? ` TOP (${limit})` : "";
2192
- const tail = limit && dialect !== "SQL Server" ? `
2193
- LIMIT ${limit}` : "";
2194
- return result("SQL SELECT statement", `SELECT${top} ${columns2.length ? columns2.map((column) => quoteIdentifier(column, dialect)).join(", ") : "*"}
2195
- FROM ${table}${where}${orderSql.length ? `
2196
- ORDER BY ${orderSql.join(", ")}` : ""}${tail};`);
2197
- }
2198
- throw new Error("Unsupported SQL builder.");
2199
- }
1024
+ const union = Array.from(itemTypes).join(" | ");
1025
+ return union.includes(" | ") ? `(${union})[]` : `${union}[]`;
1026
+ }
1027
+ if (type === "object") {
1028
+ const obj = val;
1029
+ const lines = [];
1030
+ for (const [k, v] of Object.entries(obj)) {
1031
+ const typeStr = resolveType(v, k);
1032
+ lines.push(` ${formatKey(k)}: ${typeStr};`);
1033
+ }
1034
+ const interfaceName = getUniqueName(keyHint);
1035
+ interfaces.unshift({
1036
+ name: interfaceName,
1037
+ body: `export interface ${interfaceName} {
1038
+ ${lines.join("\n")}
1039
+ }`
1040
+ });
1041
+ return interfaceName;
1042
+ }
1043
+ return "unknown";
1044
+ }
1045
+ const rootTypeName = toPascalCase(rootName) || "Root";
1046
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1047
+ const rootType = resolveType(parsed, rootTypeName);
1048
+ const found = interfaces.find((i) => i.name === rootType);
1049
+ if (found) {
1050
+ found.name = rootTypeName;
1051
+ found.body = found.body.replace(`export interface ${rootType}`, `export interface ${rootTypeName}`);
1052
+ }
1053
+ return interfaces.map((i) => i.body).join("\n\n");
1054
+ } else if (Array.isArray(parsed)) {
1055
+ const itemType = resolveType(parsed, rootTypeName);
1056
+ return `${interfaces.map((i) => i.body).join("\n\n")}
2200
1057
 
2201
- // lib/tools/sql/connections.ts
2202
- init_literals();
2203
- var defaults = { PostgreSQL: "5432", MySQL: "3306", "SQL Server": "1433" };
2204
- var mask = "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";
2205
- var normalize = (key2) => key2.toLowerCase().replace(/[\s_-]/g, "");
2206
- var coreNames = /* @__PURE__ */ new Set(["host", "hostname", "server", "datasource", "address", "addr", "networkaddress", "port", "database", "dbname", "initialcatalog", "username", "user", "userid", "uid", "password", "pwd", "pass"]);
2207
- var privateName = (key2) => /password|pwd|passphrase|token|secret|credential|auth|(?:^|[\s_-])key|accesskey|privatekey|sslkey|clientkey|certificate|signature|sastoken/i.test(key2) || /^(pass|apikey|key)$/i.test(normalize(key2));
2208
- function text2(value, label, required = false) {
2209
- const result2 = sqlText(value, label);
2210
- if (/[\x00-\x1f\x7f]/.test(result2)) throw new Error(`${label} cannot contain control characters.`);
2211
- if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(result2)) throw new Error(`${label} must contain valid Unicode.`);
2212
- if (required && !result2.trim()) throw new Error(`${label} is required.`);
2213
- return result2;
2214
- }
2215
- function port(value, type) {
2216
- if (!value) return defaults[type];
2217
- if (!/^[1-9]\d{0,4}$/.test(value) || Number(value) > 65535) throw new Error("Port must be an integer from 1 to 65,535, or blank for the database default.");
2218
- return value;
2219
- }
2220
- function host(value) {
2221
- if (!value || value !== value.trim() || /[\s/?@#\\]/u.test(value)) throw new Error("Host must be a hostname, IP address, or IPv6 address without a scheme, path, or credentials.");
2222
- if (value.includes(":")) {
2223
- const bracketed = value.startsWith("[") && value.endsWith("]") ? value : `[${value}]`;
2224
- try {
2225
- const url = new URL(`http://${bracketed}/`);
2226
- if (!url.hostname.startsWith("[")) throw new Error();
2227
- return url.hostname;
2228
- } catch {
2229
- throw new Error("Enter a valid IPv6 address; zone identifiers and host:port syntax are unsupported.");
2230
- }
2231
- }
2232
- if (!/^[\p{L}\p{N}._-]+$/u.test(value) || value.length > 253) throw new Error("Enter a valid hostname or IP address.");
2233
- try {
2234
- return new URL(`http://${value}/`).hostname;
2235
- } catch {
2236
- throw new Error("Enter a valid hostname or IP address.");
2237
- }
2238
- }
2239
- function decode(value, query = false) {
2240
- try {
2241
- return decodeURIComponent(query ? value.replace(/\+/g, " ") : value);
2242
- } catch {
2243
- throw new Error("Connection string contains invalid percent encoding.");
2244
- }
2245
- }
2246
- function validateParameters(parameters2, rejectCore) {
2247
- if (parameters2.length > 100) throw new Error("Parameters exceed the 100-entry limit.");
2248
- const seen = /* @__PURE__ */ new Set();
2249
- return parameters2.map(({ key: key2, value }) => {
2250
- if (!/^[A-Za-z][A-Za-z0-9 ._-]{0,127}$/.test(key2)) throw new Error("Parameter names must start with a letter and contain only letters, numbers, spaces, dots, underscores, or hyphens.");
2251
- const normalized = normalize(key2);
2252
- if (seen.has(normalized)) throw new Error("Duplicate connection parameter names are unsupported.");
2253
- seen.add(normalized);
2254
- if (rejectCore && coreNames.has(normalized)) throw new Error("Parameters cannot override host, port, database, username, or password fields.");
2255
- return { key: key2, value: text2(value, "Parameter value") };
2256
- });
2257
- }
2258
- function parameters(value) {
2259
- if (!value.trim()) return [];
2260
- if (value.startsWith("?") || value.includes("&") && !/[\r\n]/.test(value)) return queryParameters(value.replace(/^\?/, ""));
2261
- return validateParameters(value.split(/\r\n|\r|\n/).filter((line) => line.trim() !== "").map((line) => {
2262
- const equals = line.indexOf("=");
2263
- if (equals < 1) throw new Error("Parameters must use one key=value per line, or URL query syntax beginning with ?.");
2264
- return { key: line.slice(0, equals).trim(), value: line.slice(equals + 1) };
2265
- }), true);
2266
- }
2267
- function queryParameters(query, rejectCore = true) {
2268
- if (!query) return [];
2269
- return validateParameters(query.split("&").map((pair) => {
2270
- const equals = pair.indexOf("=");
2271
- if (equals < 1) throw new Error("Each URL parameter must use key=value syntax.");
2272
- return { key: decode(pair.slice(0, equals), true), value: decode(pair.slice(equals + 1), true) };
2273
- }), rejectCore);
2274
- }
2275
- function adoQuote(value) {
2276
- return `"${value.replace(/"/g, '""')}"`;
2277
- }
2278
- function build(values) {
2279
- const type = values.databaseType;
2280
- if (type !== "PostgreSQL" && type !== "MySQL" && type !== "SQL Server") throw new Error("Choose PostgreSQL, MySQL, or SQL Server.");
2281
- const hostname = host(text2(values.host, "Host", true));
2282
- const serverPort = port(text2(values.port, "Port"), type);
2283
- const database = text2(values.database, "Database", true);
2284
- const username = text2(values.username, "Username", true);
2285
- const password = text2(values.password, "Password");
2286
- const extra = parameters(values.parameters === void 0 ? "" : sqlText(values.parameters, "Parameters"));
2287
- let connection;
2288
- if (type === "SQL Server") {
2289
- connection = `Data Source=${adoQuote(`${hostname},${serverPort}`)};Initial Catalog=${adoQuote(database)};User ID=${adoQuote(username)};Password=${adoQuote(password)};${extra.map((item) => `${item.key}=${adoQuote(item.value)};`).join("")}`;
1058
+ export type ${rootTypeName} = ${itemType};`.trim();
2290
1059
  } else {
2291
- const query = extra.length ? `?${extra.map((item) => `${encodeURIComponent(item.key)}=${encodeURIComponent(item.value)}`).join("&")}` : "";
2292
- connection = `${type === "PostgreSQL" ? "postgresql" : "mysql"}://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${hostname}:${serverPort}/${encodeURIComponent(database)}${query}`;
1060
+ const primitiveType = resolveType(parsed, rootTypeName);
1061
+ return `export type ${rootTypeName} = ${primitiveType};`;
2293
1062
  }
2294
- if (connection.length > 2e6) throw new Error("Connection string exceeds the output limit.");
2295
- return { rows: [{ label: "Connection string", value: connection }] };
2296
1063
  }
2297
- function redacted(item) {
2298
- let inspection = item.value;
2299
- for (let round = 0; round < 2; round++) {
2300
- try {
2301
- inspection = decodeURIComponent(inspection);
2302
- } catch {
2303
- break;
2304
- }
2305
- }
2306
- const secretValue = /[a-z][a-z\d+.-]*:\/\/[^\s/]*@/i.test(inspection) || /(?:password|pwd|token|secret|credential|auth|access.?key|private.?key|api.?key|signature)\s*(?:=|:)/i.test(inspection);
2307
- return { key: item.key, value: privateName(item.key) || secretValue ? mask : item.value };
2308
- }
2309
- function output(type, hostname, serverPort, database, username, extra) {
2310
- return { rows: [
2311
- { label: "Database type", value: type },
2312
- { label: "Host", value: hostname },
2313
- { label: "Port", value: serverPort },
2314
- { label: "Database name", value: database },
2315
- { label: "Username", value: username },
2316
- { label: "Masked password", value: mask },
2317
- { label: "Parameters", value: extra.length ? extra.map(redacted).map((item) => `${item.key}=${item.value}`).join("\n") : "None" }
2318
- ] };
2319
- }
2320
- function parseUri(input) {
2321
- const scheme = /^(postgresql|postgres|mysql):\/\//i.exec(input);
2322
- if (!scheme) throw new Error("Use a PostgreSQL/MySQL URI or a SQL Server ADO.NET connection string.");
2323
- const type = scheme[1].toLowerCase() === "mysql" ? "MySQL" : "PostgreSQL";
2324
- const authority = input.slice(scheme[0].length).split(/[/?#]/, 1)[0];
2325
- if ((authority.match(/@/g) ?? []).length > 1) throw new Error("Encode @ inside URI credentials; multiple userinfo separators are ambiguous.");
2326
- if (input.includes("#")) throw new Error("Connection URI fragments are unsupported; encode # inside field values.");
2327
- let url;
1064
+ function jsonToZod(jsonInput, rootName = "rootSchema") {
1065
+ let parsed;
2328
1066
  try {
2329
- url = new URL(input);
2330
- } catch {
2331
- throw new Error("Invalid database connection URI.");
2332
- }
2333
- const username = text2(decode(url.username), "Username");
2334
- text2(decode(url.password), "Password");
2335
- const database = text2(decode(url.pathname.replace(/^\//, "")), "Database", true);
2336
- if (url.pathname.slice(1).includes("/")) throw new Error("Database paths must be one encoded path segment.");
2337
- const hostname = host(url.hostname);
2338
- const serverPort = port(url.port, type);
2339
- const extra = queryParameters(url.search.replace(/^\?/, ""));
2340
- return output(type, hostname, serverPort, database, username, extra);
2341
- }
2342
- function adoParameters(input) {
2343
- const pairs = [];
2344
- let position = 0;
2345
- while (position < input.length) {
2346
- while (/[\s;]/.test(input[position] ?? "") && position < input.length) position++;
2347
- if (position === input.length) break;
2348
- const start = position;
2349
- while (position < input.length && input[position] !== "=" && input[position] !== ";") position++;
2350
- if (input[position] !== "=") throw new Error("ADO.NET connection entries must use key=value syntax.");
2351
- const key2 = input.slice(start, position++).trim();
2352
- while (input[position] === " ") position++;
2353
- let value = "";
2354
- const quote = input[position];
2355
- if (quote === '"' || quote === "'") {
2356
- position++;
2357
- let closed = false;
2358
- while (position < input.length) {
2359
- const character = input[position++];
2360
- if (character !== quote) {
2361
- value += character;
2362
- continue;
2363
- }
2364
- if (input[position] === quote) {
2365
- value += quote;
2366
- position++;
1067
+ parsed = JSON.parse(jsonInput);
1068
+ } catch (err) {
1069
+ throw new Error(`Invalid JSON: ${err instanceof Error ? err.message : String(err)}`);
1070
+ }
1071
+ const schemas = [];
1072
+ const createdNames = /* @__PURE__ */ new Set();
1073
+ function getUniqueName(base) {
1074
+ let name = base.endsWith("Schema") ? base : `${base}Schema`;
1075
+ let counter = 1;
1076
+ while (createdNames.has(name)) {
1077
+ counter += 1;
1078
+ name = `${base}${counter}Schema`;
1079
+ }
1080
+ createdNames.add(name);
1081
+ return name;
1082
+ }
1083
+ function resolveZod(val, keyHint) {
1084
+ if (val === null) return "z.null()";
1085
+ if (val === void 0) return "z.undefined()";
1086
+ if (typeof val === "string") return "z.string()";
1087
+ if (typeof val === "number") return Number.isInteger(val) ? "z.number().int()" : "z.number()";
1088
+ if (typeof val === "boolean") return "z.boolean()";
1089
+ if (Array.isArray(val)) {
1090
+ if (val.length === 0) return "z.array(z.unknown())";
1091
+ const sampleObjects = [];
1092
+ const itemSchemas = /* @__PURE__ */ new Set();
1093
+ for (const item of val) {
1094
+ if (item && typeof item === "object" && !Array.isArray(item)) {
1095
+ sampleObjects.push(item);
2367
1096
  } else {
2368
- closed = true;
2369
- break;
1097
+ itemSchemas.add(resolveZod(item, `${keyHint}Item`));
2370
1098
  }
2371
1099
  }
2372
- if (!closed) throw new Error("ADO.NET connection string has an unclosed quoted value.");
2373
- while (input[position] === " ") position++;
2374
- if (position < input.length && input[position] !== ";") throw new Error("Unexpected text after a quoted ADO.NET value.");
2375
- } else {
2376
- const startValue = position;
2377
- while (position < input.length && input[position] !== ";") position++;
2378
- value = input.slice(startValue, position).trim();
2379
- if (/["']/.test(value)) throw new Error("Quote the entire ADO.NET value when it contains quotes.");
1100
+ if (sampleObjects.length > 0) {
1101
+ const merged = {};
1102
+ for (const obj of sampleObjects) {
1103
+ for (const [k, v] of Object.entries(obj)) {
1104
+ if (!merged[k]) merged[k] = { schemas: /* @__PURE__ */ new Set(), count: 0 };
1105
+ merged[k].count += 1;
1106
+ merged[k].schemas.add(resolveZod(v, k));
1107
+ }
1108
+ }
1109
+ const lines = [];
1110
+ for (const [k, meta] of Object.entries(merged)) {
1111
+ const isOptional = meta.count < sampleObjects.length;
1112
+ let schemaStr = Array.from(meta.schemas)[0] || "z.unknown()";
1113
+ if (meta.schemas.size > 1) {
1114
+ schemaStr = `z.union([${Array.from(meta.schemas).join(", ")}])`;
1115
+ }
1116
+ if (isOptional) {
1117
+ schemaStr += ".optional()";
1118
+ }
1119
+ lines.push(` ${formatKey(k)}: ${schemaStr},`);
1120
+ }
1121
+ const schemaName = getUniqueName(`${keyHint}Item`);
1122
+ schemas.unshift({
1123
+ name: schemaName,
1124
+ body: `export const ${schemaName} = z.object({
1125
+ ${lines.join("\n")}
1126
+ });`
1127
+ });
1128
+ itemSchemas.add(schemaName);
1129
+ }
1130
+ const union = Array.from(itemSchemas);
1131
+ if (union.length === 1) return `z.array(${union[0]})`;
1132
+ return `z.array(z.union([${union.join(", ")}]))`;
1133
+ }
1134
+ if (typeof val === "object") {
1135
+ const obj = val;
1136
+ const lines = [];
1137
+ for (const [k, v] of Object.entries(obj)) {
1138
+ lines.push(` ${formatKey(k)}: ${resolveZod(v, k)},`);
1139
+ }
1140
+ const schemaName = getUniqueName(keyHint);
1141
+ schemas.unshift({
1142
+ name: schemaName,
1143
+ body: `export const ${schemaName} = z.object({
1144
+ ${lines.join("\n")}
1145
+ });`
1146
+ });
1147
+ return schemaName;
2380
1148
  }
2381
- pairs.push({ key: key2, value });
2382
- if (input[position] === ";") position++;
2383
- if (pairs.length > 100) throw new Error("Connection entries exceed the 100-entry limit.");
1149
+ return "z.unknown()";
2384
1150
  }
2385
- return validateParameters(pairs, false);
2386
- }
2387
- function parseAdo(input) {
2388
- const pairs = adoParameters(input);
2389
- const aliases = {
2390
- server: "host",
2391
- datasource: "host",
2392
- address: "host",
2393
- addr: "host",
2394
- networkaddress: "host",
2395
- host: "host",
2396
- initialcatalog: "database",
2397
- database: "database",
2398
- dbname: "database",
2399
- userid: "username",
2400
- uid: "username",
2401
- user: "username",
2402
- username: "username",
2403
- password: "password",
2404
- pwd: "password",
2405
- pass: "password",
2406
- port: "port"
2407
- };
2408
- const core = /* @__PURE__ */ new Map();
2409
- const extra = [];
2410
- for (const pair of pairs) {
2411
- const normalized = normalize(pair.key);
2412
- const key2 = Object.prototype.hasOwnProperty.call(aliases, normalized) ? aliases[normalized] : void 0;
2413
- if (!key2) {
2414
- extra.push(pair);
2415
- continue;
2416
- }
2417
- if (core.has(key2)) throw new Error("Connection string contains duplicate aliases for a core field.");
2418
- core.set(key2, pair.value);
1151
+ const safeRootName = rootName.endsWith("Schema") ? rootName : `${rootName}Schema`;
1152
+ const typeName = toPascalCase(rootName.replace(/Schema$/i, "")) || "Root";
1153
+ const rootResult = resolveZod(parsed, safeRootName);
1154
+ const found = schemas.find((s) => s.name === rootResult);
1155
+ if (found) {
1156
+ found.name = safeRootName;
1157
+ found.body = found.body.replace(`export const ${rootResult}`, `export const ${safeRootName}`);
2419
1158
  }
2420
- const source = (core.get("host") ?? "").replace(/^tcp:/i, "");
2421
- const parts = source.split(",");
2422
- if (parts.length > 2 || parts.length === 2 && core.has("port")) throw new Error("SQL Server host and port are ambiguous; supply one port.");
2423
- const hostname = host(parts[0].trim());
2424
- const serverPort = port((parts[1] ?? core.get("port") ?? "").trim(), "SQL Server");
2425
- const database = text2(core.get("database") ?? "", "Database", true);
2426
- return output("SQL Server", hostname, serverPort, database, core.get("username") ?? "", extra);
2427
- }
2428
- function runConnection(toolId, values) {
2429
- if (toolId === "database-connection-string-builder") return build(values);
2430
- if (toolId !== "database-connection-string-parser") throw new Error("Unsupported connection string tool.");
2431
- const input = sqlText(values.connectionString, "Connection string").trim();
2432
- if (!input) throw new Error("Enter a connection string.");
2433
- if (/[\x00-\x1f\x7f]/.test(input)) throw new Error("Connection strings cannot contain control characters.");
2434
- return /^[A-Za-z][A-Za-z\d+.-]*:\/\//.test(input) ? parseUri(input) : parseAdo(input);
2435
- }
1159
+ const header = `import { z } from "zod";
2436
1160
 
2437
- // lib/tools/sql/engine.ts
2438
- init_literals();
2439
- async function runSql(toolId, values) {
2440
- let result2;
2441
- if (toolId === "database-connection-string-builder" || toolId === "database-connection-string-parser") {
2442
- result2 = runConnection(toolId, values);
2443
- } else if (["sql-formatter", "sql-minifier", "sql-validator", "sql-to-json", "sql-to-csv", "sql-to-markdown", "er-diagram-generator"].includes(toolId)) {
2444
- const dialect = readDialect(values.dialect);
2445
- const sql = sqlText(values.sql, "SQL");
2446
- if (toolId === "er-diagram-generator") {
2447
- const { ddlOutput: ddlOutput2 } = await Promise.resolve().then(() => (init_ddl(), ddl_exports));
2448
- result2 = await ddlOutput2(sql, dialect);
2449
- } else {
2450
- const { formatSqlTool: formatSqlTool2, minifySqlTool: minifySqlTool2, validateSqlTool: validateSqlTool2, insertOutput: insertOutput2 } = await Promise.resolve().then(() => (init_transforms(), transforms_exports));
2451
- result2 = toolId === "sql-formatter" ? await formatSqlTool2(sql, dialect) : toolId === "sql-minifier" ? await minifySqlTool2(sql, dialect) : toolId === "sql-validator" ? await validateSqlTool2(sql, dialect) : await insertOutput2(toolId, sql, dialect);
2452
- }
2453
- } else result2 = await runBuilder(toolId, values);
2454
- if (JSON.stringify(result2).length > 2e6) throw new Error("The complete result exceeds the 2,000,000-character output budget. Use a smaller input.");
2455
- return result2;
1161
+ `;
1162
+ const schemaDeclarations = schemas.map((s) => s.body).join("\n\n");
1163
+ const typeExport = `
1164
+
1165
+ export type ${typeName} = z.infer<typeof ${safeRootName}>;`;
1166
+ return header + (schemaDeclarations ? `${schemaDeclarations}${typeExport}` : `export const ${safeRootName} = ${rootResult};${typeExport}`);
2456
1167
  }
2457
1168
 
2458
1169
  // mcp/server.ts
@@ -2763,19 +1474,43 @@ function createMcpServer(cliKey) {
2763
1474
  },
2764
1475
  required: ["json"]
2765
1476
  }
1477
+ },
1478
+ {
1479
+ name: "codestation_json_to_typescript",
1480
+ description: "Generate clean TypeScript interfaces and types from sample JSON data. [Pro Tier: \u20B9199/mo or $2.99/mo]",
1481
+ inputSchema: {
1482
+ type: "object",
1483
+ properties: {
1484
+ json: { type: "string", description: "Sample JSON string or object representation" },
1485
+ rootName: { type: "string", description: "Name for the root interface (default: 'Root')" }
1486
+ },
1487
+ required: ["json"]
1488
+ }
1489
+ },
1490
+ {
1491
+ name: "codestation_json_to_zod",
1492
+ description: "Generate production-ready Zod validation schema and inferred types from sample JSON data. [Pro Tier: \u20B9199/mo or $2.99/mo]",
1493
+ inputSchema: {
1494
+ type: "object",
1495
+ properties: {
1496
+ json: { type: "string", description: "Sample JSON string or object representation" },
1497
+ rootName: { type: "string", description: "Name for the root schema (default: 'rootSchema')" }
1498
+ },
1499
+ required: ["json"]
1500
+ }
2766
1501
  }
2767
1502
  ];
2768
1503
  server.setRequestHandler(ListToolsRequestSchema, async () => {
2769
1504
  return { tools };
2770
1505
  });
2771
1506
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
2772
- const { name: name2, arguments: args = {} } = request.params;
2773
- if (PRO_TOOLS.has(name2) && !license.isPro) {
1507
+ const { name, arguments: args = {} } = request.params;
1508
+ if (PRO_TOOLS.has(name) && !license.isPro) {
2774
1509
  return {
2775
1510
  content: [
2776
1511
  {
2777
1512
  type: "text",
2778
- text: getProUpgradeNotice(name2)
1513
+ text: getProUpgradeNotice(name)
2779
1514
  }
2780
1515
  ],
2781
1516
  isError: true
@@ -2783,7 +1518,7 @@ function createMcpServer(cliKey) {
2783
1518
  }
2784
1519
  try {
2785
1520
  let outputText = "";
2786
- switch (name2) {
1521
+ switch (name) {
2787
1522
  // --- Free tools ---
2788
1523
  case "codestation_uuid": {
2789
1524
  const count = Math.min(Math.max(Number(args.count ?? 1), 1), 50);
@@ -2792,34 +1527,34 @@ function createMcpServer(cliKey) {
2792
1527
  break;
2793
1528
  }
2794
1529
  case "codestation_base64": {
2795
- const text3 = String(args.text ?? "");
1530
+ const text2 = String(args.text ?? "");
2796
1531
  const action = String(args.action ?? "encode");
2797
1532
  const urlSafe = Boolean(args.urlSafe);
2798
1533
  if (action === "encode") {
2799
1534
  if (urlSafe) {
2800
- outputText = encodeBase64Url(text3);
1535
+ outputText = encodeBase64Url(text2);
2801
1536
  } else {
2802
- outputText = Buffer.from(text3, "utf-8").toString("base64");
1537
+ outputText = Buffer.from(text2, "utf-8").toString("base64");
2803
1538
  }
2804
1539
  } else {
2805
1540
  if (urlSafe) {
2806
- outputText = decodeBase64Url(text3);
1541
+ outputText = decodeBase64Url(text2);
2807
1542
  } else {
2808
- outputText = Buffer.from(text3, "base64").toString("utf-8");
1543
+ outputText = Buffer.from(text2, "base64").toString("utf-8");
2809
1544
  }
2810
1545
  }
2811
1546
  break;
2812
1547
  }
2813
1548
  case "codestation_url_codec": {
2814
- const text3 = String(args.text ?? "");
1549
+ const text2 = String(args.text ?? "");
2815
1550
  const action = String(args.action ?? "encode");
2816
- outputText = action === "encode" ? encodeUrlComponent(text3) : decodeUrlComponent(text3);
1551
+ outputText = action === "encode" ? encodeUrlComponent(text2) : decodeUrlComponent(text2);
2817
1552
  break;
2818
1553
  }
2819
1554
  case "codestation_hex_codec": {
2820
- const text3 = String(args.text ?? "");
1555
+ const text2 = String(args.text ?? "");
2821
1556
  const action = String(args.action ?? "encode");
2822
- outputText = action === "encode" ? encodeHexadecimal(text3) : decodeHexadecimal(text3);
1557
+ outputText = action === "encode" ? encodeHexadecimal(text2) : decodeHexadecimal(text2);
2823
1558
  break;
2824
1559
  }
2825
1560
  case "codestation_format_json": {
@@ -2841,9 +1576,9 @@ function createMcpServer(cliKey) {
2841
1576
  break;
2842
1577
  }
2843
1578
  case "codestation_case_convert": {
2844
- const text3 = String(args.text ?? "");
1579
+ const text2 = String(args.text ?? "");
2845
1580
  const targetCase = String(args.targetCase ?? "camel");
2846
- outputText = convertCase(text3, targetCase);
1581
+ outputText = convertCase(text2, targetCase);
2847
1582
  break;
2848
1583
  }
2849
1584
  case "codestation_text_diff": {
@@ -2856,25 +1591,25 @@ function createMcpServer(cliKey) {
2856
1591
  }
2857
1592
  // --- Pro tools ---
2858
1593
  case "codestation_hash": {
2859
- const text3 = String(args.text ?? "");
1594
+ const text2 = String(args.text ?? "");
2860
1595
  const algo = String(args.algorithm ?? "SHA-256").toUpperCase();
2861
- if (algo === "MD5") outputText = md5(text3);
2862
- else if (algo === "SHA-1") outputText = sha1(text3);
2863
- else if (algo === "SHA-256") outputText = await sha256(text3);
2864
- else if (algo === "SHA-384") outputText = await sha384(text3);
2865
- else if (algo === "SHA-512") outputText = await sha512(text3);
2866
- else if (algo === "CRC32") outputText = crc32(text3);
1596
+ if (algo === "MD5") outputText = md5(text2);
1597
+ else if (algo === "SHA-1") outputText = sha1(text2);
1598
+ else if (algo === "SHA-256") outputText = await sha256(text2);
1599
+ else if (algo === "SHA-384") outputText = await sha384(text2);
1600
+ else if (algo === "SHA-512") outputText = await sha512(text2);
1601
+ else if (algo === "CRC32") outputText = crc32(text2);
2867
1602
  else throw new Error(`Unsupported hash algorithm: ${algo}`);
2868
1603
  break;
2869
1604
  }
2870
1605
  case "codestation_hmac": {
2871
- const text3 = String(args.text ?? "");
1606
+ const text2 = String(args.text ?? "");
2872
1607
  const secret = String(args.secret ?? "");
2873
1608
  const algo = String(args.algorithm ?? "SHA-256").toUpperCase();
2874
1609
  if (algo === "SHA-512") {
2875
- outputText = await hmacSha512(text3, secret);
1610
+ outputText = await hmacSha512(text2, secret);
2876
1611
  } else {
2877
- outputText = await hmacSha256(text3, secret);
1612
+ outputText = await hmacSha256(text2, secret);
2878
1613
  }
2879
1614
  break;
2880
1615
  }
@@ -2884,9 +1619,19 @@ function createMcpServer(cliKey) {
2884
1619
  }
2885
1620
  case "codestation_format_sql": {
2886
1621
  const sql = String(args.sql ?? "");
2887
- const dialect = String(args.dialect ?? "PostgreSQL");
2888
- const res = await runSql("sql-formatter", { sql, dialect });
2889
- outputText = res.rows?.find((r) => r.label === "Formatted SQL")?.value ?? "";
1622
+ const dialect = String(args.dialect ?? "PostgreSQL").toLowerCase();
1623
+ const { format } = await import("sql-formatter");
1624
+ const dialectMap = {
1625
+ postgresql: "postgresql",
1626
+ postgres: "postgresql",
1627
+ mysql: "mysql",
1628
+ sqlite: "sqlite",
1629
+ sqlserver: "transactsql",
1630
+ tsql: "transactsql",
1631
+ "sql server": "transactsql"
1632
+ };
1633
+ const lang = dialectMap[dialect] || "sql";
1634
+ outputText = format(sql, { language: lang, tabWidth: 2 });
2890
1635
  break;
2891
1636
  }
2892
1637
  case "codestation_cron_explain": {
@@ -2910,17 +1655,29 @@ function createMcpServer(cliKey) {
2910
1655
  }
2911
1656
  case "codestation_regex_test": {
2912
1657
  const pattern = String(args.pattern ?? "");
2913
- const text3 = String(args.text ?? "");
1658
+ const text2 = String(args.text ?? "");
2914
1659
  const flags = String(args.flags ?? "g");
2915
- outputText = testRegex(pattern, flags, text3);
1660
+ outputText = testRegex(pattern, flags, text2);
2916
1661
  break;
2917
1662
  }
2918
1663
  case "codestation_json_schema": {
2919
1664
  outputText = generateJsonSchema(String(args.json ?? ""));
2920
1665
  break;
2921
1666
  }
1667
+ case "codestation_json_to_typescript": {
1668
+ const json = String(args.json ?? "");
1669
+ const rootName = args.rootName ? String(args.rootName) : "Root";
1670
+ outputText = jsonToTypescript(json, rootName);
1671
+ break;
1672
+ }
1673
+ case "codestation_json_to_zod": {
1674
+ const json = String(args.json ?? "");
1675
+ const rootName = args.rootName ? String(args.rootName) : "rootSchema";
1676
+ outputText = jsonToZod(json, rootName);
1677
+ break;
1678
+ }
2922
1679
  default:
2923
- throw new Error(`Unknown tool: ${name2}`);
1680
+ throw new Error(`Unknown tool: ${name}`);
2924
1681
  }
2925
1682
  return {
2926
1683
  content: [{ type: "text", text: outputText }]
@@ -2936,35 +1693,459 @@ function createMcpServer(cliKey) {
2936
1693
  return { server, license };
2937
1694
  }
2938
1695
 
1696
+ // mcp/setup.ts
1697
+ import * as fs2 from "node:fs";
1698
+ import * as path2 from "node:path";
1699
+ import * as os2 from "node:os";
1700
+ function getClaudeDesktopConfigPath() {
1701
+ const platform = process.platform;
1702
+ if (platform === "darwin") {
1703
+ return path2.join(os2.homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
1704
+ } else if (platform === "win32") {
1705
+ const appData = process.env.APPDATA || path2.join(os2.homedir(), "AppData", "Roaming");
1706
+ return path2.join(appData, "Claude", "claude_desktop_config.json");
1707
+ } else {
1708
+ return path2.join(os2.homedir(), ".config", "Claude", "claude_desktop_config.json");
1709
+ }
1710
+ }
1711
+ function getCursorGlobalConfigPath() {
1712
+ return path2.join(os2.homedir(), ".cursor", "mcp.json");
1713
+ }
1714
+ function getWindsurfConfigPath() {
1715
+ return path2.join(os2.homedir(), ".codeium", "windsurf", "mcp_config.json");
1716
+ }
1717
+ function mergeMcpConfig(filePath, mcpEntry) {
1718
+ try {
1719
+ const dir = path2.dirname(filePath);
1720
+ if (!fs2.existsSync(dir)) {
1721
+ fs2.mkdirSync(dir, { recursive: true });
1722
+ }
1723
+ let config = {};
1724
+ if (fs2.existsSync(filePath)) {
1725
+ try {
1726
+ const raw = fs2.readFileSync(filePath, "utf-8");
1727
+ config = JSON.parse(raw);
1728
+ } catch {
1729
+ config = {};
1730
+ }
1731
+ }
1732
+ if (!config.mcpServers || typeof config.mcpServers !== "object") {
1733
+ config.mcpServers = {};
1734
+ }
1735
+ config.mcpServers.codestation = mcpEntry;
1736
+ fs2.writeFileSync(filePath, JSON.stringify(config, null, 2) + "\n", "utf-8");
1737
+ return { target: path2.basename(filePath), path: filePath, status: "configured" };
1738
+ } catch (err) {
1739
+ return {
1740
+ target: path2.basename(filePath),
1741
+ path: filePath,
1742
+ status: "error",
1743
+ message: err instanceof Error ? err.message : String(err)
1744
+ };
1745
+ }
1746
+ }
1747
+ async function runAutoSetup(licenseKey) {
1748
+ const cleanKey = licenseKey?.trim();
1749
+ if (cleanKey && validateLicenseKey(cleanKey)) {
1750
+ saveCachedLicense(cleanKey, true);
1751
+ }
1752
+ const mcpEntry = {
1753
+ command: "npx",
1754
+ args: cleanKey ? ["-y", "codestation-mcp", "--key", cleanKey] : ["-y", "codestation-mcp"]
1755
+ };
1756
+ const targets = [
1757
+ { name: "Claude Desktop", path: getClaudeDesktopConfigPath() },
1758
+ { name: "Cursor IDE (Global)", path: getCursorGlobalConfigPath() },
1759
+ { name: "Windsurf / Codeium", path: getWindsurfConfigPath() }
1760
+ ];
1761
+ const localCursorPath = path2.join(process.cwd(), ".cursor", "mcp.json");
1762
+ if (fs2.existsSync(path2.join(process.cwd(), ".cursor"))) {
1763
+ targets.push({ name: "Cursor IDE (Local Project)", path: localCursorPath });
1764
+ }
1765
+ const results = [];
1766
+ for (const t of targets) {
1767
+ const res = mergeMcpConfig(t.path, mcpEntry);
1768
+ res.target = t.name;
1769
+ results.push(res);
1770
+ }
1771
+ return results;
1772
+ }
1773
+
1774
+ // mcp/cli-tools.ts
1775
+ import * as fs3 from "node:fs";
1776
+
1777
+ // lib/tools/cron/next-run.ts
1778
+ var DAY2 = 864e5;
1779
+ var SIX_HOURS = 6 * 36e5;
1780
+ var pad3 = (value, width = 2) => String(value).padStart(width, "0");
1781
+ function parseCronReference(reference) {
1782
+ if (reference.length > 64) throw new Error("Reference exceeds the 64-character limit.");
1783
+ const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})$/.exec(reference);
1784
+ if (!match) throw new Error("Reference must be an absolute ISO date/time: YYYY-MM-DDTHH:mm[:ss[.sss]] followed by Z or \xB1HH:mm.");
1785
+ const [year, month, day, hour, minute, second] = [match[1], match[2], match[3], match[4], match[5], match[6] ?? "0"].map(Number);
1786
+ if (year < 1970 || year > 2099) throw new Error("Reference years must be between 1970 and 2099.");
1787
+ const days = new Date(Date.UTC(year, month, 0)).getUTCDate();
1788
+ if (month < 1 || month > 12 || day < 1 || day > days || hour > 23 || minute > 59 || second > 59) throw new Error("Reference contains an impossible calendar date or time.");
1789
+ const milliseconds = Number((match[7] ?? "").padEnd(3, "0"));
1790
+ let offset = 0;
1791
+ if (match[8] !== "Z") {
1792
+ const offsetHour = Number(match[8].slice(1, 3));
1793
+ const offsetMinute = Number(match[8].slice(4, 6));
1794
+ if (offsetMinute > 59 || offsetHour > 14 || offsetHour === 14 && offsetMinute !== 0) throw new Error("Reference offset must be within \xB114:00, with valid minutes.");
1795
+ offset = (offsetHour * 60 + offsetMinute) * 6e4 * (match[8][0] === "-" ? -1 : 1);
1796
+ }
1797
+ const instant = Date.UTC(year, month - 1, day, hour, minute, second, milliseconds) - offset;
1798
+ const utcYear = new Date(instant).getUTCFullYear();
1799
+ if (utcYear < 1970 || utcYear > 2099) throw new Error("Reference instant must fall within UTC years 1970\u20132099.");
1800
+ return instant;
1801
+ }
1802
+ function zoneFormatter2(timezone) {
1803
+ if (!timezone || timezone !== timezone.trim()) throw new Error("Select a nonempty IANA timezone.");
1804
+ if (timezone.length > 128 || !/^[A-Za-z][A-Za-z0-9_+\-/]*$/.test(timezone)) throw new Error("Enter a valid IANA timezone name; numeric offsets are not timezone names.");
1805
+ try {
1806
+ return new Intl.DateTimeFormat("en-GB-u-ca-gregory-nu-latn", {
1807
+ timeZone: timezone,
1808
+ year: "numeric",
1809
+ month: "2-digit",
1810
+ day: "2-digit",
1811
+ hour: "2-digit",
1812
+ minute: "2-digit",
1813
+ second: "2-digit",
1814
+ hourCycle: "h23"
1815
+ });
1816
+ } catch {
1817
+ throw new Error("Timezone is not a recognized IANA timezone in this runtime.");
1818
+ }
1819
+ }
1820
+ function wallTime(formatter, instant) {
1821
+ const parts = formatter.formatToParts(instant);
1822
+ const get = (name) => Number(parts.find((part) => part.type === name)?.value);
1823
+ return { year: get("year"), month: get("month"), day: get("day"), hour: get("hour"), minute: get("minute"), second: get("second") };
1824
+ }
1825
+ function offsetAt(formatter, instant) {
1826
+ const wholeSecond = Math.floor(instant / 1e3) * 1e3;
1827
+ const wall = wallTime(formatter, wholeSecond);
1828
+ return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - wholeSecond;
1829
+ }
1830
+ function offsetIntervals(formatter, midnight) {
1831
+ const start = midnight - 2 * DAY2;
1832
+ const end = midnight + 3 * DAY2;
1833
+ const intervals = [];
1834
+ let intervalStart = start;
1835
+ let priorOffset = offsetAt(formatter, start);
1836
+ for (let probe = start + SIX_HOURS; probe <= end; probe += SIX_HOURS) {
1837
+ const nextOffset = offsetAt(formatter, probe);
1838
+ if (nextOffset !== priorOffset) {
1839
+ let low = probe - SIX_HOURS;
1840
+ let high = probe;
1841
+ while (high - low > 1e3) {
1842
+ const middle = Math.floor((low + high) / 2e3) * 1e3;
1843
+ if (offsetAt(formatter, middle) === priorOffset) low = middle;
1844
+ else high = middle;
1845
+ }
1846
+ intervals.push({ start: intervalStart, end: high, offset: priorOffset });
1847
+ intervalStart = high;
1848
+ priorOffset = nextOffset;
1849
+ }
1850
+ }
1851
+ intervals.push({ start: intervalStart, end, offset: priorOffset });
1852
+ return intervals;
1853
+ }
1854
+ function selectedSecond(cron, lower, upper) {
1855
+ if (lower >= upper || lower >= 86400) return void 0;
1856
+ lower = Math.max(0, Math.ceil(lower));
1857
+ const firstHour = Math.floor(lower / 3600);
1858
+ for (const hour of cron.hour.values) {
1859
+ if (hour < firstHour) continue;
1860
+ const firstMinute = hour === firstHour ? Math.floor(lower % 3600 / 60) : 0;
1861
+ for (const minute of cron.minute.values) {
1862
+ if (minute < firstMinute) continue;
1863
+ const base = hour * 3600 + minute * 60;
1864
+ if (base >= upper) return void 0;
1865
+ const second = cron.second.values.find((value) => base + value >= lower);
1866
+ if (second !== void 0) return base + second < upper ? base + second : void 0;
1867
+ }
1868
+ }
1869
+ return void 0;
1870
+ }
1871
+ function formatCronDuration(milliseconds) {
1872
+ if (!Number.isSafeInteger(milliseconds)) throw new Error("Duration is outside supported integer precision.");
1873
+ const sign = milliseconds < 0 ? "-" : "+";
1874
+ let remainder = Math.abs(milliseconds);
1875
+ const pieces = [];
1876
+ for (const [size, name] of [[DAY2, "day"], [36e5, "hour"], [6e4, "minute"], [1e3, "second"], [1, "millisecond"]]) {
1877
+ const count = Math.floor(remainder / size);
1878
+ remainder %= size;
1879
+ if (count) pieces.push(`${count} ${name}${count === 1 ? "" : "s"}`);
1880
+ }
1881
+ return sign + (pieces.join(", ") || "0 seconds");
1882
+ }
1883
+ function nextCronRun(expression, reference, timezone) {
1884
+ const cron = typeof expression === "string" ? parseCron(expression) : expression;
1885
+ const instant = parseCronReference(reference);
1886
+ const formatter = zoneFormatter2(timezone);
1887
+ const referenceWall = wallTime(formatter, instant);
1888
+ if (referenceWall.year < 1970 || referenceWall.year > 2099) throw new Error("Reference in the selected timezone must fall within years 1970\u20132099.");
1889
+ const referenceDay = Date.UTC(referenceWall.year, referenceWall.month - 1, referenceWall.day);
1890
+ const firstDay = Math.max(Date.UTC(1970, 0, 1), referenceDay - 2 * DAY2);
1891
+ const searchEnd = Math.min(Date.UTC(2100, 0, 1), Date.UTC(referenceWall.year + 8, referenceWall.month - 1, referenceWall.day + 1));
1892
+ const utcReference = new Date(instant);
1893
+ const eightYearLimit = Date.UTC(utcReference.getUTCFullYear() + 8, utcReference.getUTCMonth(), utcReference.getUTCDate(), utcReference.getUTCHours(), utcReference.getUTCMinutes(), utcReference.getUTCSeconds(), utcReference.getUTCMilliseconds());
1894
+ const absoluteEnd = Math.min(Date.UTC(2100, 0, 1), eightYearLimit + 1);
1895
+ let best;
1896
+ let bestOffset = 0;
1897
+ for (let midnight = firstDay; midnight < searchEnd; midnight += DAY2) {
1898
+ if (best !== void 0 && midnight - DAY2 > best) break;
1899
+ const date = new Date(midnight);
1900
+ const year = date.getUTCFullYear();
1901
+ const month = date.getUTCMonth() + 1;
1902
+ const day = date.getUTCDate();
1903
+ if (!matchesCronDate(cron, year, month, day)) continue;
1904
+ for (const interval of offsetIntervals(formatter, midnight)) {
1905
+ const lowerUtc = Math.max(interval.start, instant + 1, midnight - interval.offset, Date.UTC(1970, 0, 1));
1906
+ const upperUtc = Math.min(interval.end, midnight + DAY2 - interval.offset, absoluteEnd, best ?? Infinity);
1907
+ const second = selectedSecond(cron, (lowerUtc + interval.offset - midnight) / 1e3, (upperUtc + interval.offset - midnight) / 1e3);
1908
+ if (second === void 0) continue;
1909
+ const candidate = midnight + second * 1e3 - interval.offset;
1910
+ const actual = wallTime(formatter, candidate);
1911
+ if (actual.year !== year || actual.month !== month || actual.day !== day || actual.hour !== Math.floor(second / 3600) || actual.minute !== Math.floor(second % 3600 / 60) || actual.second !== second % 60) continue;
1912
+ if (candidate > instant && (best === void 0 || candidate < best)) {
1913
+ best = candidate;
1914
+ bestOffset = interval.offset;
1915
+ }
1916
+ }
1917
+ }
1918
+ if (best === void 0) throw new Error("No occurrence found within eight calendar years after the reference, ending no later than 2099. The expression may select impossible calendar dates.");
1919
+ if (bestOffset % 6e4 !== 0) throw new Error("This historical timezone offset includes seconds and cannot be represented by an RFC 3339 \xB1HH:mm offset; choose a reference after the zone adopted minute-based offsets.");
1920
+ const wall = wallTime(formatter, best);
1921
+ const offsetMinutes = Math.abs(bestOffset / 6e4);
1922
+ const offset = `${bestOffset < 0 ? "-" : "+"}${pad3(Math.floor(offsetMinutes / 60))}:${pad3(offsetMinutes % 60)}`;
1923
+ const dateTime = `${pad3(wall.year, 4)}-${pad3(wall.month)}-${pad3(wall.day)}T${pad3(wall.hour)}:${pad3(wall.minute)}:${pad3(wall.second)}${offset}[${timezone}]`;
1924
+ const durationMilliseconds = best - instant;
1925
+ return { instant: best, dateTime, timezone, durationMilliseconds, duration: formatCronDuration(durationMilliseconds) };
1926
+ }
1927
+
1928
+ // mcp/cli-tools.ts
1929
+ async function readInput(arg) {
1930
+ if (arg && arg !== "-") {
1931
+ if (fs3.existsSync(arg)) {
1932
+ return fs3.readFileSync(arg, "utf-8");
1933
+ }
1934
+ return arg;
1935
+ }
1936
+ if (!process.stdin.isTTY) {
1937
+ return new Promise((resolve, reject) => {
1938
+ let data = "";
1939
+ process.stdin.setEncoding("utf-8");
1940
+ process.stdin.on("data", (chunk) => {
1941
+ data += chunk;
1942
+ });
1943
+ process.stdin.on("end", () => resolve(data.trim()));
1944
+ process.stdin.on("error", reject);
1945
+ });
1946
+ }
1947
+ return "";
1948
+ }
1949
+ async function handleCliSubcommand(command, args) {
1950
+ switch (command.toLowerCase()) {
1951
+ case "jwt": {
1952
+ const input = await readInput(args[0]);
1953
+ if (!input) {
1954
+ process.stderr.write("Usage: npx codestation-mcp jwt <jwt_token>\n");
1955
+ return true;
1956
+ }
1957
+ try {
1958
+ const decoded = JSON.parse(decodeJwt(input));
1959
+ process.stdout.write("\n=== JWT HEADER ===\n");
1960
+ process.stdout.write(JSON.stringify(decoded.header, null, 2) + "\n");
1961
+ process.stdout.write("\n=== JWT PAYLOAD ===\n");
1962
+ process.stdout.write(JSON.stringify(decoded.payload, null, 2) + "\n");
1963
+ if (decoded.payload.exp) {
1964
+ const expDate = new Date(decoded.payload.exp * 1e3);
1965
+ const isExpired = Date.now() > expDate.getTime();
1966
+ process.stdout.write(
1967
+ `
1968
+ Expiry: ${expDate.toISOString()} (${isExpired ? "EXPIRED" : "Valid until " + expDate.toLocaleString()})
1969
+
1970
+ `
1971
+ );
1972
+ }
1973
+ } catch (err) {
1974
+ process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
1975
+ `);
1976
+ }
1977
+ return true;
1978
+ }
1979
+ case "sql": {
1980
+ const input = await readInput(args[0]);
1981
+ if (!input) {
1982
+ process.stderr.write('Usage: npx codestation-mcp sql "<query>" [--dialect postgresql|mysql|sqlite|sqlserver]\n');
1983
+ return true;
1984
+ }
1985
+ let dialect = "postgresql";
1986
+ const dialectIdx = args.indexOf("--dialect");
1987
+ if (dialectIdx !== -1 && args[dialectIdx + 1]) {
1988
+ dialect = args[dialectIdx + 1].toLowerCase();
1989
+ }
1990
+ const dialectMap = {
1991
+ postgresql: "postgresql",
1992
+ postgres: "postgresql",
1993
+ mysql: "mysql",
1994
+ sqlite: "sqlite",
1995
+ sqlserver: "transactsql",
1996
+ tsql: "transactsql",
1997
+ "sql server": "transactsql"
1998
+ };
1999
+ const lang = dialectMap[dialect] || "sql";
2000
+ try {
2001
+ const { format } = await import("sql-formatter");
2002
+ const formatted = format(input, { language: lang, tabWidth: 2 });
2003
+ process.stdout.write(formatted + "\n");
2004
+ } catch (err) {
2005
+ process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
2006
+ `);
2007
+ }
2008
+ return true;
2009
+ }
2010
+ case "cron": {
2011
+ const input = args.join(" ").replace(/--key\s+[^\s]+/g, "").trim();
2012
+ if (!input) {
2013
+ process.stderr.write('Usage: npx codestation-mcp cron "<cron_expression>"\nExample: npx codestation-mcp cron "0 9 * * 1-5"\n');
2014
+ return true;
2015
+ }
2016
+ try {
2017
+ const parsed = parseCron(input);
2018
+ const explanation = explainCron(parsed);
2019
+ const next = nextCronRun(parsed, (/* @__PURE__ */ new Date()).toISOString(), "UTC");
2020
+ process.stdout.write(`
2021
+ Expression: ${input}
2022
+ `);
2023
+ process.stdout.write(`Description: ${explanation}
2024
+ `);
2025
+ process.stdout.write(`Next run: ${next.dateTime} (${next.duration})
2026
+
2027
+ `);
2028
+ } catch (err) {
2029
+ process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
2030
+ `);
2031
+ }
2032
+ return true;
2033
+ }
2034
+ case "hash": {
2035
+ const input = await readInput(args[0]);
2036
+ if (!input) {
2037
+ process.stderr.write('Usage: npx codestation-mcp hash "<string>" [--alg sha256|sha512|md5|sha1|crc32]\n');
2038
+ return true;
2039
+ }
2040
+ let alg = "sha256";
2041
+ const algIdx = args.indexOf("--alg");
2042
+ if (algIdx !== -1 && args[algIdx + 1]) {
2043
+ alg = args[algIdx + 1].toLowerCase();
2044
+ }
2045
+ let result = "";
2046
+ if (alg === "sha256") result = await sha256(input);
2047
+ else if (alg === "sha512") result = await sha512(input);
2048
+ else if (alg === "md5") result = md5(input);
2049
+ else if (alg === "sha1") result = sha1(input);
2050
+ else if (alg === "crc32") result = crc32(input);
2051
+ else result = await sha256(input);
2052
+ process.stdout.write(`${alg.toUpperCase()}: ${result}
2053
+ `);
2054
+ return true;
2055
+ }
2056
+ case "ts":
2057
+ case "types": {
2058
+ const input = await readInput(args[0]);
2059
+ if (!input) {
2060
+ process.stderr.write('Usage: npx codestation-mcp ts "<json_string_or_file>" [RootName]\n');
2061
+ return true;
2062
+ }
2063
+ const rootName = args[1] || "Root";
2064
+ try {
2065
+ const tsOutput = jsonToTypescript(input, rootName);
2066
+ process.stdout.write(tsOutput + "\n");
2067
+ } catch (err) {
2068
+ process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
2069
+ `);
2070
+ }
2071
+ return true;
2072
+ }
2073
+ case "zod": {
2074
+ const input = await readInput(args[0]);
2075
+ if (!input) {
2076
+ process.stderr.write('Usage: npx codestation-mcp zod "<json_string_or_file>" [rootSchema]\n');
2077
+ return true;
2078
+ }
2079
+ const rootName = args[1] || "rootSchema";
2080
+ try {
2081
+ const zodOutput = jsonToZod(input, rootName);
2082
+ process.stdout.write(zodOutput + "\n");
2083
+ } catch (err) {
2084
+ process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
2085
+ `);
2086
+ }
2087
+ return true;
2088
+ }
2089
+ case "uuid": {
2090
+ const count = parseInt(args[0], 10) || 1;
2091
+ for (let i = 0; i < count; i++) {
2092
+ process.stdout.write(crypto.randomUUID() + "\n");
2093
+ }
2094
+ return true;
2095
+ }
2096
+ case "json": {
2097
+ const input = await readInput(args[0]);
2098
+ if (!input) {
2099
+ process.stderr.write('Usage: npx codestation-mcp json "<raw_json>"\n');
2100
+ return true;
2101
+ }
2102
+ try {
2103
+ const formatted = formatJson(input, 2);
2104
+ process.stdout.write(formatted + "\n");
2105
+ } catch (err) {
2106
+ process.stderr.write(`[Error] ${err instanceof Error ? err.message : String(err)}
2107
+ `);
2108
+ }
2109
+ return true;
2110
+ }
2111
+ default:
2112
+ return false;
2113
+ }
2114
+ }
2115
+
2939
2116
  // mcp/cli.ts
2940
2117
  function printHelp() {
2941
2118
  process.stderr.write(`
2942
- Code Station MCP Server
2943
- Local-first developer toolbox for AI assistants (Cursor, Claude Desktop, Antigravity)
2119
+ Code Station MCP Server & Developer CLI
2120
+ Local-first developer toolbox for AI assistants (Cursor, Claude Desktop, Windsurf) and terminal workflows.
2944
2121
 
2945
2122
  Usage:
2946
- npx codestation-mcp [options]
2123
+ npx codestation-mcp [command|options]
2947
2124
 
2948
- Options:
2949
- --key <license_key> Activate Code Station Pro features
2950
- --help, -h Show this help message
2951
- --version, -v Show version information
2125
+ 1-Click AI Assistant Setup:
2126
+ npx codestation-mcp setup [--key <license_key>]
2127
+ Automatically configures Claude Desktop, Cursor IDE, and Windsurf.
2952
2128
 
2953
- Pricing:
2954
- \u2022 Free Tier: Unlimited Base64, JSON, YAML, UUID, Text Diff, Case conversion
2955
- \u2022 Pro Tier (India): ${PRICING.inr} (or ${PRICING.lifetimeInr})
2956
- \u2022 Pro Tier (Global): ${PRICING.usd} (or ${PRICING.lifetimeUsd})
2957
- \u2022 Upgrade / Account: ${PRICING.upgradeUrl}
2129
+ Terminal Subcommands:
2130
+ jwt <token> Decode & inspect JWT header, payload, and expiry
2131
+ sql "<query>" [--dialect] Format SQL query (postgresql, mysql, sqlite, sqlserver)
2132
+ cron "<expression>" Explain cron schedule & project next 5 runtimes
2133
+ hash "<text>" [--alg] Compute digest (sha256, sha512, md5, sha1, crc32)
2134
+ ts "<json_string|file>" Generate clean TypeScript interfaces from JSON
2135
+ zod "<json_string|file>" Generate production-ready Zod schema from JSON
2136
+ uuid [count] Generate random RFC 4122 v4 UUIDs
2137
+ json "<raw_json>" Validate & pretty-print JSON
2958
2138
 
2959
- Configuration for Claude Desktop (claude_desktop_config.json):
2960
- {
2961
- "mcpServers": {
2962
- "codestation": {
2963
- "command": "npx",
2964
- "args": ["-y", "codestation-mcp", "--key", "YOUR_PRO_KEY"]
2965
- }
2966
- }
2967
- }
2139
+ Stdio Server Options (for AI Assistants):
2140
+ --key <license_key> Activate Code Station Pro features
2141
+ --help, -h Show this help message
2142
+ --version, -v Show version information
2143
+
2144
+ Pricing:
2145
+ \u2022 Free Tier: Unlimited Base64, JSON, YAML, UUID, Text Diff, Case conversion
2146
+ \u2022 Pro Tier (India): ${PRICING.inr} (or ${PRICING.lifetimeInr})
2147
+ \u2022 Pro Tier (Global): ${PRICING.usd} (or ${PRICING.lifetimeUsd})
2148
+ \u2022 Upgrade / Account: ${PRICING.upgradeUrl}
2968
2149
 
2969
2150
  `);
2970
2151
  }
@@ -2975,9 +2156,41 @@ async function main() {
2975
2156
  process.exit(0);
2976
2157
  }
2977
2158
  if (args.includes("--version") || args.includes("-v")) {
2978
- process.stderr.write("codestation-mcp v1.0.0\n");
2159
+ process.stderr.write("codestation-mcp v1.1.0\n");
2160
+ process.exit(0);
2161
+ }
2162
+ if (args[0] === "setup") {
2163
+ let key;
2164
+ const keyIdx = args.indexOf("--key");
2165
+ if (keyIdx !== -1 && args[keyIdx + 1]) {
2166
+ key = args[keyIdx + 1];
2167
+ }
2168
+ process.stdout.write("\n=== Code Station 1-Click AI Setup ===\n");
2169
+ if (key) {
2170
+ process.stdout.write(`Activating with Pro Key: ${key.slice(0, 8)}...
2171
+ `);
2172
+ } else {
2173
+ process.stdout.write("Configuring in Free Tier mode (run with --key anytime to activate Pro).\n");
2174
+ }
2175
+ const results = await runAutoSetup(key);
2176
+ for (const r of results) {
2177
+ if (r.status === "configured") {
2178
+ process.stdout.write(` \u2714 ${r.target.padEnd(26)} Configured (${r.path})
2179
+ `);
2180
+ } else {
2181
+ process.stdout.write(` \u2716 ${r.target.padEnd(26)} Error: ${r.message}
2182
+ `);
2183
+ }
2184
+ }
2185
+ process.stdout.write("\n\u2728 Setup complete! Restart your editor(s) to start using Code Station tools.\n\n");
2979
2186
  process.exit(0);
2980
2187
  }
2188
+ if (args.length > 0 && !args[0].startsWith("-")) {
2189
+ const handled = await handleCliSubcommand(args[0], args.slice(1));
2190
+ if (handled) {
2191
+ process.exit(0);
2192
+ }
2193
+ }
2981
2194
  let cliKey;
2982
2195
  const keyIndex = args.indexOf("--key");
2983
2196
  if (keyIndex !== -1 && args[keyIndex + 1]) {