codestation-mcp 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +100 -2
- package/bin/codestation-mcp.mjs +3004 -0
- package/package.json +37 -4
|
@@ -0,0 +1,3004 @@
|
|
|
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
|
+
|
|
900
|
+
// mcp/cli.ts
|
|
901
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
902
|
+
|
|
903
|
+
// mcp/server.ts
|
|
904
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
905
|
+
import {
|
|
906
|
+
CallToolRequestSchema,
|
|
907
|
+
ListToolsRequestSchema
|
|
908
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
909
|
+
|
|
910
|
+
// mcp/config.ts
|
|
911
|
+
import * as fs from "node:fs";
|
|
912
|
+
import * as path from "node:path";
|
|
913
|
+
import * as os from "node:os";
|
|
914
|
+
var PRICING = {
|
|
915
|
+
inr: "\u20B9199 / month",
|
|
916
|
+
usd: "$2.99 / month",
|
|
917
|
+
lifetimeInr: "\u20B9999 one-time",
|
|
918
|
+
lifetimeUsd: "$19.00 one-time",
|
|
919
|
+
upgradeUrl: "https://codestation.in/pro"
|
|
920
|
+
};
|
|
921
|
+
var PRO_TOOLS = /* @__PURE__ */ new Set([
|
|
922
|
+
"codestation_hash",
|
|
923
|
+
"codestation_hmac",
|
|
924
|
+
"codestation_jwt_decode",
|
|
925
|
+
"codestation_format_sql",
|
|
926
|
+
"codestation_cron_explain",
|
|
927
|
+
"codestation_timezone_convert",
|
|
928
|
+
"codestation_business_days",
|
|
929
|
+
"codestation_regex_test",
|
|
930
|
+
"codestation_json_schema"
|
|
931
|
+
]);
|
|
932
|
+
var CACHE_DIR = path.join(os.homedir(), ".codestation");
|
|
933
|
+
var CACHE_FILE = path.join(CACHE_DIR, "license.json");
|
|
934
|
+
function readCachedLicense() {
|
|
935
|
+
try {
|
|
936
|
+
if (fs.existsSync(CACHE_FILE)) {
|
|
937
|
+
const data = JSON.parse(fs.readFileSync(CACHE_FILE, "utf-8"));
|
|
938
|
+
if (Date.now() - data.verifiedAt < 30 * 24 * 60 * 60 * 1e3) {
|
|
939
|
+
return data;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
} catch {
|
|
943
|
+
}
|
|
944
|
+
return null;
|
|
945
|
+
}
|
|
946
|
+
function saveCachedLicense(key2, isPro) {
|
|
947
|
+
try {
|
|
948
|
+
if (process.env.NODE_ENV === "test") return;
|
|
949
|
+
if (!fs.existsSync(CACHE_DIR)) {
|
|
950
|
+
fs.mkdirSync(CACHE_DIR, { recursive: true });
|
|
951
|
+
}
|
|
952
|
+
const cache = {
|
|
953
|
+
key: key2,
|
|
954
|
+
verifiedAt: Date.now(),
|
|
955
|
+
isPro
|
|
956
|
+
};
|
|
957
|
+
fs.writeFileSync(CACHE_FILE, JSON.stringify(cache, null, 2), "utf-8");
|
|
958
|
+
} catch {
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
function validateLicenseKey(rawKey) {
|
|
962
|
+
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_")) {
|
|
966
|
+
return true;
|
|
967
|
+
}
|
|
968
|
+
if (key2 === "PRO_DEMO_KEY" || key2 === "CS-PRO-DEV") {
|
|
969
|
+
return true;
|
|
970
|
+
}
|
|
971
|
+
return false;
|
|
972
|
+
}
|
|
973
|
+
function resolveLicense(cliKey) {
|
|
974
|
+
if (cliKey) {
|
|
975
|
+
const valid = validateLicenseKey(cliKey);
|
|
976
|
+
if (valid) {
|
|
977
|
+
saveCachedLicense(cliKey, true);
|
|
978
|
+
return { isPro: true, licenseKey: cliKey, source: "cli", tier: "pro" };
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
const envKey = process.env.CODESTATION_LICENSE_KEY;
|
|
982
|
+
if (envKey) {
|
|
983
|
+
const valid = validateLicenseKey(envKey);
|
|
984
|
+
if (valid) {
|
|
985
|
+
saveCachedLicense(envKey, true);
|
|
986
|
+
return { isPro: true, licenseKey: envKey, source: "env", tier: "pro" };
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
const cached = readCachedLicense();
|
|
990
|
+
if (cached && cached.isPro) {
|
|
991
|
+
return { isPro: true, licenseKey: cached.key, source: "cache", tier: "pro" };
|
|
992
|
+
}
|
|
993
|
+
return { isPro: false, source: "none", tier: "free" };
|
|
994
|
+
}
|
|
995
|
+
function getProUpgradeNotice(toolName) {
|
|
996
|
+
return [
|
|
997
|
+
`\u{1F512} Tool "${toolName}" is a Code Station Pro feature.`,
|
|
998
|
+
``,
|
|
999
|
+
`Get Code Station Pro:`,
|
|
1000
|
+
` \u2022 India: ${PRICING.inr} (or ${PRICING.lifetimeInr})`,
|
|
1001
|
+
` \u2022 Global: ${PRICING.usd} (or ${PRICING.lifetimeUsd})`,
|
|
1002
|
+
` \u2022 Upgrade URL: ${PRICING.upgradeUrl}`,
|
|
1003
|
+
``,
|
|
1004
|
+
`To activate, launch with:`,
|
|
1005
|
+
` npx codestation-mcp --key CS-PRO-YOURKEY`,
|
|
1006
|
+
`or set environment variable:`,
|
|
1007
|
+
` export CODESTATION_LICENSE_KEY=CS-PRO-YOURKEY`
|
|
1008
|
+
].join("\n");
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
// lib/tools/index.ts
|
|
1012
|
+
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
|
|
1013
|
+
|
|
1014
|
+
// lib/tools/encoding-station.ts
|
|
1015
|
+
function utf8(value) {
|
|
1016
|
+
return new TextEncoder().encode(value);
|
|
1017
|
+
}
|
|
1018
|
+
function text(bytes2) {
|
|
1019
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes2);
|
|
1020
|
+
}
|
|
1021
|
+
function encodeBase64Url(value) {
|
|
1022
|
+
const bytes2 = utf8(value);
|
|
1023
|
+
let binary = "";
|
|
1024
|
+
for (const byte of bytes2) binary += String.fromCharCode(byte);
|
|
1025
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
1026
|
+
}
|
|
1027
|
+
function decodeBase64Url(value) {
|
|
1028
|
+
if (!/^[A-Za-z0-9_-]*$/.test(value)) throw new Error("Invalid Base64URL input.");
|
|
1029
|
+
const padded = value.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - value.length % 4) % 4);
|
|
1030
|
+
try {
|
|
1031
|
+
const binary = atob(padded);
|
|
1032
|
+
return text(Uint8Array.from(binary, (character) => character.charCodeAt(0)));
|
|
1033
|
+
} catch {
|
|
1034
|
+
throw new Error("Base64URL input is not valid Base64 or UTF-8 text.");
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
var encodeUrlComponent = encodeURIComponent;
|
|
1038
|
+
function decodeUrlComponent(value) {
|
|
1039
|
+
try {
|
|
1040
|
+
return decodeURIComponent(value);
|
|
1041
|
+
} catch {
|
|
1042
|
+
throw new Error("URL component contains invalid percent escapes.");
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
function encodeHexadecimal(value) {
|
|
1046
|
+
return Array.from(utf8(value), (byte) => byte.toString(16).padStart(2, "0")).join(" ");
|
|
1047
|
+
}
|
|
1048
|
+
function decodeHexadecimal(value) {
|
|
1049
|
+
const clean = value.replace(/[\s:-]/g, "");
|
|
1050
|
+
if (!/^(?:[\da-f]{2})+$/i.test(clean)) throw new Error("Use hexadecimal byte pairs such as 48 65 6c 6c 6f.");
|
|
1051
|
+
try {
|
|
1052
|
+
return text(Uint8Array.from(clean.match(/../g), (byte) => parseInt(byte, 16)));
|
|
1053
|
+
} catch {
|
|
1054
|
+
throw new Error("Hexadecimal input is not valid UTF-8 text.");
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
// lib/tools/index.ts
|
|
1059
|
+
function formatJson(value, indent = 2) {
|
|
1060
|
+
if (!Number.isInteger(indent) || indent < 0 || indent > 10) {
|
|
1061
|
+
throw new RangeError("indent must be an integer between 0 and 10");
|
|
1062
|
+
}
|
|
1063
|
+
return JSON.stringify(JSON.parse(value), null, indent);
|
|
1064
|
+
}
|
|
1065
|
+
function minifyJson(value) {
|
|
1066
|
+
return JSON.stringify(JSON.parse(value));
|
|
1067
|
+
}
|
|
1068
|
+
function jsonToYaml(value) {
|
|
1069
|
+
return stringifyYaml(JSON.parse(value));
|
|
1070
|
+
}
|
|
1071
|
+
function yamlToJson(value) {
|
|
1072
|
+
return JSON.stringify(parseYaml(value), null, 2);
|
|
1073
|
+
}
|
|
1074
|
+
function generateJsonSchema(value) {
|
|
1075
|
+
const sample = JSON.parse(value);
|
|
1076
|
+
const infer = (node) => {
|
|
1077
|
+
if (node === null) return { type: "null" };
|
|
1078
|
+
if (Array.isArray(node)) return { type: "array", items: node.length ? infer(node[0]) : {} };
|
|
1079
|
+
if (typeof node === "object") {
|
|
1080
|
+
const properties = Object.fromEntries(Object.entries(node).map(([key2, child]) => [key2, infer(child)]));
|
|
1081
|
+
return { type: "object", properties, required: Object.keys(properties), additionalProperties: false };
|
|
1082
|
+
}
|
|
1083
|
+
return { type: typeof node === "number" && Number.isInteger(node) ? "integer" : typeof node };
|
|
1084
|
+
};
|
|
1085
|
+
return JSON.stringify({ $schema: "https://json-schema.org/draft/2020-12/schema", ...infer(sample) }, null, 2);
|
|
1086
|
+
}
|
|
1087
|
+
function decodeBase64Url2(value) {
|
|
1088
|
+
return decodeBase64(value.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - value.length % 4) % 4));
|
|
1089
|
+
}
|
|
1090
|
+
function decodeJwt(value) {
|
|
1091
|
+
const parts = value.trim().split(".");
|
|
1092
|
+
if (parts.length !== 3) throw new Error("A JWT must contain three dot-separated sections.");
|
|
1093
|
+
try {
|
|
1094
|
+
return JSON.stringify({ header: JSON.parse(decodeBase64Url2(parts[0])), payload: JSON.parse(decodeBase64Url2(parts[1])), signature: parts[2], note: "Decoded for inspection only. Signature validity was not verified." }, null, 2);
|
|
1095
|
+
} catch {
|
|
1096
|
+
throw new Error("JWT header and payload must contain valid Base64URL-encoded JSON.");
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
function testRegex(pattern, flags, text3) {
|
|
1100
|
+
let regex;
|
|
1101
|
+
try {
|
|
1102
|
+
regex = new RegExp(pattern, flags);
|
|
1103
|
+
} catch (cause) {
|
|
1104
|
+
throw new Error(cause instanceof Error ? cause.message : "Invalid regular expression.");
|
|
1105
|
+
}
|
|
1106
|
+
const matches = [];
|
|
1107
|
+
if (!regex.global) {
|
|
1108
|
+
const match = regex.exec(text3);
|
|
1109
|
+
if (match) matches.push({ match: match[0], index: match.index, groups: match.groups ?? {}, captures: match.slice(1) });
|
|
1110
|
+
} else {
|
|
1111
|
+
let match;
|
|
1112
|
+
while ((match = regex.exec(text3)) !== null) {
|
|
1113
|
+
matches.push({ match: match[0], index: match.index, groups: match.groups ?? {}, captures: match.slice(1) });
|
|
1114
|
+
if (match[0] === "") regex.lastIndex += 1;
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
return JSON.stringify({ count: matches.length, matches }, null, 2);
|
|
1118
|
+
}
|
|
1119
|
+
function utf8Decode(bytes2) {
|
|
1120
|
+
let result2 = "";
|
|
1121
|
+
for (let i = 0; i < bytes2.length; ) {
|
|
1122
|
+
const first = bytes2[i++];
|
|
1123
|
+
let code;
|
|
1124
|
+
if (first < 128) code = first;
|
|
1125
|
+
else if (first >= 194 && first <= 223 && i < bytes2.length) code = (first & 31) << 6 | bytes2[i++] & 63;
|
|
1126
|
+
else if (first >= 224 && first <= 239 && i + 1 < bytes2.length) code = (first & 15) << 12 | (bytes2[i++] & 63) << 6 | bytes2[i++] & 63;
|
|
1127
|
+
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
|
+
else throw new Error("Invalid UTF-8 data");
|
|
1129
|
+
if (code <= 65535) result2 += String.fromCharCode(code);
|
|
1130
|
+
else {
|
|
1131
|
+
const n = code - 65536;
|
|
1132
|
+
result2 += String.fromCharCode(55296 | n >> 10, 56320 | n & 1023);
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
return result2;
|
|
1136
|
+
}
|
|
1137
|
+
var BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
1138
|
+
function decodeBase64(value) {
|
|
1139
|
+
if (value.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) throw new Error("Invalid Base64 string");
|
|
1140
|
+
const bytes2 = [];
|
|
1141
|
+
for (let i = 0; i < value.length; i += 4) {
|
|
1142
|
+
const a = BASE64.indexOf(value[i]);
|
|
1143
|
+
const b = BASE64.indexOf(value[i + 1]);
|
|
1144
|
+
const c = value[i + 2] === "=" ? 0 : BASE64.indexOf(value[i + 2]);
|
|
1145
|
+
const d = value[i + 3] === "=" ? 0 : BASE64.indexOf(value[i + 3]);
|
|
1146
|
+
bytes2.push(a << 2 | b >> 4);
|
|
1147
|
+
if (value[i + 2] !== "=") bytes2.push((b & 15) << 4 | c >> 2);
|
|
1148
|
+
if (value[i + 3] !== "=") bytes2.push((c & 3) << 6 | d);
|
|
1149
|
+
}
|
|
1150
|
+
return utf8Decode(bytes2);
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
// lib/tools/security-station.ts
|
|
1154
|
+
var encoder = () => new TextEncoder();
|
|
1155
|
+
function bytes(input) {
|
|
1156
|
+
return typeof input === "string" ? encoder().encode(input) : input instanceof Uint8Array ? input : new Uint8Array(input);
|
|
1157
|
+
}
|
|
1158
|
+
function webBytes(input) {
|
|
1159
|
+
return bytes(input).slice().buffer;
|
|
1160
|
+
}
|
|
1161
|
+
function hex(input) {
|
|
1162
|
+
return Array.from(input, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1163
|
+
}
|
|
1164
|
+
function requireCrypto() {
|
|
1165
|
+
if (!globalThis.crypto?.subtle) throw new Error("Web Crypto is unavailable in this environment.");
|
|
1166
|
+
return globalThis.crypto;
|
|
1167
|
+
}
|
|
1168
|
+
function words(input) {
|
|
1169
|
+
const length = input.length + 9 + 63 >> 6 << 4;
|
|
1170
|
+
const out = new Array(length).fill(0);
|
|
1171
|
+
input.forEach((byte, index) => {
|
|
1172
|
+
out[index >> 2] |= byte << (index & 3) * 8;
|
|
1173
|
+
});
|
|
1174
|
+
out[input.length >> 2] |= 128 << (input.length & 3) * 8;
|
|
1175
|
+
const bitLength = input.length * 8;
|
|
1176
|
+
out[length - 2] = bitLength & 4294967295;
|
|
1177
|
+
out[length - 1] = Math.floor(bitLength / 4294967296);
|
|
1178
|
+
return out;
|
|
1179
|
+
}
|
|
1180
|
+
function rotl(value, count) {
|
|
1181
|
+
return value << count | value >>> 32 - count;
|
|
1182
|
+
}
|
|
1183
|
+
function littleHex(value) {
|
|
1184
|
+
return [0, 8, 16, 24].map((shift) => (value >>> shift & 255).toString(16).padStart(2, "0")).join("");
|
|
1185
|
+
}
|
|
1186
|
+
function md5(input) {
|
|
1187
|
+
const k = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296));
|
|
1188
|
+
const s = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21];
|
|
1189
|
+
let a = 1732584193, b = 4023233417, c = 2562383102, d = 271733878;
|
|
1190
|
+
const m = words(bytes(input));
|
|
1191
|
+
for (let offset = 0; offset < m.length; offset += 16) {
|
|
1192
|
+
let aa = a, bb = b, cc = c, dd = d;
|
|
1193
|
+
for (let i = 0; i < 64; i++) {
|
|
1194
|
+
let f, g;
|
|
1195
|
+
if (i < 16) {
|
|
1196
|
+
f = bb & cc | ~bb & dd;
|
|
1197
|
+
g = i;
|
|
1198
|
+
} else if (i < 32) {
|
|
1199
|
+
f = dd & bb | ~dd & cc;
|
|
1200
|
+
g = (5 * i + 1) % 16;
|
|
1201
|
+
} else if (i < 48) {
|
|
1202
|
+
f = bb ^ cc ^ dd;
|
|
1203
|
+
g = (3 * i + 5) % 16;
|
|
1204
|
+
} else {
|
|
1205
|
+
f = cc ^ (bb | ~dd);
|
|
1206
|
+
g = 7 * i % 16;
|
|
1207
|
+
}
|
|
1208
|
+
const next = dd;
|
|
1209
|
+
dd = cc;
|
|
1210
|
+
cc = bb;
|
|
1211
|
+
bb = bb + rotl(aa + f + k[i] + m[offset + g] | 0, s[i]) | 0;
|
|
1212
|
+
aa = next;
|
|
1213
|
+
}
|
|
1214
|
+
a = a + aa | 0;
|
|
1215
|
+
b = b + bb | 0;
|
|
1216
|
+
c = c + cc | 0;
|
|
1217
|
+
d = d + dd | 0;
|
|
1218
|
+
}
|
|
1219
|
+
return littleHex(a) + littleHex(b) + littleHex(c) + littleHex(d);
|
|
1220
|
+
}
|
|
1221
|
+
function sha1(input) {
|
|
1222
|
+
const source = bytes(input);
|
|
1223
|
+
const padded = new Uint8Array(source.length + 9 + 63 >> 6 << 6);
|
|
1224
|
+
padded.set(source);
|
|
1225
|
+
padded[source.length] = 128;
|
|
1226
|
+
const view = new DataView(padded.buffer);
|
|
1227
|
+
view.setUint32(padded.length - 4, source.length * 8);
|
|
1228
|
+
let h0 = 1732584193, h1 = 4023233417, h2 = 2562383102, h3 = 271733878, h4 = 3285377520;
|
|
1229
|
+
for (let offset = 0; offset < padded.length; offset += 64) {
|
|
1230
|
+
const w = new Uint32Array(80);
|
|
1231
|
+
for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4);
|
|
1232
|
+
for (let i = 16; i < 80; i++) w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1) >>> 0;
|
|
1233
|
+
let a = h0, b = h1, c = h2, d = h3, e = h4;
|
|
1234
|
+
for (let i = 0; i < 80; i++) {
|
|
1235
|
+
const f = i < 20 ? b & c | ~b & d : i < 40 ? b ^ c ^ d : i < 60 ? b & c | b & d | c & d : b ^ c ^ d;
|
|
1236
|
+
const t = rotl(a, 5) + f + e + w[i] + (i < 20 ? 1518500249 : i < 40 ? 1859775393 : i < 60 ? 2400959708 : 3395469782) | 0;
|
|
1237
|
+
e = d;
|
|
1238
|
+
d = c;
|
|
1239
|
+
c = rotl(b, 30);
|
|
1240
|
+
b = a;
|
|
1241
|
+
a = t;
|
|
1242
|
+
}
|
|
1243
|
+
h0 = h0 + a | 0;
|
|
1244
|
+
h1 = h1 + b | 0;
|
|
1245
|
+
h2 = h2 + c | 0;
|
|
1246
|
+
h3 = h3 + d | 0;
|
|
1247
|
+
h4 = h4 + e | 0;
|
|
1248
|
+
}
|
|
1249
|
+
return [h0, h1, h2, h3, h4].map((value) => (value >>> 0).toString(16).padStart(8, "0")).join("");
|
|
1250
|
+
}
|
|
1251
|
+
async function hash(input, algorithm = "SHA-256") {
|
|
1252
|
+
const result2 = await requireCrypto().subtle.digest(algorithm, webBytes(input));
|
|
1253
|
+
return hex(new Uint8Array(result2));
|
|
1254
|
+
}
|
|
1255
|
+
var sha256 = (input) => hash(input, "SHA-256");
|
|
1256
|
+
var sha384 = (input) => hash(input, "SHA-384");
|
|
1257
|
+
var sha512 = (input) => hash(input, "SHA-512");
|
|
1258
|
+
async function hmac(input, secret, algorithm = "SHA-256") {
|
|
1259
|
+
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))));
|
|
1262
|
+
}
|
|
1263
|
+
var hmacSha256 = (input, secret) => hmac(input, secret, "SHA-256");
|
|
1264
|
+
var hmacSha512 = (input, secret) => hmac(input, secret, "SHA-512");
|
|
1265
|
+
function crc32(input) {
|
|
1266
|
+
let crc = 4294967295;
|
|
1267
|
+
for (const byte of bytes(input)) {
|
|
1268
|
+
crc ^= byte;
|
|
1269
|
+
for (let i = 0; i < 8; i++) crc = crc >>> 1 ^ (crc & 1 ? 3988292384 : 0);
|
|
1270
|
+
}
|
|
1271
|
+
return ((crc ^ 4294967295) >>> 0).toString(16).padStart(8, "0");
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
// lib/tools/text-station.ts
|
|
1275
|
+
var MAX_TEXT_LENGTH = 1e6;
|
|
1276
|
+
var MAX_DIFF_LINES = 2e3;
|
|
1277
|
+
var MAX_DIFF_CELLS = 4e6;
|
|
1278
|
+
var LOREM_WORDS = [
|
|
1279
|
+
"lorem",
|
|
1280
|
+
"ipsum",
|
|
1281
|
+
"dolor",
|
|
1282
|
+
"sit",
|
|
1283
|
+
"amet",
|
|
1284
|
+
"consectetur",
|
|
1285
|
+
"adipiscing",
|
|
1286
|
+
"elit",
|
|
1287
|
+
"sed",
|
|
1288
|
+
"do",
|
|
1289
|
+
"eiusmod",
|
|
1290
|
+
"tempor",
|
|
1291
|
+
"incididunt",
|
|
1292
|
+
"ut",
|
|
1293
|
+
"labore",
|
|
1294
|
+
"et",
|
|
1295
|
+
"dolore",
|
|
1296
|
+
"magna",
|
|
1297
|
+
"aliqua",
|
|
1298
|
+
"enim",
|
|
1299
|
+
"ad",
|
|
1300
|
+
"minim",
|
|
1301
|
+
"veniam",
|
|
1302
|
+
"quis",
|
|
1303
|
+
"nostrud",
|
|
1304
|
+
"exercitation",
|
|
1305
|
+
"ullamco",
|
|
1306
|
+
"laboris",
|
|
1307
|
+
"nisi",
|
|
1308
|
+
"aliquip",
|
|
1309
|
+
"ex",
|
|
1310
|
+
"ea",
|
|
1311
|
+
"commodo",
|
|
1312
|
+
" consequat",
|
|
1313
|
+
"duis",
|
|
1314
|
+
"aute",
|
|
1315
|
+
"irure",
|
|
1316
|
+
"in",
|
|
1317
|
+
"reprehenderit",
|
|
1318
|
+
"voluptate",
|
|
1319
|
+
"velit",
|
|
1320
|
+
"esse",
|
|
1321
|
+
"cillum",
|
|
1322
|
+
"fugiat",
|
|
1323
|
+
"nulla",
|
|
1324
|
+
"pariatur",
|
|
1325
|
+
"excepteur",
|
|
1326
|
+
"sint",
|
|
1327
|
+
"occaecat",
|
|
1328
|
+
"cupidatat",
|
|
1329
|
+
"non",
|
|
1330
|
+
"proident",
|
|
1331
|
+
"sunt",
|
|
1332
|
+
"culpa",
|
|
1333
|
+
"qui",
|
|
1334
|
+
"officia",
|
|
1335
|
+
"deserunt",
|
|
1336
|
+
"mollit",
|
|
1337
|
+
"anim",
|
|
1338
|
+
"id",
|
|
1339
|
+
"est",
|
|
1340
|
+
"laborum"
|
|
1341
|
+
].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.`);
|
|
1345
|
+
return value;
|
|
1346
|
+
}
|
|
1347
|
+
function parseLines(value) {
|
|
1348
|
+
assertText(value);
|
|
1349
|
+
const firstCrLf = value.indexOf("\r\n");
|
|
1350
|
+
const firstLf = value.indexOf("\n");
|
|
1351
|
+
const firstCr = value.indexOf("\r");
|
|
1352
|
+
let ending = "\n";
|
|
1353
|
+
if (firstCrLf >= 0 && (firstLf < 0 || firstCrLf <= firstLf)) ending = "\r\n";
|
|
1354
|
+
else if (firstCr >= 0 && (firstLf < 0 || firstCr < firstLf)) ending = "\r";
|
|
1355
|
+
const normalized = value.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
1356
|
+
if (!normalized) return { lines: [], ending, trailingBreak: false };
|
|
1357
|
+
const trailingBreak = normalized.endsWith("\n");
|
|
1358
|
+
const body = trailingBreak ? normalized.slice(0, -1) : normalized;
|
|
1359
|
+
return { lines: body ? body.split("\n") : [""], ending, trailingBreak };
|
|
1360
|
+
}
|
|
1361
|
+
function firstCharacterUpper(value, locale) {
|
|
1362
|
+
const characters = Array.from(value);
|
|
1363
|
+
if (!characters.length) return value;
|
|
1364
|
+
return characters[0].toLocaleUpperCase(locale) + characters.slice(1).join("");
|
|
1365
|
+
}
|
|
1366
|
+
function wordsOf(value) {
|
|
1367
|
+
return value.replace(/([\p{Ll}\p{N}])([\p{Lu}])/gu, "$1 $2").match(/[\p{L}\p{N}]+/gu) ?? [];
|
|
1368
|
+
}
|
|
1369
|
+
function convertCase(value, style, options = {}) {
|
|
1370
|
+
assertText(value);
|
|
1371
|
+
const locale = options.locale;
|
|
1372
|
+
if (style === "upper") return value.toLocaleUpperCase(locale);
|
|
1373
|
+
if (style === "lower") return value.toLocaleLowerCase(locale);
|
|
1374
|
+
if (style === "title") {
|
|
1375
|
+
return value.toLocaleLowerCase(locale).replace(/(^|[\s\-_\/.])([\p{L}\p{N}])/gu, (_, separator, character) => `${separator}${character.toLocaleUpperCase(locale)}`);
|
|
1376
|
+
}
|
|
1377
|
+
if (style === "sentence") {
|
|
1378
|
+
const lower = value.toLocaleLowerCase(locale);
|
|
1379
|
+
return lower.replace(/(^|[.!?…。!?]\s+)(\s*)([\p{L}\p{N}])/gu, (_, boundary, whitespace, character) => `${boundary}${whitespace}${character.toLocaleUpperCase(locale)}`);
|
|
1380
|
+
}
|
|
1381
|
+
const words2 = wordsOf(value).map((word) => word.toLocaleLowerCase(locale));
|
|
1382
|
+
if (style === "camel") return words2.map((word, index) => index === 0 ? word : firstCharacterUpper(word, locale)).join("");
|
|
1383
|
+
if (style === "pascal") return words2.map((word) => firstCharacterUpper(word, locale)).join("");
|
|
1384
|
+
if (style === "snake") return words2.join("_");
|
|
1385
|
+
if (style === "kebab") return words2.join("-");
|
|
1386
|
+
if (style === "constant") return words2.map((word) => word.toLocaleUpperCase(locale)).join("_");
|
|
1387
|
+
throw new Error(`Unsupported case style: ${String(style)}.`);
|
|
1388
|
+
}
|
|
1389
|
+
function escapeRegex(value) {
|
|
1390
|
+
return value.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&");
|
|
1391
|
+
}
|
|
1392
|
+
function diffOperations(left, right) {
|
|
1393
|
+
if (left.length > MAX_DIFF_LINES || right.length > MAX_DIFF_LINES) throw new RangeError(`Text diff supports at most ${MAX_DIFF_LINES.toLocaleString()} lines per side.`);
|
|
1394
|
+
if (left.length * right.length > MAX_DIFF_CELLS) throw new RangeError("Text diff inputs are too large to compare safely; reduce the number of lines.");
|
|
1395
|
+
const table = Array.from({ length: left.length + 1 }, () => new Uint32Array(right.length + 1));
|
|
1396
|
+
for (let i2 = left.length - 1; i2 >= 0; i2 -= 1) {
|
|
1397
|
+
for (let j2 = right.length - 1; j2 >= 0; j2 -= 1) table[i2][j2] = left[i2] === right[j2] ? table[i2 + 1][j2 + 1] + 1 : Math.max(table[i2 + 1][j2], table[i2][j2 + 1]);
|
|
1398
|
+
}
|
|
1399
|
+
const operations = [];
|
|
1400
|
+
let i = 0;
|
|
1401
|
+
let j = 0;
|
|
1402
|
+
while (i < left.length && j < right.length) {
|
|
1403
|
+
if (left[i] === right[j]) {
|
|
1404
|
+
operations.push({ type: "equal", text: left[i] });
|
|
1405
|
+
i += 1;
|
|
1406
|
+
j += 1;
|
|
1407
|
+
} else if (table[i + 1][j] >= table[i][j + 1]) {
|
|
1408
|
+
operations.push({ type: "deletion", text: left[i] });
|
|
1409
|
+
i += 1;
|
|
1410
|
+
} else {
|
|
1411
|
+
operations.push({ type: "addition", text: right[j] });
|
|
1412
|
+
j += 1;
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
while (i < left.length) operations.push({ type: "deletion", text: left[i++] });
|
|
1416
|
+
while (j < right.length) operations.push({ type: "addition", text: right[j++] });
|
|
1417
|
+
return operations;
|
|
1418
|
+
}
|
|
1419
|
+
function buildUnified(operations) {
|
|
1420
|
+
let oldLine = 1;
|
|
1421
|
+
let newLine = 1;
|
|
1422
|
+
let added = 0;
|
|
1423
|
+
let removed = 0;
|
|
1424
|
+
const lines = operations.map((operation) => {
|
|
1425
|
+
if (operation.type === "equal") return { type: "context", text: operation.text, oldLine: oldLine++, newLine: newLine++ };
|
|
1426
|
+
if (operation.type === "deletion") {
|
|
1427
|
+
removed += 1;
|
|
1428
|
+
return { type: "deletion", text: operation.text, oldLine: oldLine++, newLine: null };
|
|
1429
|
+
}
|
|
1430
|
+
added += 1;
|
|
1431
|
+
return { type: "addition", text: operation.text, oldLine: null, newLine: newLine++ };
|
|
1432
|
+
});
|
|
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 };
|
|
1435
|
+
}
|
|
1436
|
+
function buildSideBySide(operations) {
|
|
1437
|
+
const rows = [];
|
|
1438
|
+
let leftLine = 1;
|
|
1439
|
+
let rightLine = 1;
|
|
1440
|
+
for (let i = 0; i < operations.length; i += 1) {
|
|
1441
|
+
const operation = operations[i];
|
|
1442
|
+
if (operation.type === "equal") {
|
|
1443
|
+
rows.push({ type: "equal", left: { line: leftLine++, text: operation.text }, right: { line: rightLine++, text: operation.text } });
|
|
1444
|
+
continue;
|
|
1445
|
+
}
|
|
1446
|
+
const deleted = [];
|
|
1447
|
+
const added = [];
|
|
1448
|
+
while (i < operations.length && operations[i].type !== "equal") {
|
|
1449
|
+
if (operations[i].type === "deletion") deleted.push(operations[i].text);
|
|
1450
|
+
else added.push(operations[i].text);
|
|
1451
|
+
i += 1;
|
|
1452
|
+
}
|
|
1453
|
+
i -= 1;
|
|
1454
|
+
const width = Math.max(deleted.length, added.length);
|
|
1455
|
+
for (let offset = 0; offset < width; offset += 1) {
|
|
1456
|
+
const left = deleted[offset];
|
|
1457
|
+
const right = added[offset];
|
|
1458
|
+
rows.push({
|
|
1459
|
+
type: left !== void 0 && right !== void 0 ? "changed" : left !== void 0 ? "removed" : "added",
|
|
1460
|
+
left: left === void 0 ? null : { line: leftLine++, text: left },
|
|
1461
|
+
right: right === void 0 ? null : { line: rightLine++, text: right }
|
|
1462
|
+
});
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
return rows;
|
|
1466
|
+
}
|
|
1467
|
+
function textDiff(left, right) {
|
|
1468
|
+
const leftParsed = parseLines(left);
|
|
1469
|
+
const rightParsed = parseLines(right);
|
|
1470
|
+
const operations = diffOperations(leftParsed.lines, rightParsed.lines);
|
|
1471
|
+
const unified = buildUnified(operations);
|
|
1472
|
+
const sideBySide = buildSideBySide(operations);
|
|
1473
|
+
return {
|
|
1474
|
+
changed: unified.added > 0 || unified.removed > 0,
|
|
1475
|
+
added: unified.added,
|
|
1476
|
+
removed: unified.removed,
|
|
1477
|
+
unified: unified.text,
|
|
1478
|
+
unifiedLines: unified.lines,
|
|
1479
|
+
sideBySide,
|
|
1480
|
+
unifiedData: unified.lines,
|
|
1481
|
+
sideBySideData: sideBySide
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
function diffText(left, right) {
|
|
1485
|
+
return textDiff(left, right).unified;
|
|
1486
|
+
}
|
|
1487
|
+
function slugify(value, separator = "-") {
|
|
1488
|
+
assertText(value);
|
|
1489
|
+
assertText(separator, "separator");
|
|
1490
|
+
if (!separator || separator.length > 16 || /[\p{L}\p{N}]/u.test(separator)) throw new Error("Slug separator must be 1\u201316 non-alphanumeric characters.");
|
|
1491
|
+
return value.normalize("NFKD").replace(/[\u0300-\u036f]/gu, "").toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu, separator).replace(new RegExp(`(?:${escapeRegex(separator)})+`, "g"), separator).replace(new RegExp(`^${escapeRegex(separator)}|${escapeRegex(separator)}$`, "g"), "");
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
// lib/tools/date-time-station.ts
|
|
1495
|
+
var SECOND = 1e3;
|
|
1496
|
+
var MINUTE = 60 * SECOND;
|
|
1497
|
+
var HOUR = 60 * MINUTE;
|
|
1498
|
+
var DAY = 24 * HOUR;
|
|
1499
|
+
var MIN_DATE = -621355968e5;
|
|
1500
|
+
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}.`);
|
|
1503
|
+
return value;
|
|
1504
|
+
}
|
|
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;
|
|
1511
|
+
}
|
|
1512
|
+
function isGregorianLeapYear(year) {
|
|
1513
|
+
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
1514
|
+
}
|
|
1515
|
+
function daysInMonth(year, month) {
|
|
1516
|
+
return [31, isGregorianLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
|
|
1517
|
+
}
|
|
1518
|
+
function validateParts(parts) {
|
|
1519
|
+
integer(parts.year, "Year", 1, 9999);
|
|
1520
|
+
integer(parts.month, "Month", 1, 12);
|
|
1521
|
+
integer(parts.day, "Day", 1, daysInMonth(parts.year, parts.month));
|
|
1522
|
+
integer(parts.hour, "Hour", 0, 23);
|
|
1523
|
+
integer(parts.minute, "Minute", 0, 59);
|
|
1524
|
+
integer(parts.second, "Second", 0, 59);
|
|
1525
|
+
integer(parts.millisecond, "Millisecond", 0, 999);
|
|
1526
|
+
}
|
|
1527
|
+
function utcMilliseconds(parts) {
|
|
1528
|
+
const date = /* @__PURE__ */ new Date(0);
|
|
1529
|
+
date.setUTCFullYear(parts.year, parts.month - 1, parts.day);
|
|
1530
|
+
date.setUTCHours(parts.hour ?? 0, parts.minute ?? 0, parts.second ?? 0, parts.millisecond ?? 0);
|
|
1531
|
+
return date.getTime();
|
|
1532
|
+
}
|
|
1533
|
+
function checkedDate(milliseconds) {
|
|
1534
|
+
if (!Number.isFinite(milliseconds)) throw new RangeError("Date or timestamp must be finite and valid.");
|
|
1535
|
+
if (milliseconds < MIN_DATE || milliseconds > MAX_DATE) throw new RangeError("Date must be within Gregorian years 0001\u20139999 in UTC.");
|
|
1536
|
+
return new Date(milliseconds);
|
|
1537
|
+
}
|
|
1538
|
+
function timestampUnit(unit) {
|
|
1539
|
+
if (unit !== "seconds" && unit !== "milliseconds") throw new Error("Timestamp unit must be seconds or milliseconds.");
|
|
1540
|
+
return unit;
|
|
1541
|
+
}
|
|
1542
|
+
function timestampToDate(value, unit = "seconds") {
|
|
1543
|
+
timestampUnit(unit);
|
|
1544
|
+
let number;
|
|
1545
|
+
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);
|
|
1549
|
+
} else if (typeof value === "number") number = value;
|
|
1550
|
+
else throw new TypeError("Timestamp must be a number or numeric text.");
|
|
1551
|
+
if (!Number.isFinite(number)) throw new RangeError("Timestamp must be finite.");
|
|
1552
|
+
if (unit === "milliseconds" && !Number.isInteger(number)) throw new RangeError("A millisecond timestamp must be an integer.");
|
|
1553
|
+
return checkedDate(unit === "seconds" ? Math.round(number * SECOND) : number);
|
|
1554
|
+
}
|
|
1555
|
+
function zoneFormatter(timeZone) {
|
|
1556
|
+
const zone = inputText(timeZone, "Time zone", 128);
|
|
1557
|
+
if (/^[+-]/.test(zone)) throw new Error("Use an IANA time zone such as America/New_York, Asia/Kolkata, or UTC.");
|
|
1558
|
+
try {
|
|
1559
|
+
return new Intl.DateTimeFormat("en-US", {
|
|
1560
|
+
timeZone: zone,
|
|
1561
|
+
calendar: "gregory",
|
|
1562
|
+
numberingSystem: "latn",
|
|
1563
|
+
era: "short",
|
|
1564
|
+
year: "numeric",
|
|
1565
|
+
month: "2-digit",
|
|
1566
|
+
day: "2-digit",
|
|
1567
|
+
hour: "2-digit",
|
|
1568
|
+
minute: "2-digit",
|
|
1569
|
+
second: "2-digit",
|
|
1570
|
+
hourCycle: "h23"
|
|
1571
|
+
});
|
|
1572
|
+
} catch {
|
|
1573
|
+
throw new Error(`Unknown or unsupported IANA time zone: ${zone}.`);
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
function validateTimeZone(timeZone) {
|
|
1577
|
+
return zoneFormatter(timeZone).resolvedOptions().timeZone;
|
|
1578
|
+
}
|
|
1579
|
+
function zoneParts(milliseconds, formatter) {
|
|
1580
|
+
const fields = Object.fromEntries(formatter.formatToParts(new Date(milliseconds)).map((part) => [part.type, part.value]));
|
|
1581
|
+
return {
|
|
1582
|
+
year: fields.era === "BC" ? 1 - Number(fields.year) : Number(fields.year),
|
|
1583
|
+
month: Number(fields.month),
|
|
1584
|
+
day: Number(fields.day),
|
|
1585
|
+
hour: Number(fields.hour),
|
|
1586
|
+
minute: Number(fields.minute),
|
|
1587
|
+
second: Number(fields.second),
|
|
1588
|
+
millisecond: (milliseconds % SECOND + SECOND) % SECOND
|
|
1589
|
+
};
|
|
1590
|
+
}
|
|
1591
|
+
function disambiguation(value = "reject") {
|
|
1592
|
+
if (!["reject", "earlier", "later"].includes(value)) throw new Error("Time disambiguation must be reject, earlier, or later.");
|
|
1593
|
+
return value;
|
|
1594
|
+
}
|
|
1595
|
+
function sameParts(left, right) {
|
|
1596
|
+
return left.year === right.year && left.month === right.month && left.day === right.day && left.hour === right.hour && left.minute === right.minute && left.second === right.second && left.millisecond === right.millisecond;
|
|
1597
|
+
}
|
|
1598
|
+
function localToDate(parts, formatter, choice) {
|
|
1599
|
+
const wall = utcMilliseconds(parts);
|
|
1600
|
+
const offsets = /* @__PURE__ */ new Set();
|
|
1601
|
+
for (let hours = -48; hours <= 48; hours += 12) {
|
|
1602
|
+
const sample = wall + hours * HOUR;
|
|
1603
|
+
offsets.add(utcMilliseconds(zoneParts(sample, formatter)) - sample);
|
|
1604
|
+
}
|
|
1605
|
+
const matches = [...offsets].map((offset) => wall - offset).filter((candidate) => sameParts(zoneParts(candidate, formatter), parts)).sort((a, b) => a - b);
|
|
1606
|
+
const zone = formatter.resolvedOptions().timeZone;
|
|
1607
|
+
if (!matches.length) throw new Error(`This local time does not exist in ${zone} because of a time-zone clock change. Choose another time or an explicit UTC offset.`);
|
|
1608
|
+
if (matches.length > 1 && choice === "reject") throw new Error(`This local time occurs twice in ${zone}. Choose earlier or later, or supply an explicit UTC offset.`);
|
|
1609
|
+
return checkedDate(choice === "later" ? matches[matches.length - 1] : matches[0]);
|
|
1610
|
+
}
|
|
1611
|
+
function offsetMilliseconds(value) {
|
|
1612
|
+
if (/^z$/i.test(value)) return 0;
|
|
1613
|
+
const match = /^([+-])(\d{2}):?(\d{2})$/.exec(value);
|
|
1614
|
+
if (!match) throw new Error("UTC offset must be Z or \xB1HH:mm.");
|
|
1615
|
+
const hours = integer(Number(match[2]), "Offset hour", 0, 23);
|
|
1616
|
+
const minutes = integer(Number(match[3]), "Offset minute", 0, 59);
|
|
1617
|
+
if (match[1] === "-" && hours === 0 && minutes === 0) throw new Error("The unknown UTC offset -00:00 cannot identify an instant. Use Z or a known offset.");
|
|
1618
|
+
return (match[1] === "-" ? -1 : 1) * (hours * HOUR + minutes * MINUTE);
|
|
1619
|
+
}
|
|
1620
|
+
function partsToDate(parts, offset, options) {
|
|
1621
|
+
validateParts(parts);
|
|
1622
|
+
const choice = disambiguation(options.disambiguation);
|
|
1623
|
+
const formatter = zoneFormatter(options.timeZone ?? "UTC");
|
|
1624
|
+
return offset ? checkedDate(utcMilliseconds(parts) - offsetMilliseconds(offset)) : localToDate(parts, formatter, choice);
|
|
1625
|
+
}
|
|
1626
|
+
function parseDateTime(value, options = {}) {
|
|
1627
|
+
timestampUnit(options.timestampUnit ?? "milliseconds");
|
|
1628
|
+
disambiguation(options.disambiguation);
|
|
1629
|
+
if (options.timeZone !== void 0) validateTimeZone(options.timeZone);
|
|
1630
|
+
if (value instanceof Date) return checkedDate(value.getTime());
|
|
1631
|
+
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);
|
|
1635
|
+
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
|
+
return partsToDate({
|
|
1637
|
+
year: Number(match[1]),
|
|
1638
|
+
month: Number(match[2]),
|
|
1639
|
+
day: Number(match[3]),
|
|
1640
|
+
hour: Number(match[4] ?? 0),
|
|
1641
|
+
minute: Number(match[5] ?? 0),
|
|
1642
|
+
second: Number(match[6] ?? 0),
|
|
1643
|
+
millisecond: Number((match[7] ?? "").padEnd(3, "0"))
|
|
1644
|
+
}, match[8], options);
|
|
1645
|
+
}
|
|
1646
|
+
function pad(value, length = 2) {
|
|
1647
|
+
return String(value).padStart(length, "0");
|
|
1648
|
+
}
|
|
1649
|
+
function calendarText(parts) {
|
|
1650
|
+
return `${pad(parts.year, 4)}-${pad(parts.month)}-${pad(parts.day)}`;
|
|
1651
|
+
}
|
|
1652
|
+
function clockText(parts) {
|
|
1653
|
+
return `${pad(parts.hour)}:${pad(parts.minute)}:${pad(parts.second)}.${pad(parts.millisecond, 3)}`;
|
|
1654
|
+
}
|
|
1655
|
+
function offsetText(milliseconds) {
|
|
1656
|
+
if (!milliseconds) return "Z";
|
|
1657
|
+
const seconds = Math.abs(milliseconds) / SECOND;
|
|
1658
|
+
const hours = Math.floor(seconds / 3600);
|
|
1659
|
+
const minutes = Math.floor(seconds % 3600 / 60);
|
|
1660
|
+
const remainder = seconds % 60;
|
|
1661
|
+
return `${milliseconds < 0 ? "-" : "+"}${pad(hours)}:${pad(minutes)}${remainder ? `:${pad(remainder)}` : ""}`;
|
|
1662
|
+
}
|
|
1663
|
+
function getZonedDateTime(value, timeZone = "UTC", options = {}) {
|
|
1664
|
+
const date = parseDateTime(value, options);
|
|
1665
|
+
const formatter = zoneFormatter(timeZone);
|
|
1666
|
+
const parts = zoneParts(date.getTime(), formatter);
|
|
1667
|
+
validateParts(parts);
|
|
1668
|
+
const offset = utcMilliseconds(parts) - date.getTime();
|
|
1669
|
+
const renderedOffset = offsetText(offset);
|
|
1670
|
+
return {
|
|
1671
|
+
...parts,
|
|
1672
|
+
timeZone: formatter.resolvedOptions().timeZone,
|
|
1673
|
+
offsetMinutes: offset / MINUTE,
|
|
1674
|
+
offset: renderedOffset,
|
|
1675
|
+
unixMilliseconds: date.getTime(),
|
|
1676
|
+
iso: date.toISOString(),
|
|
1677
|
+
dateTime: `${calendarText(parts)}T${clockText(parts)}${renderedOffset}`
|
|
1678
|
+
};
|
|
1679
|
+
}
|
|
1680
|
+
function formatRfc3339(value, timeZoneOrOptions = "UTC", options = {}) {
|
|
1681
|
+
const timeZone = typeof timeZoneOrOptions === "string" ? timeZoneOrOptions : timeZoneOrOptions.timeZone ?? "UTC";
|
|
1682
|
+
const parseOptions = typeof timeZoneOrOptions === "string" ? options : timeZoneOrOptions;
|
|
1683
|
+
const zoned = getZonedDateTime(value, timeZone, parseOptions);
|
|
1684
|
+
if (!Number.isInteger(zoned.offsetMinutes)) throw new Error("RFC3339 cannot represent this historical sub-minute UTC offset. Format in UTC instead.");
|
|
1685
|
+
return zoned.dateTime;
|
|
1686
|
+
}
|
|
1687
|
+
function convertTimeZone(value, targetTimeZone, options = {}) {
|
|
1688
|
+
const parseOptions = typeof options === "string" ? { timeZone: options } : options;
|
|
1689
|
+
return formatRfc3339(value, targetTimeZone, parseOptions);
|
|
1690
|
+
}
|
|
1691
|
+
function convertBetweenTimeZones(value, sourceTimeZone, targetTimeZone) {
|
|
1692
|
+
return convertTimeZone(value, targetTimeZone, { timeZone: sourceTimeZone });
|
|
1693
|
+
}
|
|
1694
|
+
var relativeUnits = [
|
|
1695
|
+
{ unit: "year", milliseconds: 365 * DAY },
|
|
1696
|
+
{ unit: "quarter", milliseconds: 91 * DAY },
|
|
1697
|
+
{ unit: "month", milliseconds: 30 * DAY },
|
|
1698
|
+
{ unit: "week", milliseconds: 7 * DAY },
|
|
1699
|
+
{ unit: "day", milliseconds: DAY },
|
|
1700
|
+
{ unit: "hour", milliseconds: HOUR },
|
|
1701
|
+
{ unit: "minute", milliseconds: MINUTE },
|
|
1702
|
+
{ unit: "second", milliseconds: SECOND }
|
|
1703
|
+
];
|
|
1704
|
+
function calendarCompare(left, right) {
|
|
1705
|
+
return utcMilliseconds(left) - utcMilliseconds(right);
|
|
1706
|
+
}
|
|
1707
|
+
function calendarDayNumber(date) {
|
|
1708
|
+
return Math.floor(utcMilliseconds(date) / DAY);
|
|
1709
|
+
}
|
|
1710
|
+
function calendarFromDayNumber(day) {
|
|
1711
|
+
const date = new Date(day * DAY);
|
|
1712
|
+
return { year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate() };
|
|
1713
|
+
}
|
|
1714
|
+
function calendarWeekday(date) {
|
|
1715
|
+
return new Date(utcMilliseconds(date)).getUTCDay();
|
|
1716
|
+
}
|
|
1717
|
+
function dateCalendar(value, options) {
|
|
1718
|
+
const zoned = getZonedDateTime(value, options.timeZone ?? "UTC", { timeZone: options.timeZone ?? "UTC" });
|
|
1719
|
+
return { year: zoned.year, month: zoned.month, day: zoned.day };
|
|
1720
|
+
}
|
|
1721
|
+
function weekdaysInclusive(start, end) {
|
|
1722
|
+
if (calendarCompare(start, end) > 0) return -weekdaysInclusive(end, start);
|
|
1723
|
+
const first = calendarDayNumber(start);
|
|
1724
|
+
const total = calendarDayNumber(end) - first + 1;
|
|
1725
|
+
const weeks = Math.floor(total / 7);
|
|
1726
|
+
let count = weeks * 5;
|
|
1727
|
+
for (let day = first + weeks * 7; day <= calendarDayNumber(end); day += 1) {
|
|
1728
|
+
const weekday = new Date(day * DAY).getUTCDay();
|
|
1729
|
+
if (weekday !== 0 && weekday !== 6) count += 1;
|
|
1730
|
+
}
|
|
1731
|
+
return count;
|
|
1732
|
+
}
|
|
1733
|
+
function businessDaysBetween(start, end, options = {}) {
|
|
1734
|
+
const left = dateCalendar(start, options);
|
|
1735
|
+
const right = dateCalendar(end, options);
|
|
1736
|
+
if (calendarCompare(left, right) === 0) return (options.inclusiveStart ?? true) && (options.inclusiveEnd ?? false) && calendarWeekday(left) !== 0 && calendarWeekday(left) !== 6 ? 1 : 0;
|
|
1737
|
+
const direction = calendarCompare(left, right) < 0 ? 1 : -1;
|
|
1738
|
+
const earlier = direction > 0 ? left : right;
|
|
1739
|
+
const later = direction > 0 ? right : left;
|
|
1740
|
+
let first = calendarDayNumber(earlier);
|
|
1741
|
+
let last = calendarDayNumber(later);
|
|
1742
|
+
const includeEarlier = direction > 0 ? options.inclusiveStart ?? true : options.inclusiveEnd ?? false;
|
|
1743
|
+
const includeLater = direction > 0 ? options.inclusiveEnd ?? false : options.inclusiveStart ?? true;
|
|
1744
|
+
if (!includeEarlier) first += 1;
|
|
1745
|
+
if (!includeLater) last -= 1;
|
|
1746
|
+
if (first > last) return 0;
|
|
1747
|
+
return direction * weekdaysInclusive(calendarFromDayNumber(first), calendarFromDayNumber(last));
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
// lib/tools/cron/parser.ts
|
|
1751
|
+
var MONTH_NAMES = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
|
|
1752
|
+
var WEEKDAY_NAMES = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
|
|
1753
|
+
var SPECS = [
|
|
1754
|
+
{ name: "second", label: "Second", min: 0, max: 59 },
|
|
1755
|
+
{ name: "minute", label: "Minute", min: 0, max: 59 },
|
|
1756
|
+
{ name: "hour", label: "Hour", min: 0, max: 23 },
|
|
1757
|
+
{ name: "dayOfMonth", label: "Day of month", min: 1, max: 31 },
|
|
1758
|
+
{ name: "month", label: "Month", min: 1, max: 12 },
|
|
1759
|
+
{ name: "dayOfWeek", label: "Day of week", min: 0, max: 7 }
|
|
1760
|
+
];
|
|
1761
|
+
function parseField(expression, spec) {
|
|
1762
|
+
const fail = (message) => {
|
|
1763
|
+
throw new Error(`${spec.label}: ${message}`);
|
|
1764
|
+
};
|
|
1765
|
+
if (expression.length > 128) fail("field exceeds the 128-character limit.");
|
|
1766
|
+
if (!expression) fail("field cannot be empty.");
|
|
1767
|
+
const endpoint = (text3) => {
|
|
1768
|
+
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());
|
|
1772
|
+
else return fail("use integer values, permitted month/weekday names, *, ranges, lists or steps.");
|
|
1773
|
+
if (!Number.isSafeInteger(value) || value < spec.min || value > spec.max) fail(`value must be between ${spec.min} and ${spec.max}.`);
|
|
1774
|
+
return value;
|
|
1775
|
+
};
|
|
1776
|
+
const selected = /* @__PURE__ */ new Set();
|
|
1777
|
+
for (const item of expression.split(",")) {
|
|
1778
|
+
if (!item) fail("lists cannot contain empty items.");
|
|
1779
|
+
const pieces = item.split("/");
|
|
1780
|
+
if (pieces.length > 2 || !pieces[0]) fail("malformed step notation.");
|
|
1781
|
+
let step = 1;
|
|
1782
|
+
if (pieces.length === 2) {
|
|
1783
|
+
if (!/^\d+$/.test(pieces[1])) fail("step must be a positive integer.");
|
|
1784
|
+
step = Number(pieces[1]);
|
|
1785
|
+
if (!Number.isSafeInteger(step) || step < 1 || step > spec.max - spec.min + 1) fail(`step must be between 1 and ${spec.max - spec.min + 1}.`);
|
|
1786
|
+
}
|
|
1787
|
+
const base = pieces[0];
|
|
1788
|
+
let first;
|
|
1789
|
+
let last;
|
|
1790
|
+
if (base === "*") {
|
|
1791
|
+
first = spec.min;
|
|
1792
|
+
last = spec.max;
|
|
1793
|
+
} else {
|
|
1794
|
+
const range = base.split("-");
|
|
1795
|
+
if (range.length > 2 || range.some((value) => !value)) fail("malformed range; negative values are not supported.");
|
|
1796
|
+
first = endpoint(range[0]);
|
|
1797
|
+
last = range.length === 2 ? endpoint(range[1]) : pieces.length === 2 ? spec.max : first;
|
|
1798
|
+
if (last < first) fail("descending or wrapping ranges are not supported.");
|
|
1799
|
+
}
|
|
1800
|
+
for (let value = first; value <= last; value += step) selected.add(spec.name === "dayOfWeek" && value === 7 ? 0 : value);
|
|
1801
|
+
}
|
|
1802
|
+
return { ...spec, expression, values: [...selected].sort((a, b) => a - b), wildcard: expression.startsWith("*") };
|
|
1803
|
+
}
|
|
1804
|
+
function parseCron(expression) {
|
|
1805
|
+
if (typeof expression !== "string" || !expression.trim()) throw new Error("Enter a cron expression.");
|
|
1806
|
+
if (expression.length > 1024) throw new Error("Cron expression exceeds the 1,024-character limit.");
|
|
1807
|
+
if (/[?#]/.test(expression) || /(?:^|[\s,/-])(?:L|LW|\d+[LW]|W|H(?:\([^)]*\))?)(?=$|[\s,/-])/i.test(expression) || /\b(?:cron|rate)\s*\(/i.test(expression)) {
|
|
1808
|
+
throw new Error("Quartz, AWS and Jenkins extensions (?, L, W, # and H) are not supported; use Unix numeric cron notation.");
|
|
1809
|
+
}
|
|
1810
|
+
if (expression.includes("@")) throw new Error("Cron macros are not supported; enter five Unix fields or six seconds-first fields.");
|
|
1811
|
+
const tokens = expression.trim().split(/\s+/);
|
|
1812
|
+
if (tokens.length !== 5 && tokens.length !== 6) throw new Error("Expected five Unix fields or six seconds-first fields; years, commands, comments and environment assignments are not supported.");
|
|
1813
|
+
const hasSeconds = tokens.length === 6;
|
|
1814
|
+
const fields = tokens.map((token, index) => parseField(token, SPECS[index + (hasSeconds ? 0 : 1)]));
|
|
1815
|
+
const second = hasSeconds ? fields[0] : parseField("0", SPECS[0]);
|
|
1816
|
+
const [minute, hour, dayOfMonth, month, dayOfWeek] = fields.slice(hasSeconds ? 1 : 0);
|
|
1817
|
+
return { expression, hasSeconds, fields, second, minute, hour, dayOfMonth, month, dayOfWeek, dayMode: dayOfMonth.wildcard || dayOfWeek.wildcard ? "and" : "or" };
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
// lib/tools/cron/explain.ts
|
|
1821
|
+
var FULL_MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
|
1822
|
+
var FULL_WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
|
|
1823
|
+
var pad2 = (value) => String(value).padStart(2, "0");
|
|
1824
|
+
function explainCron(cron) {
|
|
1825
|
+
let timing;
|
|
1826
|
+
if (cron.hour.values.length === 1 && cron.minute.values.length === 1 && cron.second.values.length === 1) {
|
|
1827
|
+
timing = `At ${pad2(cron.hour.values[0])}:${pad2(cron.minute.values[0])}${cron.hasSeconds ? `:${pad2(cron.second.values[0])}` : ""}`;
|
|
1828
|
+
} else if (cron.hasSeconds && cron.hour.expression === "*" && cron.minute.expression === "*" && cron.second.expression === "*") timing = "Every second";
|
|
1829
|
+
else if (cron.hour.expression === "*" && cron.minute.expression === "*" && !cron.hasSeconds) timing = "Every minute (at second 0)";
|
|
1830
|
+
else if (cron.hour.expression === "*" && /^\*\/\d+$/.test(cron.minute.expression) && !cron.hasSeconds) timing = `Every ${Number(cron.minute.expression.slice(2))} minutes within each hour (at second 0)`;
|
|
1831
|
+
else if (cron.hour.expression === "*" && cron.minute.values.length === 1 && cron.second.values.length === 1) timing = `Every hour at minute ${cron.minute.values[0]}, second ${cron.second.values[0]}`;
|
|
1832
|
+
else timing = `${cron.hasSeconds ? "Seconds-first schedule" : "Unix schedule (at second 0)"}: hours ${cron.hour.expression === "*" ? "every hour" : cron.hour.values.map(pad2).join(", ")}; minutes ${cron.minute.expression === "*" ? "every minute" : cron.minute.values.map(pad2).join(", ")}${cron.hasSeconds ? `; seconds ${cron.second.expression === "*" ? "every second" : cron.second.values.map(pad2).join(", ")}` : ""}`;
|
|
1833
|
+
const months = cron.month.values.length === 12 ? "" : `; in ${cron.month.values.map((value) => FULL_MONTHS[value - 1]).join(", ")}`;
|
|
1834
|
+
const dom = cron.dayOfMonth.values.length === 31 ? "every day of month" : `day of month ${cron.dayOfMonth.values.join(", ")}`;
|
|
1835
|
+
const dow = cron.dayOfWeek.values.length === 7 ? "every weekday (Sunday\u2013Saturday)" : cron.dayOfWeek.values.map((value) => FULL_WEEKDAYS[value]).join(", ");
|
|
1836
|
+
const days = cron.dayMode === "or" ? `when either ${dom} OR weekday ${dow} matches` : cron.dayOfMonth.values.length === 31 && cron.dayOfWeek.values.length === 7 ? "every day" : cron.dayOfMonth.values.length === 31 ? `on ${dow}` : cron.dayOfWeek.values.length === 7 ? `on ${dom}` : `when both ${dom} AND weekday ${dow} match`;
|
|
1837
|
+
return `${timing}; ${days}${months}.`;
|
|
1838
|
+
}
|
|
1839
|
+
|
|
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);
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
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);
|
|
1945
|
+
}
|
|
1946
|
+
white();
|
|
1947
|
+
if (input[position] === close) break;
|
|
1948
|
+
if (input[position] !== ",") fail(`Expected ',' or '${close}'`);
|
|
1949
|
+
punctuation();
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
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
|
+
}
|
|
2200
|
+
|
|
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("")}`;
|
|
2290
|
+
} 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}`;
|
|
2293
|
+
}
|
|
2294
|
+
if (connection.length > 2e6) throw new Error("Connection string exceeds the output limit.");
|
|
2295
|
+
return { rows: [{ label: "Connection string", value: connection }] };
|
|
2296
|
+
}
|
|
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;
|
|
2328
|
+
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++;
|
|
2367
|
+
} else {
|
|
2368
|
+
closed = true;
|
|
2369
|
+
break;
|
|
2370
|
+
}
|
|
2371
|
+
}
|
|
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.");
|
|
2380
|
+
}
|
|
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.");
|
|
2384
|
+
}
|
|
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);
|
|
2419
|
+
}
|
|
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
|
+
}
|
|
2436
|
+
|
|
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;
|
|
2456
|
+
}
|
|
2457
|
+
|
|
2458
|
+
// mcp/server.ts
|
|
2459
|
+
function createMcpServer(cliKey) {
|
|
2460
|
+
const license = resolveLicense(cliKey);
|
|
2461
|
+
const server = new Server(
|
|
2462
|
+
{
|
|
2463
|
+
name: "codestation-mcp",
|
|
2464
|
+
version: "1.0.0"
|
|
2465
|
+
},
|
|
2466
|
+
{
|
|
2467
|
+
capabilities: {
|
|
2468
|
+
tools: {}
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
);
|
|
2472
|
+
const tools = [
|
|
2473
|
+
// ----------------- FREE TOOLS -----------------
|
|
2474
|
+
{
|
|
2475
|
+
name: "codestation_uuid",
|
|
2476
|
+
description: "Generate cryptographically secure v4 UUIDs. [Free Tier]",
|
|
2477
|
+
inputSchema: {
|
|
2478
|
+
type: "object",
|
|
2479
|
+
properties: {
|
|
2480
|
+
count: {
|
|
2481
|
+
type: "integer",
|
|
2482
|
+
description: "Number of UUIDs to generate (1 to 50, default: 1)",
|
|
2483
|
+
minimum: 1,
|
|
2484
|
+
maximum: 50
|
|
2485
|
+
}
|
|
2486
|
+
}
|
|
2487
|
+
}
|
|
2488
|
+
},
|
|
2489
|
+
{
|
|
2490
|
+
name: "codestation_base64",
|
|
2491
|
+
description: "Encode or decode Base64 and URL-safe Base64 strings. [Free Tier]",
|
|
2492
|
+
inputSchema: {
|
|
2493
|
+
type: "object",
|
|
2494
|
+
properties: {
|
|
2495
|
+
text: { type: "string", description: "The string to encode or decode" },
|
|
2496
|
+
action: {
|
|
2497
|
+
type: "string",
|
|
2498
|
+
enum: ["encode", "decode"],
|
|
2499
|
+
description: "Whether to encode or decode"
|
|
2500
|
+
},
|
|
2501
|
+
urlSafe: {
|
|
2502
|
+
type: "boolean",
|
|
2503
|
+
description: "Whether to use URL-safe Base64 (default: false)"
|
|
2504
|
+
}
|
|
2505
|
+
},
|
|
2506
|
+
required: ["text", "action"]
|
|
2507
|
+
}
|
|
2508
|
+
},
|
|
2509
|
+
{
|
|
2510
|
+
name: "codestation_url_codec",
|
|
2511
|
+
description: "URL encode or decode string components. [Free Tier]",
|
|
2512
|
+
inputSchema: {
|
|
2513
|
+
type: "object",
|
|
2514
|
+
properties: {
|
|
2515
|
+
text: { type: "string", description: "Text to URL-encode or URL-decode" },
|
|
2516
|
+
action: {
|
|
2517
|
+
type: "string",
|
|
2518
|
+
enum: ["encode", "decode"],
|
|
2519
|
+
description: "Action to perform"
|
|
2520
|
+
}
|
|
2521
|
+
},
|
|
2522
|
+
required: ["text", "action"]
|
|
2523
|
+
}
|
|
2524
|
+
},
|
|
2525
|
+
{
|
|
2526
|
+
name: "codestation_hex_codec",
|
|
2527
|
+
description: "Encode UTF-8 string to hexadecimal byte pairs or decode hex to text. [Free Tier]",
|
|
2528
|
+
inputSchema: {
|
|
2529
|
+
type: "object",
|
|
2530
|
+
properties: {
|
|
2531
|
+
text: { type: "string", description: "Text or hex string" },
|
|
2532
|
+
action: {
|
|
2533
|
+
type: "string",
|
|
2534
|
+
enum: ["encode", "decode"],
|
|
2535
|
+
description: "Action to perform"
|
|
2536
|
+
}
|
|
2537
|
+
},
|
|
2538
|
+
required: ["text", "action"]
|
|
2539
|
+
}
|
|
2540
|
+
},
|
|
2541
|
+
{
|
|
2542
|
+
name: "codestation_format_json",
|
|
2543
|
+
description: "Prettify, format, and validate a JSON string. [Free Tier]",
|
|
2544
|
+
inputSchema: {
|
|
2545
|
+
type: "object",
|
|
2546
|
+
properties: {
|
|
2547
|
+
json: { type: "string", description: "Raw JSON string to format" },
|
|
2548
|
+
indent: {
|
|
2549
|
+
type: "integer",
|
|
2550
|
+
description: "Number of spaces for indentation (0-8, default: 2)",
|
|
2551
|
+
minimum: 0,
|
|
2552
|
+
maximum: 8
|
|
2553
|
+
}
|
|
2554
|
+
},
|
|
2555
|
+
required: ["json"]
|
|
2556
|
+
}
|
|
2557
|
+
},
|
|
2558
|
+
{
|
|
2559
|
+
name: "codestation_minify_json",
|
|
2560
|
+
description: "Minify JSON by stripping all whitespace. [Free Tier]",
|
|
2561
|
+
inputSchema: {
|
|
2562
|
+
type: "object",
|
|
2563
|
+
properties: {
|
|
2564
|
+
json: { type: "string", description: "JSON string to minify" }
|
|
2565
|
+
},
|
|
2566
|
+
required: ["json"]
|
|
2567
|
+
}
|
|
2568
|
+
},
|
|
2569
|
+
{
|
|
2570
|
+
name: "codestation_json_to_yaml",
|
|
2571
|
+
description: "Convert JSON to clean YAML format. [Free Tier]",
|
|
2572
|
+
inputSchema: {
|
|
2573
|
+
type: "object",
|
|
2574
|
+
properties: {
|
|
2575
|
+
json: { type: "string", description: "Valid JSON string" }
|
|
2576
|
+
},
|
|
2577
|
+
required: ["json"]
|
|
2578
|
+
}
|
|
2579
|
+
},
|
|
2580
|
+
{
|
|
2581
|
+
name: "codestation_yaml_to_json",
|
|
2582
|
+
description: "Convert YAML formatted text to JSON. [Free Tier]",
|
|
2583
|
+
inputSchema: {
|
|
2584
|
+
type: "object",
|
|
2585
|
+
properties: {
|
|
2586
|
+
yaml: { type: "string", description: "YAML text string" }
|
|
2587
|
+
},
|
|
2588
|
+
required: ["yaml"]
|
|
2589
|
+
}
|
|
2590
|
+
},
|
|
2591
|
+
{
|
|
2592
|
+
name: "codestation_case_convert",
|
|
2593
|
+
description: "Convert text into different naming conventions (camelCase, snake_case, kebab-case, PascalCase, CONSTANT_CASE, etc.). [Free Tier]",
|
|
2594
|
+
inputSchema: {
|
|
2595
|
+
type: "object",
|
|
2596
|
+
properties: {
|
|
2597
|
+
text: { type: "string", description: "The string or identifier to convert" },
|
|
2598
|
+
targetCase: {
|
|
2599
|
+
type: "string",
|
|
2600
|
+
enum: ["camel", "pascal", "snake", "kebab", "constant", "title", "sentence", "upper", "lower"],
|
|
2601
|
+
description: "Target casing style"
|
|
2602
|
+
}
|
|
2603
|
+
},
|
|
2604
|
+
required: ["text", "targetCase"]
|
|
2605
|
+
}
|
|
2606
|
+
},
|
|
2607
|
+
{
|
|
2608
|
+
name: "codestation_text_diff",
|
|
2609
|
+
description: "Generate a clean line-by-line unified diff between original and modified text. [Free Tier]",
|
|
2610
|
+
inputSchema: {
|
|
2611
|
+
type: "object",
|
|
2612
|
+
properties: {
|
|
2613
|
+
original: { type: "string", description: "The original text content" },
|
|
2614
|
+
modified: { type: "string", description: "The updated text content" }
|
|
2615
|
+
},
|
|
2616
|
+
required: ["original", "modified"]
|
|
2617
|
+
}
|
|
2618
|
+
},
|
|
2619
|
+
{
|
|
2620
|
+
name: "codestation_slugify",
|
|
2621
|
+
description: "Convert strings to clean, SEO-friendly URL slugs. [Free Tier]",
|
|
2622
|
+
inputSchema: {
|
|
2623
|
+
type: "object",
|
|
2624
|
+
properties: {
|
|
2625
|
+
text: { type: "string", description: "Text to slugify" },
|
|
2626
|
+
separator: { type: "string", description: "Separator character (default: '-')" }
|
|
2627
|
+
},
|
|
2628
|
+
required: ["text"]
|
|
2629
|
+
}
|
|
2630
|
+
},
|
|
2631
|
+
// ----------------- PRO TOOLS (₹199 / $2.99) -----------------
|
|
2632
|
+
{
|
|
2633
|
+
name: "codestation_hash",
|
|
2634
|
+
description: "Generate cryptographic hashes (SHA-256, SHA-512, MD5, SHA-1, CRC-32). [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2635
|
+
inputSchema: {
|
|
2636
|
+
type: "object",
|
|
2637
|
+
properties: {
|
|
2638
|
+
text: { type: "string", description: "Text to hash" },
|
|
2639
|
+
algorithm: {
|
|
2640
|
+
type: "string",
|
|
2641
|
+
enum: ["SHA-256", "SHA-384", "SHA-512", "MD5", "SHA-1", "CRC32"],
|
|
2642
|
+
description: "Hash algorithm to apply (default: SHA-256)"
|
|
2643
|
+
}
|
|
2644
|
+
},
|
|
2645
|
+
required: ["text"]
|
|
2646
|
+
}
|
|
2647
|
+
},
|
|
2648
|
+
{
|
|
2649
|
+
name: "codestation_hmac",
|
|
2650
|
+
description: "Compute HMAC signatures using Web Crypto. [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2651
|
+
inputSchema: {
|
|
2652
|
+
type: "object",
|
|
2653
|
+
properties: {
|
|
2654
|
+
text: { type: "string", description: "Input message string" },
|
|
2655
|
+
secret: { type: "string", description: "Secret key" },
|
|
2656
|
+
algorithm: {
|
|
2657
|
+
type: "string",
|
|
2658
|
+
enum: ["SHA-256", "SHA-512"],
|
|
2659
|
+
description: "HMAC algorithm (default: SHA-256)"
|
|
2660
|
+
}
|
|
2661
|
+
},
|
|
2662
|
+
required: ["text", "secret"]
|
|
2663
|
+
}
|
|
2664
|
+
},
|
|
2665
|
+
{
|
|
2666
|
+
name: "codestation_jwt_decode",
|
|
2667
|
+
description: "Inspect & decode JSON Web Token (JWT) header, payload claims, and signature in local memory without transmitting secrets. [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2668
|
+
inputSchema: {
|
|
2669
|
+
type: "object",
|
|
2670
|
+
properties: {
|
|
2671
|
+
token: { type: "string", description: "Full JWT string (header.payload.signature)" }
|
|
2672
|
+
},
|
|
2673
|
+
required: ["token"]
|
|
2674
|
+
}
|
|
2675
|
+
},
|
|
2676
|
+
{
|
|
2677
|
+
name: "codestation_format_sql",
|
|
2678
|
+
description: "Format, beautify, and indent SQL queries across PostgreSQL, MySQL, SQLite, and standard SQL. [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2679
|
+
inputSchema: {
|
|
2680
|
+
type: "object",
|
|
2681
|
+
properties: {
|
|
2682
|
+
sql: { type: "string", description: "Raw SQL query to format" },
|
|
2683
|
+
dialect: {
|
|
2684
|
+
type: "string",
|
|
2685
|
+
enum: ["PostgreSQL", "MySQL", "SQLite", "SQL Server"],
|
|
2686
|
+
description: "SQL dialect (default: PostgreSQL)"
|
|
2687
|
+
}
|
|
2688
|
+
},
|
|
2689
|
+
required: ["sql"]
|
|
2690
|
+
}
|
|
2691
|
+
},
|
|
2692
|
+
{
|
|
2693
|
+
name: "codestation_cron_explain",
|
|
2694
|
+
description: "Parse and explain 5-field Unix cron expressions in clear plain English. [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2695
|
+
inputSchema: {
|
|
2696
|
+
type: "object",
|
|
2697
|
+
properties: {
|
|
2698
|
+
expression: {
|
|
2699
|
+
type: "string",
|
|
2700
|
+
description: "5-field cron expression, e.g. '*/15 9-17 * * 1-5'"
|
|
2701
|
+
}
|
|
2702
|
+
},
|
|
2703
|
+
required: ["expression"]
|
|
2704
|
+
}
|
|
2705
|
+
},
|
|
2706
|
+
{
|
|
2707
|
+
name: "codestation_timezone_convert",
|
|
2708
|
+
description: "Accurately convert a date/time string from one IANA timezone to another using runtime IANA rules. [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2709
|
+
inputSchema: {
|
|
2710
|
+
type: "object",
|
|
2711
|
+
properties: {
|
|
2712
|
+
dateTime: {
|
|
2713
|
+
type: "string",
|
|
2714
|
+
description: "ISO date-time string, e.g. '2026-10-09T14:30:00'"
|
|
2715
|
+
},
|
|
2716
|
+
sourceTimeZone: {
|
|
2717
|
+
type: "string",
|
|
2718
|
+
description: "Source IANA timezone (e.g. 'America/New_York', 'Asia/Kolkata', 'UTC')"
|
|
2719
|
+
},
|
|
2720
|
+
targetTimeZone: {
|
|
2721
|
+
type: "string",
|
|
2722
|
+
description: "Target IANA timezone (e.g. 'Asia/Kolkata', 'Europe/London', 'UTC')"
|
|
2723
|
+
}
|
|
2724
|
+
},
|
|
2725
|
+
required: ["dateTime", "sourceTimeZone", "targetTimeZone"]
|
|
2726
|
+
}
|
|
2727
|
+
},
|
|
2728
|
+
{
|
|
2729
|
+
name: "codestation_business_days",
|
|
2730
|
+
description: "Calculate exact working/business days between two dates, excluding weekends. [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2731
|
+
inputSchema: {
|
|
2732
|
+
type: "object",
|
|
2733
|
+
properties: {
|
|
2734
|
+
startDate: { type: "string", description: "Start date (YYYY-MM-DD)" },
|
|
2735
|
+
endDate: { type: "string", description: "End date (YYYY-MM-DD)" }
|
|
2736
|
+
},
|
|
2737
|
+
required: ["startDate", "endDate"]
|
|
2738
|
+
}
|
|
2739
|
+
},
|
|
2740
|
+
{
|
|
2741
|
+
name: "codestation_regex_test",
|
|
2742
|
+
description: "Test regular expressions against target text and return structured match groups and indices. [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2743
|
+
inputSchema: {
|
|
2744
|
+
type: "object",
|
|
2745
|
+
properties: {
|
|
2746
|
+
pattern: { type: "string", description: "Regex pattern (without bounding slashes)" },
|
|
2747
|
+
text: { type: "string", description: "Text to search within" },
|
|
2748
|
+
flags: {
|
|
2749
|
+
type: "string",
|
|
2750
|
+
description: "Regex flags (e.g. 'g', 'i', 'm', default: 'g')"
|
|
2751
|
+
}
|
|
2752
|
+
},
|
|
2753
|
+
required: ["pattern", "text"]
|
|
2754
|
+
}
|
|
2755
|
+
},
|
|
2756
|
+
{
|
|
2757
|
+
name: "codestation_json_schema",
|
|
2758
|
+
description: "Infer a Draft 2020-12 JSON Schema structure from sample JSON data. [Pro Tier: \u20B9199/mo or $2.99/mo]",
|
|
2759
|
+
inputSchema: {
|
|
2760
|
+
type: "object",
|
|
2761
|
+
properties: {
|
|
2762
|
+
json: { type: "string", description: "Sample JSON string" }
|
|
2763
|
+
},
|
|
2764
|
+
required: ["json"]
|
|
2765
|
+
}
|
|
2766
|
+
}
|
|
2767
|
+
];
|
|
2768
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
2769
|
+
return { tools };
|
|
2770
|
+
});
|
|
2771
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
2772
|
+
const { name: name2, arguments: args = {} } = request.params;
|
|
2773
|
+
if (PRO_TOOLS.has(name2) && !license.isPro) {
|
|
2774
|
+
return {
|
|
2775
|
+
content: [
|
|
2776
|
+
{
|
|
2777
|
+
type: "text",
|
|
2778
|
+
text: getProUpgradeNotice(name2)
|
|
2779
|
+
}
|
|
2780
|
+
],
|
|
2781
|
+
isError: true
|
|
2782
|
+
};
|
|
2783
|
+
}
|
|
2784
|
+
try {
|
|
2785
|
+
let outputText = "";
|
|
2786
|
+
switch (name2) {
|
|
2787
|
+
// --- Free tools ---
|
|
2788
|
+
case "codestation_uuid": {
|
|
2789
|
+
const count = Math.min(Math.max(Number(args.count ?? 1), 1), 50);
|
|
2790
|
+
const uuids = Array.from({ length: count }, () => crypto.randomUUID());
|
|
2791
|
+
outputText = count === 1 ? uuids[0] : uuids.join("\n");
|
|
2792
|
+
break;
|
|
2793
|
+
}
|
|
2794
|
+
case "codestation_base64": {
|
|
2795
|
+
const text3 = String(args.text ?? "");
|
|
2796
|
+
const action = String(args.action ?? "encode");
|
|
2797
|
+
const urlSafe = Boolean(args.urlSafe);
|
|
2798
|
+
if (action === "encode") {
|
|
2799
|
+
if (urlSafe) {
|
|
2800
|
+
outputText = encodeBase64Url(text3);
|
|
2801
|
+
} else {
|
|
2802
|
+
outputText = Buffer.from(text3, "utf-8").toString("base64");
|
|
2803
|
+
}
|
|
2804
|
+
} else {
|
|
2805
|
+
if (urlSafe) {
|
|
2806
|
+
outputText = decodeBase64Url(text3);
|
|
2807
|
+
} else {
|
|
2808
|
+
outputText = Buffer.from(text3, "base64").toString("utf-8");
|
|
2809
|
+
}
|
|
2810
|
+
}
|
|
2811
|
+
break;
|
|
2812
|
+
}
|
|
2813
|
+
case "codestation_url_codec": {
|
|
2814
|
+
const text3 = String(args.text ?? "");
|
|
2815
|
+
const action = String(args.action ?? "encode");
|
|
2816
|
+
outputText = action === "encode" ? encodeUrlComponent(text3) : decodeUrlComponent(text3);
|
|
2817
|
+
break;
|
|
2818
|
+
}
|
|
2819
|
+
case "codestation_hex_codec": {
|
|
2820
|
+
const text3 = String(args.text ?? "");
|
|
2821
|
+
const action = String(args.action ?? "encode");
|
|
2822
|
+
outputText = action === "encode" ? encodeHexadecimal(text3) : decodeHexadecimal(text3);
|
|
2823
|
+
break;
|
|
2824
|
+
}
|
|
2825
|
+
case "codestation_format_json": {
|
|
2826
|
+
const json = String(args.json ?? "");
|
|
2827
|
+
const indent = args.indent !== void 0 ? Number(args.indent) : 2;
|
|
2828
|
+
outputText = formatJson(json, indent);
|
|
2829
|
+
break;
|
|
2830
|
+
}
|
|
2831
|
+
case "codestation_minify_json": {
|
|
2832
|
+
outputText = minifyJson(String(args.json ?? ""));
|
|
2833
|
+
break;
|
|
2834
|
+
}
|
|
2835
|
+
case "codestation_json_to_yaml": {
|
|
2836
|
+
outputText = jsonToYaml(String(args.json ?? ""));
|
|
2837
|
+
break;
|
|
2838
|
+
}
|
|
2839
|
+
case "codestation_yaml_to_json": {
|
|
2840
|
+
outputText = yamlToJson(String(args.yaml ?? ""));
|
|
2841
|
+
break;
|
|
2842
|
+
}
|
|
2843
|
+
case "codestation_case_convert": {
|
|
2844
|
+
const text3 = String(args.text ?? "");
|
|
2845
|
+
const targetCase = String(args.targetCase ?? "camel");
|
|
2846
|
+
outputText = convertCase(text3, targetCase);
|
|
2847
|
+
break;
|
|
2848
|
+
}
|
|
2849
|
+
case "codestation_text_diff": {
|
|
2850
|
+
outputText = diffText(String(args.original ?? ""), String(args.modified ?? ""));
|
|
2851
|
+
break;
|
|
2852
|
+
}
|
|
2853
|
+
case "codestation_slugify": {
|
|
2854
|
+
outputText = slugify(String(args.text ?? ""), String(args.separator ?? "-"));
|
|
2855
|
+
break;
|
|
2856
|
+
}
|
|
2857
|
+
// --- Pro tools ---
|
|
2858
|
+
case "codestation_hash": {
|
|
2859
|
+
const text3 = String(args.text ?? "");
|
|
2860
|
+
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);
|
|
2867
|
+
else throw new Error(`Unsupported hash algorithm: ${algo}`);
|
|
2868
|
+
break;
|
|
2869
|
+
}
|
|
2870
|
+
case "codestation_hmac": {
|
|
2871
|
+
const text3 = String(args.text ?? "");
|
|
2872
|
+
const secret = String(args.secret ?? "");
|
|
2873
|
+
const algo = String(args.algorithm ?? "SHA-256").toUpperCase();
|
|
2874
|
+
if (algo === "SHA-512") {
|
|
2875
|
+
outputText = await hmacSha512(text3, secret);
|
|
2876
|
+
} else {
|
|
2877
|
+
outputText = await hmacSha256(text3, secret);
|
|
2878
|
+
}
|
|
2879
|
+
break;
|
|
2880
|
+
}
|
|
2881
|
+
case "codestation_jwt_decode": {
|
|
2882
|
+
outputText = decodeJwt(String(args.token ?? ""));
|
|
2883
|
+
break;
|
|
2884
|
+
}
|
|
2885
|
+
case "codestation_format_sql": {
|
|
2886
|
+
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 ?? "";
|
|
2890
|
+
break;
|
|
2891
|
+
}
|
|
2892
|
+
case "codestation_cron_explain": {
|
|
2893
|
+
const parsed = parseCron(String(args.expression ?? ""));
|
|
2894
|
+
outputText = explainCron(parsed);
|
|
2895
|
+
break;
|
|
2896
|
+
}
|
|
2897
|
+
case "codestation_timezone_convert": {
|
|
2898
|
+
const dateTime = String(args.dateTime ?? "");
|
|
2899
|
+
const sourceZone = String(args.sourceTimeZone ?? "UTC");
|
|
2900
|
+
const targetZone = String(args.targetTimeZone ?? "UTC");
|
|
2901
|
+
outputText = convertBetweenTimeZones(dateTime, sourceZone, targetZone);
|
|
2902
|
+
break;
|
|
2903
|
+
}
|
|
2904
|
+
case "codestation_business_days": {
|
|
2905
|
+
const start = String(args.startDate ?? "");
|
|
2906
|
+
const end = String(args.endDate ?? "");
|
|
2907
|
+
const days = businessDaysBetween(start, end);
|
|
2908
|
+
outputText = `${days} business day${days === 1 ? "" : "s"}`;
|
|
2909
|
+
break;
|
|
2910
|
+
}
|
|
2911
|
+
case "codestation_regex_test": {
|
|
2912
|
+
const pattern = String(args.pattern ?? "");
|
|
2913
|
+
const text3 = String(args.text ?? "");
|
|
2914
|
+
const flags = String(args.flags ?? "g");
|
|
2915
|
+
outputText = testRegex(pattern, flags, text3);
|
|
2916
|
+
break;
|
|
2917
|
+
}
|
|
2918
|
+
case "codestation_json_schema": {
|
|
2919
|
+
outputText = generateJsonSchema(String(args.json ?? ""));
|
|
2920
|
+
break;
|
|
2921
|
+
}
|
|
2922
|
+
default:
|
|
2923
|
+
throw new Error(`Unknown tool: ${name2}`);
|
|
2924
|
+
}
|
|
2925
|
+
return {
|
|
2926
|
+
content: [{ type: "text", text: outputText }]
|
|
2927
|
+
};
|
|
2928
|
+
} catch (err) {
|
|
2929
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2930
|
+
return {
|
|
2931
|
+
content: [{ type: "text", text: `Error: ${message}` }],
|
|
2932
|
+
isError: true
|
|
2933
|
+
};
|
|
2934
|
+
}
|
|
2935
|
+
});
|
|
2936
|
+
return { server, license };
|
|
2937
|
+
}
|
|
2938
|
+
|
|
2939
|
+
// mcp/cli.ts
|
|
2940
|
+
function printHelp() {
|
|
2941
|
+
process.stderr.write(`
|
|
2942
|
+
Code Station MCP Server
|
|
2943
|
+
Local-first developer toolbox for AI assistants (Cursor, Claude Desktop, Antigravity)
|
|
2944
|
+
|
|
2945
|
+
Usage:
|
|
2946
|
+
npx codestation-mcp [options]
|
|
2947
|
+
|
|
2948
|
+
Options:
|
|
2949
|
+
--key <license_key> Activate Code Station Pro features
|
|
2950
|
+
--help, -h Show this help message
|
|
2951
|
+
--version, -v Show version information
|
|
2952
|
+
|
|
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}
|
|
2958
|
+
|
|
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
|
+
}
|
|
2968
|
+
|
|
2969
|
+
`);
|
|
2970
|
+
}
|
|
2971
|
+
async function main() {
|
|
2972
|
+
const args = process.argv.slice(2);
|
|
2973
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
2974
|
+
printHelp();
|
|
2975
|
+
process.exit(0);
|
|
2976
|
+
}
|
|
2977
|
+
if (args.includes("--version") || args.includes("-v")) {
|
|
2978
|
+
process.stderr.write("codestation-mcp v1.0.0\n");
|
|
2979
|
+
process.exit(0);
|
|
2980
|
+
}
|
|
2981
|
+
let cliKey;
|
|
2982
|
+
const keyIndex = args.indexOf("--key");
|
|
2983
|
+
if (keyIndex !== -1 && args[keyIndex + 1]) {
|
|
2984
|
+
cliKey = args[keyIndex + 1];
|
|
2985
|
+
}
|
|
2986
|
+
const { server, license } = createMcpServer(cliKey);
|
|
2987
|
+
if (license.isPro) {
|
|
2988
|
+
process.stderr.write(`[Code Station MCP] Pro Tier Active (License: ${license.licenseKey?.slice(0, 8)}...). All tools unlocked.
|
|
2989
|
+
`);
|
|
2990
|
+
} else {
|
|
2991
|
+
process.stderr.write(
|
|
2992
|
+
`[Code Station MCP] Running in Free Tier. Pro tools available at ${PRICING.inr} / ${PRICING.usd} (${PRICING.upgradeUrl})
|
|
2993
|
+
`
|
|
2994
|
+
);
|
|
2995
|
+
}
|
|
2996
|
+
const transport = new StdioServerTransport();
|
|
2997
|
+
await server.connect(transport);
|
|
2998
|
+
process.stderr.write("[Code Station MCP] Connected to stdio. Ready for tool requests.\n");
|
|
2999
|
+
}
|
|
3000
|
+
main().catch((err) => {
|
|
3001
|
+
process.stderr.write(`[Code Station MCP Error] ${err instanceof Error ? err.stack : String(err)}
|
|
3002
|
+
`);
|
|
3003
|
+
process.exit(1);
|
|
3004
|
+
});
|