@cetra-ai/cli 0.0.0-stage → 0.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.
Files changed (41) hide show
  1. package/LICENSE +48 -0
  2. package/README.md +14 -2
  3. package/dist/cli.js +2816 -0
  4. package/dist/skills/cetra/SKILL.md +95 -0
  5. package/dist/skills/cetra/references/anthropic.md +82 -0
  6. package/dist/skills/cetra/references/attributes.md +178 -0
  7. package/dist/skills/cetra/references/bedrock.md +46 -0
  8. package/dist/skills/cetra/references/crewai.md +38 -0
  9. package/dist/skills/cetra/references/dspy.md +38 -0
  10. package/dist/skills/cetra/references/from-laminar.md +49 -0
  11. package/dist/skills/cetra/references/from-langfuse.md +59 -0
  12. package/dist/skills/cetra/references/google-adk.md +60 -0
  13. package/dist/skills/cetra/references/google-genai.md +50 -0
  14. package/dist/skills/cetra/references/integrations.md +71 -0
  15. package/dist/skills/cetra/references/langchain.md +76 -0
  16. package/dist/skills/cetra/references/litellm.md +45 -0
  17. package/dist/skills/cetra/references/llama-index.md +38 -0
  18. package/dist/skills/cetra/references/metadata-and-tags.md +117 -0
  19. package/dist/skills/cetra/references/openai-agents.md +55 -0
  20. package/dist/skills/cetra/references/openai.md +82 -0
  21. package/dist/skills/cetra/references/openinference.md +51 -0
  22. package/dist/skills/cetra/references/openllmetry.md +42 -0
  23. package/dist/skills/cetra/references/opentelemetry-genai.md +49 -0
  24. package/dist/skills/cetra/references/opentelemetry.md +134 -0
  25. package/dist/skills/cetra/references/otlp.md +73 -0
  26. package/dist/skills/cetra/references/privacy-controls.md +120 -0
  27. package/dist/skills/cetra/references/python-context.md +63 -0
  28. package/dist/skills/cetra/references/python-opentelemetry.md +136 -0
  29. package/dist/skills/cetra/references/python-tracing.md +77 -0
  30. package/dist/skills/cetra/references/python.md +79 -0
  31. package/dist/skills/cetra/references/sessions.md +84 -0
  32. package/dist/skills/cetra/references/sql-schema.md +210 -0
  33. package/dist/skills/cetra/references/troubleshooting.md +90 -0
  34. package/dist/skills/cetra/references/typescript-context.md +22 -0
  35. package/dist/skills/cetra/references/typescript-opentelemetry.md +68 -0
  36. package/dist/skills/cetra/references/typescript-runtimes.md +54 -0
  37. package/dist/skills/cetra/references/typescript-tracing.md +40 -0
  38. package/dist/skills/cetra/references/typescript.md +56 -0
  39. package/dist/skills/cetra/references/users.md +87 -0
  40. package/dist/skills/cetra/references/vercel-ai-sdk.md +82 -0
  41. package/package.json +39 -4
package/dist/cli.js ADDED
@@ -0,0 +1,2816 @@
1
+ #!/usr/bin/env node
2
+ import { closeSync, openSync, realpathSync } from "node:fs";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { access, appendFile, chmod, cp, mkdir, open, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
5
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
6
+ import { parseArgs, promisify } from "node:util";
7
+ import { homedir, hostname } from "node:os";
8
+ import { execFile, spawn } from "node:child_process";
9
+ import { randomBytes, randomInt } from "node:crypto";
10
+ import { createInterface } from "node:readline/promises";
11
+ // src/errors.ts
12
+ /** Exit codes (design § `@cetra-ai/cli`, D-AO-15). */
13
+ const Exit = {
14
+ Ok: 0,
15
+ Error: 1,
16
+ Usage: 2,
17
+ Unreachable: 3,
18
+ SignIn: 4,
19
+ Write: 5,
20
+ Query: 6
21
+ };
22
+ /** An error that ends the command with a message on stderr and an exit code. */
23
+ var CliError = class extends Error {
24
+ code;
25
+ constructor(message, code = Exit.Error) {
26
+ super(message);
27
+ this.code = code;
28
+ this.name = "CliError";
29
+ }
30
+ };
31
+ /** The real Io: process.stdout / process.stderr with "\n" added, process.env, process.cwd(). A reader
32
+ * that stops early (`cetra-cli query ... | head`) ends the command with 0, as the Rust CLI does. */
33
+ function realIo() {
34
+ process.stdout.once("error", (error) => {
35
+ if (error.code === "EPIPE") process.exit(Exit.Ok);
36
+ throw error;
37
+ });
38
+ return {
39
+ stdout: (line) => {
40
+ process.stdout.write(`${line}\n`);
41
+ },
42
+ stderr: (line) => {
43
+ process.stderr.write(`${line}\n`);
44
+ },
45
+ env: process.env,
46
+ cwd: process.cwd()
47
+ };
48
+ }
49
+ /** Characters to strip or refuse: one place, so Biome's noControlCharactersInRegex is never hit. */
50
+ const CONTROL = /\p{Cc}/gu;
51
+ // src/args.ts
52
+ /** parseArgs with `strict: true` and positionals allowed; any parse error becomes
53
+ * CliError(<its message>, Exit.Usage). A command that takes no positional checks
54
+ * `positionals.length === 0` itself. */
55
+ function parseOptions(args, options) {
56
+ try {
57
+ return parseArgs({
58
+ args,
59
+ options,
60
+ strict: true,
61
+ allowPositionals: true
62
+ });
63
+ } catch (error) {
64
+ throw new CliError(error instanceof Error ? error.message : String(error), Exit.Usage);
65
+ }
66
+ }
67
+ /** The options list of a command, one line per option, for `--help`. */
68
+ function optionsHelp(command, summary, lines) {
69
+ const width = Math.max(...lines.map(([flag]) => flag.length));
70
+ const rows = lines.map(([flag, text]) => ` ${flag.padEnd(width)} ${text}`);
71
+ return [
72
+ `Usage: cetra-cli ${command} [options]`,
73
+ "",
74
+ summary,
75
+ "",
76
+ "Options:",
77
+ ...rows
78
+ ].join("\n");
79
+ }
80
+ // ../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/error.js
81
+ /*!
82
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
83
+ * SPDX-License-Identifier: BSD-3-Clause
84
+ *
85
+ * Redistribution and use in source and binary forms, with or without
86
+ * modification, are permitted provided that the following conditions are met:
87
+ *
88
+ * 1. Redistributions of source code must retain the above copyright notice, this
89
+ * list of conditions and the following disclaimer.
90
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
91
+ * this list of conditions and the following disclaimer in the
92
+ * documentation and/or other materials provided with the distribution.
93
+ * 3. Neither the name of the copyright holder nor the names of its contributors
94
+ * may be used to endorse or promote products derived from this software without
95
+ * specific prior written permission.
96
+ *
97
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
98
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
99
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
100
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
101
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
102
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
103
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
104
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
105
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
106
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
107
+ */
108
+ function getLineColFromPtr(string, ptr) {
109
+ let lines = string.slice(0, ptr).split(/\r?\n/);
110
+ return [lines.length, lines.pop().length + 1];
111
+ }
112
+ function makeCodeBlock(string, line, column) {
113
+ let lines = string.split(/\r?\n/);
114
+ let codeblock = "";
115
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
116
+ for (let i = line - 1; i <= line + 1; i++) {
117
+ let l = lines[i - 1];
118
+ if (!l) continue;
119
+ codeblock += i.toString().padEnd(numberLen, " ");
120
+ codeblock += ": ";
121
+ codeblock += l;
122
+ codeblock += "\n";
123
+ if (i === line) {
124
+ codeblock += " ".repeat(numberLen + column + 2);
125
+ codeblock += "^\n";
126
+ }
127
+ }
128
+ return codeblock;
129
+ }
130
+ var TomlError = class TomlError extends Error {
131
+ line;
132
+ column;
133
+ codeblock;
134
+ constructor(message, options) {
135
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
136
+ const codeblock = makeCodeBlock(options.toml, line, column);
137
+ super(`Invalid TOML document: ${message}\n\n${codeblock}`, options);
138
+ this.line = line;
139
+ this.column = column;
140
+ this.codeblock = codeblock;
141
+ }
142
+ /** @internal */
143
+ static x(message, ctx, ptr) {
144
+ throw new TomlError(message, {
145
+ toml: ctx.s,
146
+ ptr: ptr ?? ctx.p
147
+ });
148
+ }
149
+ };
150
+ // ../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/primitive.js
151
+ /*!
152
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
153
+ * SPDX-License-Identifier: BSD-3-Clause
154
+ *
155
+ * Redistribution and use in source and binary forms, with or without
156
+ * modification, are permitted provided that the following conditions are met:
157
+ *
158
+ * 1. Redistributions of source code must retain the above copyright notice, this
159
+ * list of conditions and the following disclaimer.
160
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
161
+ * this list of conditions and the following disclaimer in the
162
+ * documentation and/or other materials provided with the distribution.
163
+ * 3. Neither the name of the copyright holder nor the names of its contributors
164
+ * may be used to endorse or promote products derived from this software without
165
+ * specific prior written permission.
166
+ *
167
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
168
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
169
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
170
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
171
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
172
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
173
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
174
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
175
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
176
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
177
+ */
178
+ /** @internal */
179
+ function parseString(ctx) {
180
+ let startPtr = ctx.p;
181
+ let c = ctx.s.charCodeAt(ctx.p++);
182
+ let first = c;
183
+ let isLiteral = c === 39;
184
+ let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
185
+ if (isMultiline) {
186
+ if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10) ctx.p++;
187
+ else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) ctx.p += 2;
188
+ }
189
+ let parsed = "";
190
+ let sliceStart = ctx.p;
191
+ let state = 0;
192
+ for (; ctx.p < ctx.s.length; ctx.p++) {
193
+ c = ctx.s.charCodeAt(ctx.p);
194
+ if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) state = state && 3;
195
+ else if (c < 32 && c !== 9 || c === 127) TomlError.x("control characters are not allowed in strings", ctx);
196
+ else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
197
+ if (isMultiline) {
198
+ if (ctx.s.charCodeAt(ctx.p + 3) === first) ctx.p++;
199
+ if (ctx.s.charCodeAt(ctx.p + 3) === first) ctx.p++;
200
+ }
201
+ if (!state) {
202
+ let s = ctx.s.slice(sliceStart, ctx.p);
203
+ parsed = parsed ? parsed + s : s;
204
+ }
205
+ ctx.p += isMultiline ? 3 : 1;
206
+ return parsed;
207
+ } else if (!state) {
208
+ if (!isLiteral && c === 92) {
209
+ parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
210
+ state = 1;
211
+ }
212
+ } else if (state === 1) {
213
+ if (c === 120 || c === 117 || c === 85) {
214
+ let errPtr = ctx.p++ - 1;
215
+ let value = 0;
216
+ let len = c === 120 ? 2 : c === 117 ? 4 : 8;
217
+ for (let j = 0; j < len; j++, ctx.p++) {
218
+ let hex = ctx.s.charCodeAt(ctx.p);
219
+ let digit = hex >= 48 && hex <= 57 ? hex - 48 : hex >= 65 && hex <= 70 ? hex - 65 + 10 : hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1;
220
+ if (digit < 0) TomlError.x("invalid non-hex character in unicode escape", ctx);
221
+ value = value << 4 | digit;
222
+ }
223
+ if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) TomlError.x("invalid unicode escape", ctx, errPtr);
224
+ parsed += String.fromCodePoint(value);
225
+ sliceStart = ctx.p--;
226
+ state = 0;
227
+ } else if (isMultiline && (c === 32 || c === 9)) state = 2;
228
+ else {
229
+ if (c === 98) parsed += "\b";
230
+ else if (c === 116) parsed += " ";
231
+ else if (c === 110) parsed += "\n";
232
+ else if (c === 102) parsed += "\f";
233
+ else if (c === 114) parsed += "\r";
234
+ else if (c === 101) parsed += "\x1B";
235
+ else if (c === 34) parsed += "\"";
236
+ else if (c === 92) parsed += "\\";
237
+ else TomlError.x("unrecognised escape sequence", ctx);
238
+ sliceStart = ctx.p + 1;
239
+ state = 0;
240
+ }
241
+ } else if (c !== 32 && c !== 9) {
242
+ if (state === 2) TomlError.x("invalid escape: only line-ending whitespace may be escaped", ctx, sliceStart);
243
+ state = !isLiteral && c === 92 ? 1 : 0;
244
+ sliceStart = ctx.p;
245
+ }
246
+ }
247
+ TomlError.x("unfinished string", ctx, startPtr);
248
+ }
249
+ // ../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/date.js
250
+ /*!
251
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
252
+ * SPDX-License-Identifier: BSD-3-Clause
253
+ *
254
+ * Redistribution and use in source and binary forms, with or without
255
+ * modification, are permitted provided that the following conditions are met:
256
+ *
257
+ * 1. Redistributions of source code must retain the above copyright notice, this
258
+ * list of conditions and the following disclaimer.
259
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
260
+ * this list of conditions and the following disclaimer in the
261
+ * documentation and/or other materials provided with the distribution.
262
+ * 3. Neither the name of the copyright holder nor the names of its contributors
263
+ * may be used to endorse or promote products derived from this software without
264
+ * specific prior written permission.
265
+ *
266
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
267
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
268
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
269
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
270
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
271
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
272
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
273
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
274
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
275
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
276
+ */
277
+ let DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;
278
+ var TomlDate = class TomlDate extends Date {
279
+ #hasDate = false;
280
+ #hasTime = false;
281
+ #offset = null;
282
+ constructor(date, fasttype, unsafeDelim) {
283
+ let hasDate = true;
284
+ let hasTime = true;
285
+ let offset = "Z";
286
+ let c;
287
+ if (typeof date === "string") {
288
+ if (fasttype) prep: {
289
+ if (fasttype < 3) {
290
+ if (+date.slice(11, 13) > 23) {
291
+ date = "";
292
+ break prep;
293
+ }
294
+ if (fasttype === 2) {
295
+ offset = null;
296
+ date += "Z";
297
+ } else if ((c = date.charCodeAt(date.length - 1)) !== 90 && c !== 122) offset = date.slice(date.length - 6);
298
+ if (unsafeDelim) date = date.slice(0, 10) + "T" + date.slice(11);
299
+ } else if (fasttype === 4) date = +date.slice(0, 2) > 23 ? "" : `0000-01-01T${date}Z`;
300
+ hasDate = fasttype !== 4;
301
+ hasTime = fasttype !== 3;
302
+ }
303
+ else {
304
+ let match = date.match(DATE_TIME_RE);
305
+ if (match) {
306
+ if (!match[1]) {
307
+ hasDate = false;
308
+ date = `0000-01-01T${date}`;
309
+ }
310
+ hasTime = !!match[2];
311
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
312
+ if (match[2] && +match[2] > 23) date = "";
313
+ else {
314
+ offset = match[3] || null;
315
+ if (!offset && hasTime) date += "Z";
316
+ }
317
+ } else date = "";
318
+ }
319
+ }
320
+ super(date);
321
+ if (!isNaN(this.getTime())) {
322
+ this.#hasDate = hasDate;
323
+ this.#hasTime = hasTime;
324
+ this.#offset = offset;
325
+ }
326
+ }
327
+ isDateTime() {
328
+ return this.#hasDate && this.#hasTime;
329
+ }
330
+ isLocal() {
331
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
332
+ }
333
+ isDate() {
334
+ return this.#hasDate && !this.#hasTime;
335
+ }
336
+ isTime() {
337
+ return this.#hasTime && !this.#hasDate;
338
+ }
339
+ isValid() {
340
+ return this.#hasDate || this.#hasTime;
341
+ }
342
+ toISOString() {
343
+ let iso = super.toISOString();
344
+ if (this.isDate()) return iso.slice(0, 10);
345
+ if (this.isTime()) return iso.slice(11, 23);
346
+ if (this.#offset === null) return iso.slice(0, -1);
347
+ if (this.#offset === "Z" || this.#offset === "z") return iso;
348
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
349
+ offset = this.#offset[0] === "-" ? offset : -offset;
350
+ return (/* @__PURE__ */ new Date(this.getTime() - offset * 6e4)).toISOString().slice(0, -1) + this.#offset;
351
+ }
352
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
353
+ let date = new TomlDate(jsDate);
354
+ date.#offset = offset;
355
+ return date;
356
+ }
357
+ static wrapAsLocalDateTime(jsDate) {
358
+ let date = new TomlDate(jsDate);
359
+ date.#offset = null;
360
+ return date;
361
+ }
362
+ static wrapAsLocalDate(jsDate) {
363
+ let date = new TomlDate(jsDate);
364
+ date.#hasTime = false;
365
+ date.#offset = null;
366
+ return date;
367
+ }
368
+ static wrapAsLocalTime(jsDate) {
369
+ let date = new TomlDate(jsDate);
370
+ date.#hasDate = false;
371
+ date.#offset = null;
372
+ return date;
373
+ }
374
+ };
375
+ // ../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/extract.js
376
+ /*!
377
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
378
+ * SPDX-License-Identifier: BSD-3-Clause
379
+ *
380
+ * Redistribution and use in source and binary forms, with or without
381
+ * modification, are permitted provided that the following conditions are met:
382
+ *
383
+ * 1. Redistributions of source code must retain the above copyright notice, this
384
+ * list of conditions and the following disclaimer.
385
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
386
+ * this list of conditions and the following disclaimer in the
387
+ * documentation and/or other materials provided with the distribution.
388
+ * 3. Neither the name of the copyright holder nor the names of its contributors
389
+ * may be used to endorse or promote products derived from this software without
390
+ * specific prior written permission.
391
+ *
392
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
393
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
394
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
395
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
396
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
397
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
398
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
399
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
400
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
401
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
402
+ */
403
+ function isDigit(char, base = 10) {
404
+ return base === 16 ? char > 47 && char < 58 || char > 64 && char < 71 || char > 96 && char < 103 : char > 47 && char < 48 + base;
405
+ }
406
+ function isEndOfValue(char, delim) {
407
+ return char === 32 || char === 9 || char === 10 || char === 13 || delim && (char === delim || char === 44) || char === 35;
408
+ }
409
+ /** @internal */
410
+ function extractValue(ctx, end) {
411
+ let errPtr = ctx.p;
412
+ let c = ctx.s.charCodeAt(ctx.p);
413
+ if (c === 91 || c === 123) {
414
+ ctx.d-- || TomlError.x("document contains excessively nested structures. aborting.", ctx);
415
+ let value = c === 91 ? parseArray(ctx) : parseInlineTable(ctx);
416
+ ctx.d++;
417
+ return value;
418
+ }
419
+ if (c === 34 || c === 39) return parseString(ctx);
420
+ if (c === 116) {
421
+ if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101) TomlError.x("invalid value", ctx, errPtr);
422
+ return ctx.p++, true;
423
+ }
424
+ if (c === 102) {
425
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 108 || ctx.s.charCodeAt(++ctx.p) !== 115 || ctx.s.charCodeAt(++ctx.p) !== 101) TomlError.x("invalid value", ctx, errPtr);
426
+ return ctx.p++, false;
427
+ }
428
+ if (c === 43 || c === 45) return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 44 - c, end);
429
+ if (ctx.s.charCodeAt(ctx.p + 4) === 45 && ctx.s.charCodeAt(ctx.p + 7) === 45) return parseDate(ctx, c, end);
430
+ if (ctx.s.charCodeAt(ctx.p + 2) === 58) return parseTime(ctx, c, end);
431
+ return parseNumber(ctx, ctx.p, c, 0, end);
432
+ }
433
+ function parseNumber(ctx, startPtr, startChr, sign, endChr) {
434
+ let c = startChr;
435
+ let state = 0;
436
+ let hasUnderscores = false;
437
+ if (c === 105) {
438
+ if (ctx.s.charCodeAt(++ctx.p) !== 110 || ctx.s.charCodeAt(++ctx.p) !== 102) TomlError.x("invalid value", ctx, startPtr);
439
+ return ctx.p++, (sign || 1) / 0;
440
+ }
441
+ if (c === 110) {
442
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 110) TomlError.x("invalid value", ctx, startPtr);
443
+ return ctx.p++, NaN;
444
+ }
445
+ if (c === 48) {
446
+ if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr)) return ctx.bi === true ? 0n : 0;
447
+ if (!sign) {
448
+ if (c === 120) return parseIntegerBaseN(ctx, startPtr, 16, endChr);
449
+ else if (c === 98) return parseIntegerBaseN(ctx, startPtr, 2, endChr);
450
+ else if (c === 111) return parseIntegerBaseN(ctx, startPtr, 8, endChr);
451
+ }
452
+ if (c === 46) state = 2;
453
+ else if (c === 101 || c === 69) state = 4;
454
+ else TomlError.x("illegal leading zero", ctx, startPtr);
455
+ } else if (!isDigit(c)) TomlError.x("invalid value", ctx, startPtr);
456
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
457
+ if (!state) state = 1;
458
+ if (c === 95) {
459
+ if (!(state & 1)) TomlError.x("illegal underscore", ctx);
460
+ state += 11;
461
+ hasUnderscores = true;
462
+ } else if (state === 1 && c === 46) state = 2;
463
+ else if ((state === 1 || state === 3) && (c === 101 || c === 69)) state = 4;
464
+ else if (state === 4 && (c === 43 || c === 45)) state = 6;
465
+ else if (!isDigit(c)) TomlError.x(`illegal character in numeric literal`, ctx);
466
+ else if (state > 9) state -= 11;
467
+ else if (!(state & 1)) state++;
468
+ }
469
+ if (!state) {
470
+ let val = (startChr - 48) * (sign || 1);
471
+ return ctx.bi === true ? BigInt(val) : val;
472
+ }
473
+ if (!(state & 1)) TomlError.x("unfinished numeric value", ctx, startPtr);
474
+ let str = ctx.s.slice(startPtr, ctx.p);
475
+ if (hasUnderscores) str = str.replaceAll("_", "");
476
+ return state > 1 ? parseFloat(str) : parseInteger(ctx, str, 10, startPtr);
477
+ }
478
+ function parseIntegerBaseN(ctx, startPtr, base, endChr) {
479
+ let c, underscore = 1;
480
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) if (c === 95) {
481
+ if (underscore & 1) TomlError.x("illegal underscore", ctx);
482
+ underscore = 3;
483
+ } else if (!isDigit(c, base)) TomlError.x(`illegal character in numeric literal`, ctx);
484
+ else if (underscore & 1) underscore--;
485
+ if (underscore & 1) TomlError.x("unfinished numeric value", ctx);
486
+ let str = ctx.s.slice(startPtr + 2, ctx.p);
487
+ if (underscore) str = str.replaceAll("_", "");
488
+ return parseInteger(ctx, str, base, startPtr);
489
+ }
490
+ function parseInteger(ctx, str, base, startPtr) {
491
+ if (ctx.bi !== true) int: {
492
+ let val = parseInt(str, base);
493
+ if (!Number.isSafeInteger(val)) {
494
+ if (ctx.bi) break int;
495
+ TomlError.x("integer value cannot be represented losslessly", ctx, startPtr);
496
+ }
497
+ return val;
498
+ }
499
+ return base === 10 ? BigInt(str) : BigInt((base === 2 ? "0b" : base === 8 ? "0o" : "0x") + str);
500
+ }
501
+ function parseDate(ctx, c, endChr) {
502
+ let startPtr = ctx.p++, unsafeSeparator;
503
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++))) return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
504
+ ctx.p += 5;
505
+ if (!isDigit(ctx.s.charCodeAt(ctx.p++))) TomlError.x("invalid date-time: date part is malformed", ctx, startPtr);
506
+ if (ctx.p >= ctx.s.length || ((c = ctx.s.charCodeAt(ctx.p)) !== 32 || (unsafeSeparator = true, !isDigit(ctx.s.charCodeAt(ctx.p + 1)))) && c !== 84 && c !== 116) return readDate(ctx, ctx.s.slice(startPtr, ctx.p), 3, false, startPtr);
507
+ if (ctx.s.charCodeAt(ctx.p += 3) !== 58) TomlError.x("invalid date-time: time part is malformed", ctx, startPtr);
508
+ if (ctx.s.charCodeAt(ctx.p += 3) === 58) ctx.p += 3;
509
+ if (ctx.s.charCodeAt(ctx.p) === 46) while (isDigit(ctx.s.charCodeAt(++ctx.p)));
510
+ if (c = ctx.s.charCodeAt(ctx.p)) {
511
+ if (c === 90 || c === 122) return readDate(ctx, ctx.s.slice(startPtr, ++ctx.p), 1, unsafeSeparator, startPtr, "[+00:00]");
512
+ if (c === 43 || c === 45) return readDate(ctx, ctx.s.slice(startPtr, ctx.p += 6), 1, unsafeSeparator, startPtr, !ctx.ld && "[" + ctx.s.slice(ctx.p - 6, ctx.p) + "]");
513
+ }
514
+ return readDate(ctx, ctx.s.slice(startPtr, ctx.p), 2, unsafeSeparator, startPtr);
515
+ }
516
+ function parseTime(ctx, c, endChr) {
517
+ let start = ctx.p;
518
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) return parseNumber(ctx, --ctx.p, c, 0, endChr);
519
+ if (ctx.s.charCodeAt(ctx.p += 4) === 58) ctx.p += 3;
520
+ if (ctx.s.charCodeAt(ctx.p) === 46) while (isDigit(ctx.s.charCodeAt(++ctx.p)));
521
+ return readDate(ctx, ctx.s.slice(start, ctx.p), 4, false, start);
522
+ }
523
+ function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
524
+ if (ctx.ld) {
525
+ let date = new TomlDate(str, type, unsafeDelim);
526
+ if (!date.isValid()) TomlError.x("invalid date", ctx, errPtr);
527
+ return date;
528
+ }
529
+ try {
530
+ if (temporalSuffix) str += temporalSuffix;
531
+ switch (type) {
532
+ case 1: return Temporal.ZonedDateTime.from(str);
533
+ case 2: return Temporal.PlainDateTime.from(str);
534
+ case 3: return Temporal.PlainDate.from(str);
535
+ case 4: return Temporal.PlainTime.from(str);
536
+ }
537
+ } catch (e) {
538
+ TomlError.x(e instanceof Error ? e.message : "" + e, ctx, errPtr);
539
+ }
540
+ }
541
+ // ../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/util.js
542
+ /*!
543
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
544
+ * SPDX-License-Identifier: BSD-3-Clause
545
+ *
546
+ * Redistribution and use in source and binary forms, with or without
547
+ * modification, are permitted provided that the following conditions are met:
548
+ *
549
+ * 1. Redistributions of source code must retain the above copyright notice, this
550
+ * list of conditions and the following disclaimer.
551
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
552
+ * this list of conditions and the following disclaimer in the
553
+ * documentation and/or other materials provided with the distribution.
554
+ * 3. Neither the name of the copyright holder nor the names of its contributors
555
+ * may be used to endorse or promote products derived from this software without
556
+ * specific prior written permission.
557
+ *
558
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
559
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
560
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
561
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
562
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
563
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
564
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
565
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
566
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
567
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
568
+ */
569
+ /** @internal */
570
+ function skipComment(ctx) {
571
+ for (; ctx.p < ctx.s.length; ctx.p++) {
572
+ let c = ctx.s.charCodeAt(ctx.p);
573
+ if (c === 10) break;
574
+ if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
575
+ ctx.p++;
576
+ break;
577
+ }
578
+ if (c < 32 && c !== 9 || c === 127) TomlError.x("control characters are not allowed in comments", ctx);
579
+ }
580
+ }
581
+ /** @internal */
582
+ function skipVoid(ctx, banNewLines, banComments) {
583
+ let c;
584
+ while (ctx.p < ctx.s.length) {
585
+ while (ctx.p < ctx.s.length && ((c = ctx.s.charCodeAt(ctx.p)) === 32 || c === 9 || !banNewLines && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10))) ctx.p++;
586
+ if (banComments || c !== 35) break;
587
+ skipComment(ctx);
588
+ }
589
+ }
590
+ // ../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/struct.js
591
+ /*!
592
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
593
+ * SPDX-License-Identifier: BSD-3-Clause
594
+ *
595
+ * Redistribution and use in source and binary forms, with or without
596
+ * modification, are permitted provided that the following conditions are met:
597
+ *
598
+ * 1. Redistributions of source code must retain the above copyright notice, this
599
+ * list of conditions and the following disclaimer.
600
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
601
+ * this list of conditions and the following disclaimer in the
602
+ * documentation and/or other materials provided with the distribution.
603
+ * 3. Neither the name of the copyright holder nor the names of its contributors
604
+ * may be used to endorse or promote products derived from this software without
605
+ * specific prior written permission.
606
+ *
607
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
608
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
609
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
610
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
611
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
612
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
613
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
614
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
615
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
616
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
617
+ */
618
+ /** @internal */
619
+ function parseKey(ctx, end = 61) {
620
+ let startPtr;
621
+ let state = 0;
622
+ let parsed = [];
623
+ let sliceStart;
624
+ let c = ctx.s.charCodeAt(startPtr = ctx.p);
625
+ do
626
+ if (c === end) {
627
+ if (!state) TomlError.x("unexpected end of key", ctx);
628
+ if (state === 1) parsed.push(ctx.s.slice(sliceStart, ctx.p));
629
+ return ctx.p++, parsed;
630
+ } else if (c === 46) {
631
+ if (!state) TomlError.x("illegal empty bare key", ctx);
632
+ if (state === 1) parsed.push(ctx.s.slice(sliceStart, ctx.p));
633
+ state = 0;
634
+ } else if (!state && (c === 34 || c === 39)) {
635
+ if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2)) TomlError.x("illegal quoted key: multiline strings are not allowed", ctx);
636
+ parsed.push(parseString(ctx));
637
+ state = 2;
638
+ ctx.p--;
639
+ } else if (c === 32 || c === 9) {
640
+ if (state === 1) {
641
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
642
+ state = 2;
643
+ }
644
+ } else if (state === 2 || c < 48 && c !== 45 || c > 57 && c < 65 || c > 90 && c < 97 && c !== 95 || c > 122) TomlError.x("illegal character in key", ctx);
645
+ else if (!state) {
646
+ state = 1;
647
+ sliceStart = ctx.p;
648
+ }
649
+ while (c = ctx.s.charCodeAt(++ctx.p));
650
+ TomlError.x("incomplete key-value: cannot find end of key", ctx, startPtr);
651
+ }
652
+ /** @internal */
653
+ function parseInlineTable(ctx) {
654
+ let startPtr = ctx.p++;
655
+ let res = Object.create(null);
656
+ let seen = /* @__PURE__ */ new Set();
657
+ let c;
658
+ while (ctx.p < ctx.s.length) {
659
+ skipVoid(ctx);
660
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
661
+ ctx.p++;
662
+ return res;
663
+ }
664
+ let k;
665
+ let t = res;
666
+ let hasOwn = false;
667
+ let errPtr = ctx.p;
668
+ let key = parseKey(ctx);
669
+ for (let i = 0; i < key.length; i++) {
670
+ if (i) t = hasOwn ? t[k] : t[k] = Object.create(null);
671
+ k = key[i];
672
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) TomlError.x("trying to redefine an already defined value", ctx, errPtr);
673
+ let unsafe = k === "__proto__";
674
+ if (ctx.uk && (unsafe || k === "constructor")) {
675
+ t = ctx.uk !== 1 && TomlError.x("document contains an unsafe property", ctx, errPtr);
676
+ break;
677
+ }
678
+ if (!hasOwn && unsafe) Object.defineProperty(t, k, {
679
+ enumerable: true,
680
+ configurable: true,
681
+ writable: true
682
+ });
683
+ }
684
+ if (hasOwn) TomlError.x("trying to redefine an already defined value", ctx, errPtr);
685
+ skipVoid(ctx, true, true);
686
+ let value = extractValue(ctx, 125);
687
+ if (t && typeof (t[k] = value) === "object") seen.add(value);
688
+ skipVoid(ctx);
689
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) return res;
690
+ if (c !== 44) TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
691
+ }
692
+ TomlError.x("unfinished table", ctx, startPtr);
693
+ }
694
+ /** @internal */
695
+ function parseArray(ctx) {
696
+ let startPtr = ctx.p++;
697
+ let res = [];
698
+ let c;
699
+ while (ctx.p < ctx.s.length) {
700
+ skipVoid(ctx);
701
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
702
+ ctx.p++;
703
+ return res;
704
+ }
705
+ res.push(extractValue(ctx, 93));
706
+ skipVoid(ctx);
707
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) return res;
708
+ if (c !== 44) TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
709
+ }
710
+ TomlError.x("unfinished array", ctx, startPtr);
711
+ }
712
+ // ../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/parse.js
713
+ /*!
714
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
715
+ * SPDX-License-Identifier: BSD-3-Clause
716
+ *
717
+ * Redistribution and use in source and binary forms, with or without
718
+ * modification, are permitted provided that the following conditions are met:
719
+ *
720
+ * 1. Redistributions of source code must retain the above copyright notice, this
721
+ * list of conditions and the following disclaimer.
722
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
723
+ * this list of conditions and the following disclaimer in the
724
+ * documentation and/or other materials provided with the distribution.
725
+ * 3. Neither the name of the copyright holder nor the names of its contributors
726
+ * may be used to endorse or promote products derived from this software without
727
+ * specific prior written permission.
728
+ *
729
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
730
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
731
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
732
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
733
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
734
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
735
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
736
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
737
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
738
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
739
+ */
740
+ function peekTable(ctx, key, table, meta, type) {
741
+ let t = table;
742
+ let m = meta;
743
+ let k;
744
+ let hasOwn = false;
745
+ let state;
746
+ for (let i = 0; i < key.length; i++) {
747
+ if (i) {
748
+ t = hasOwn ? t[k] : t[k] = Object.create(null);
749
+ m = (state = m[k]).c;
750
+ if (type === 0 && (state.t === 1 || state.t === 2)) return null;
751
+ if (state.t === 2) {
752
+ let l = t.length - 1;
753
+ t = t[l];
754
+ m = m[l].c;
755
+ }
756
+ }
757
+ k = key[i];
758
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) return null;
759
+ if (!hasOwn) {
760
+ let unsafe = k === "__proto__";
761
+ if (ctx.uk && (unsafe || k === "constructor")) return false;
762
+ if (unsafe) {
763
+ Object.defineProperty(t, k, {
764
+ enumerable: true,
765
+ configurable: true,
766
+ writable: true
767
+ });
768
+ Object.defineProperty(m, k, {
769
+ enumerable: true,
770
+ configurable: true,
771
+ writable: true
772
+ });
773
+ }
774
+ m[k] = {
775
+ t: i < key.length - 1 && type === 2 ? 3 : type,
776
+ d: false,
777
+ i: 0,
778
+ c: Object.create(null)
779
+ };
780
+ }
781
+ }
782
+ state = m[k];
783
+ if (state.t !== type && !(type === 1 && state.t === 3)) return null;
784
+ if (type === 2) {
785
+ if (!state.d) {
786
+ state.d = true;
787
+ t[k] = [];
788
+ }
789
+ t[k].push(t = Object.create(null));
790
+ state.c[state.i++] = state = {
791
+ t: 1,
792
+ d: false,
793
+ i: 0,
794
+ c: Object.create(null)
795
+ };
796
+ }
797
+ if (state.d) return null;
798
+ state.d = true;
799
+ if (type === 1) t = hasOwn ? t[k] : t[k] = Object.create(null);
800
+ else if (type === 0 && hasOwn) return null;
801
+ return [
802
+ k,
803
+ t,
804
+ state.c
805
+ ];
806
+ }
807
+ function validateTablePeek(ctx, peek, ptr) {
808
+ if (peek === null || ctx.uk === 2) TomlError.x(peek === null ? "trying to redefine an already defined table or value" : "document contains an unsafe property", ctx, ptr);
809
+ }
810
+ function parse(toml, options = {}) {
811
+ let ctx = {
812
+ s: toml,
813
+ p: 0,
814
+ d: options.maxDepth ?? 1e3,
815
+ bi: options.integersAsBigInt ?? false,
816
+ ld: options.useLegacyDate ?? true,
817
+ uk: options.unsafeKeyBehaviour === "throw" ? 2 : options.unsafeKeyBehaviour === "drop" ? 1 : 0
818
+ };
819
+ let res = Object.create(null);
820
+ let meta = Object.create(null);
821
+ let tmp;
822
+ let skipping = false;
823
+ let tbl = res;
824
+ let m = meta;
825
+ if (toml.charCodeAt(0) === 65279) ctx.p++;
826
+ skipVoid(ctx);
827
+ while (ctx.p < toml.length) {
828
+ if (toml.charCodeAt(ctx.p) === 91) {
829
+ let isTableArray = toml.charCodeAt(++ctx.p) === 91;
830
+ tmp = ctx.p += +isTableArray;
831
+ skipping = false;
832
+ let k = parseKey(ctx, 93);
833
+ if (isTableArray) {
834
+ if (toml.charCodeAt(ctx.p) !== 93) TomlError.x("expected end of table array declaration", ctx);
835
+ ctx.p++;
836
+ }
837
+ let p = peekTable(ctx, k, res, meta, isTableArray ? 2 : 1);
838
+ if (!p) {
839
+ validateTablePeek(ctx, p, tmp);
840
+ skipping = true;
841
+ } else {
842
+ m = p[2];
843
+ tbl = p[1];
844
+ }
845
+ } else {
846
+ tmp = ctx.p;
847
+ let p = peekTable(ctx, parseKey(ctx), tbl, m, 0);
848
+ if (!p && !skipping) validateTablePeek(ctx, p, tmp);
849
+ skipVoid(ctx, true, true);
850
+ let v = extractValue(ctx, void 0);
851
+ if (p && !skipping) p[1][p[0]] = v;
852
+ }
853
+ skipVoid(ctx, true);
854
+ if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && (tmp !== 13 || toml.charCodeAt(ctx.p + 1) !== 10)) TomlError.x("each key-value declaration must be followed by an end-of-line", ctx);
855
+ skipVoid(ctx);
856
+ }
857
+ return res;
858
+ }
859
+ // ../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/stringify.js
860
+ /*!
861
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
862
+ * SPDX-License-Identifier: BSD-3-Clause
863
+ *
864
+ * Redistribution and use in source and binary forms, with or without
865
+ * modification, are permitted provided that the following conditions are met:
866
+ *
867
+ * 1. Redistributions of source code must retain the above copyright notice, this
868
+ * list of conditions and the following disclaimer.
869
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
870
+ * this list of conditions and the following disclaimer in the
871
+ * documentation and/or other materials provided with the distribution.
872
+ * 3. Neither the name of the copyright holder nor the names of its contributors
873
+ * may be used to endorse or promote products derived from this software without
874
+ * specific prior written permission.
875
+ *
876
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
877
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
878
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
879
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
880
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
881
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
882
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
883
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
884
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
885
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
886
+ */
887
+ let BARE_KEY = /^[a-z0-9-_]+$/i;
888
+ let HAS_WELLFORMED = !!"".isWellFormed;
889
+ function extendedTypeOf(obj) {
890
+ let type = typeof obj;
891
+ if (type === "object") {
892
+ if (Array.isArray(obj)) return "array";
893
+ if (typeof obj.getUTCDate === "function" && obj instanceof Date) return "date";
894
+ if (globalThis.Temporal) {
895
+ if (obj.until) {
896
+ if (obj instanceof Temporal.ZonedDateTime) return "temporal/tz+uc";
897
+ if (obj instanceof Temporal.PlainDateTime || obj instanceof Temporal.PlainDate) return "temporal/uc";
898
+ if (obj instanceof Temporal.PlainTime || obj instanceof Temporal.Instant) return "temporal";
899
+ if (obj instanceof Temporal.PlainYearMonth) return "temporal/x";
900
+ } else if (obj.toPlainDate && obj instanceof Temporal.PlainMonthDay || obj.negated && obj instanceof Temporal.Duration) return "temporal/x";
901
+ }
902
+ }
903
+ return type;
904
+ }
905
+ function isArrayOfTables(obj) {
906
+ for (let i = 0; i < obj.length; i++) if (extendedTypeOf(obj[i]) !== "object") return false;
907
+ return obj.length != 0;
908
+ }
909
+ function formatWellFormedStringUnchecked(s) {
910
+ return JSON.stringify(s).replaceAll("", "\\u007f");
911
+ }
912
+ function formatString(s) {
913
+ return formatWellFormedStringUnchecked(HAS_WELLFORMED ? s.toWellFormed() : s);
914
+ }
915
+ function formatKey(s) {
916
+ if (BARE_KEY.test(s)) return s;
917
+ if (HAS_WELLFORMED && !s.isWellFormed()) throw new RangeError("key contains illegal lone surrogates");
918
+ return formatWellFormedStringUnchecked(s);
919
+ }
920
+ function stringifyValue(val, type, depth, numberAsFloat, strictTemporal) {
921
+ if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
922
+ switch (type) {
923
+ case "number":
924
+ if (isNaN(val)) return "nan";
925
+ if (val === Infinity) return "inf";
926
+ if (val === -Infinity) return "-inf";
927
+ if (Number.isInteger(val) && (numberAsFloat || !Number.isSafeInteger(val))) return val.toFixed(1);
928
+ case "bigint":
929
+ case "boolean":
930
+ case "temporal": return val.toString();
931
+ case "string": return formatString(val);
932
+ case "date":
933
+ if (isNaN(val.getTime())) throw new TypeError("cannot serialize invalid date");
934
+ return val.toISOString();
935
+ case "object": return stringifyInlineTable(val, depth, numberAsFloat, strictTemporal);
936
+ case "array": return stringifyArray(val, depth, numberAsFloat, strictTemporal);
937
+ case "temporal/tz+uc": if (strictTemporal) {
938
+ let tz = val.timeZoneId;
939
+ let tzc = tz.charCodeAt(0);
940
+ if (tzc !== 43 && tzc !== 45 && (tzc !== 85 && tzc !== 71 && tzc !== 90 && tzc !== 69 || tz !== "UTC" && tz !== "UCT" && tz !== "Universal" && tz !== "Zulu" && !tz.startsWith("GMT") && tz !== "Greenwich" && !tz.startsWith("Etc/"))) throw new TypeError("Temporal objects with an IANA timezone are not allowed in Temporal strict mode");
941
+ }
942
+ case "temporal/uc":
943
+ if (strictTemporal && val.calendarId !== "iso8601") throw new TypeError("Temporal objects with a non-default calendar are not allowed in Temporal strict mode");
944
+ return val.toString({
945
+ calendarName: "never",
946
+ timeZoneName: "never"
947
+ });
948
+ case "temporal/x": throw new TypeError("Unsupported " + val[Symbol.toStringTag]);
949
+ }
950
+ }
951
+ function stringifyInlineTable(obj, depth, numberAsFloat, strictTemporal) {
952
+ let keys = Object.keys(obj);
953
+ if (keys.length === 0) return "{}";
954
+ let res = "{ ";
955
+ for (let i = 0; i < keys.length; i++) {
956
+ let k = keys[i];
957
+ if (i) res += ", ";
958
+ res += formatKey(k) + " = " + stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat, strictTemporal);
959
+ }
960
+ return res + " }";
961
+ }
962
+ function stringifyArray(array, depth, numberAsFloat, strictTemporal) {
963
+ if (array.length === 0) return "[]";
964
+ let res = "[ ";
965
+ for (let i = 0; i < array.length; i++) {
966
+ if (i) res += ", ";
967
+ if (array[i] === null || array[i] === void 0) throw new TypeError("arrays cannot contain null or undefined values");
968
+ res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat, strictTemporal);
969
+ }
970
+ return res + " ]";
971
+ }
972
+ function stringifyArrayTable(array, key, depth, numberAsFloat, strictTemporal) {
973
+ if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
974
+ let res = "";
975
+ for (let i = 0; i < array.length; i++) {
976
+ res += `${res && "\n"}[[${key}]]\n`;
977
+ res += stringifyTable(0, array[i], key, depth, numberAsFloat, strictTemporal);
978
+ }
979
+ return res;
980
+ }
981
+ function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat, strictTemporal) {
982
+ if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
983
+ let preamble = "";
984
+ let tables = "";
985
+ let keys = Object.keys(obj);
986
+ for (let i = 0; i < keys.length; i++) {
987
+ let k = keys[i];
988
+ if (obj[k] !== null && obj[k] !== void 0) {
989
+ let type = extendedTypeOf(obj[k]);
990
+ if (type === "symbol" || type === "function") throw new TypeError(`cannot serialize values of type '${type}'`);
991
+ let key = formatKey(k);
992
+ if (type === "array" && isArrayOfTables(obj[k])) tables += (tables && "\n") + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat, strictTemporal);
993
+ else if (type === "object") {
994
+ let tblKey = prefix ? `${prefix}.${key}` : key;
995
+ tables += (tables && "\n") + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat, strictTemporal);
996
+ } else {
997
+ preamble += key;
998
+ preamble += " = ";
999
+ preamble += stringifyValue(obj[k], type, depth, numberAsFloat, strictTemporal);
1000
+ preamble += "\n";
1001
+ }
1002
+ }
1003
+ }
1004
+ if (tableKey && (preamble || !tables)) preamble = preamble ? `[${tableKey}]\n${preamble}` : `[${tableKey}]`;
1005
+ return preamble && tables ? `${preamble}\n${tables}` : preamble || tables;
1006
+ }
1007
+ function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false, strictTemporal = false } = {}) {
1008
+ if (extendedTypeOf(obj) !== "object") throw new TypeError("stringify can only be called with an object");
1009
+ let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat, strictTemporal);
1010
+ if (str[str.length - 1] !== "\n") return str + "\n";
1011
+ return str;
1012
+ }
1013
+ // ../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/index.js
1014
+ /*!
1015
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
1016
+ * SPDX-License-Identifier: BSD-3-Clause
1017
+ *
1018
+ * Redistribution and use in source and binary forms, with or without
1019
+ * modification, are permitted provided that the following conditions are met:
1020
+ *
1021
+ * 1. Redistributions of source code must retain the above copyright notice, this
1022
+ * list of conditions and the following disclaimer.
1023
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
1024
+ * this list of conditions and the following disclaimer in the
1025
+ * documentation and/or other materials provided with the distribution.
1026
+ * 3. Neither the name of the copyright holder nor the names of its contributors
1027
+ * may be used to endorse or promote products derived from this software without
1028
+ * specific prior written permission.
1029
+ *
1030
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1031
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1032
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1033
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1034
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1035
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1036
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1037
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1038
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1039
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1040
+ */
1041
+ // src/envfile.ts
1042
+ const HEADER = "# cetra (npx @cetra-ai/cli init)";
1043
+ /** The values `init` writes: URLs, keys and plain words, so no quoting is needed. */
1044
+ const VALUE = /^[\w:/.[\]-]+$/;
1045
+ const ASSIGNMENT = /^(\s*(?:export\s+)?)([A-Za-z_]\w*)\s*=/;
1046
+ const run$1 = promisify(execFile);
1047
+ /** Writes a private (0600) text file: a `<name>.tmp` file, synced, renamed over the target; the
1048
+ * temporary file is removed on failure. Creates missing parent directories, never changes an
1049
+ * existing directory's mode. Used for `.env` and `credentials.toml`. A symlink at `path` is
1050
+ * followed: its target is replaced and the link stays (a dangling link is replaced itself). */
1051
+ async function writeEnvFile(path, text) {
1052
+ const target = await realpath(path).catch(() => path);
1053
+ const temporary = `${target}.tmp`;
1054
+ try {
1055
+ await mkdir(dirname(target), { recursive: true });
1056
+ const handle = await open(temporary, "w", 384);
1057
+ try {
1058
+ await handle.writeFile(text, "utf8");
1059
+ await handle.sync();
1060
+ await handle.chmod(384);
1061
+ } finally {
1062
+ await handle.close();
1063
+ }
1064
+ await rename(temporary, target);
1065
+ } catch {
1066
+ await rm(temporary, { force: true }).catch(() => void 0);
1067
+ throw new CliError(`could not write ${basename(path)}`, Exit.Write);
1068
+ }
1069
+ }
1070
+ /** Sets `values` in an env file's text. Lines that assign a name are replaced in place (keeping
1071
+ * `export` and a CR), other lines, comments and order are kept, missing names are appended. A
1072
+ * new file (`text` undefined) starts with a header comment. Keeps a leading BOM and CRLF line
1073
+ * endings. The values are checked first. */
1074
+ function setVariables(text, values) {
1075
+ for (const [name, value] of Object.entries(values)) if (!VALUE.test(value)) throw new CliError(`invalid value for ${name}`, Exit.Write);
1076
+ const source = text ?? "";
1077
+ const bom = source.startsWith("") ? "" : "";
1078
+ const body = source.slice(bom.length);
1079
+ const eolSuffix = body.includes("\r\n") ? "\r" : "";
1080
+ const lines = body.split("\n");
1081
+ if (lines[lines.length - 1] === "") lines.pop();
1082
+ const out = text === void 0 ? [HEADER] : [];
1083
+ const found = /* @__PURE__ */ new Set();
1084
+ for (const line of lines) {
1085
+ const cr = line.endsWith("\r") ? "\r" : "";
1086
+ const match = ASSIGNMENT.exec(line.slice(0, line.length - cr.length));
1087
+ const name = match?.[2];
1088
+ if (match !== null && name !== void 0 && Object.hasOwn(values, name)) {
1089
+ found.add(name);
1090
+ out.push(`${match[1] ?? ""}${name}=${values[name]}${cr}`);
1091
+ } else out.push(line);
1092
+ }
1093
+ for (const [name, value] of Object.entries(values)) if (!found.has(name)) out.push(`${name}=${value}${eolSuffix}`);
1094
+ return out.length === 0 ? "" : `${bom}${out.join("\n")}\n`;
1095
+ }
1096
+ /** The value of the last assignment of `name` in an env file's text: quotes removed, spaces and a
1097
+ * CR trimmed. Undefined when the name is not assigned. */
1098
+ function readVariable(text, name) {
1099
+ let value;
1100
+ for (const line of text.replace(/^\uFEFF/, "").split("\n")) {
1101
+ const match = /^\s*(?:export\s+)?([A-Za-z_]\w*)\s*=(.*)$/.exec(line.replace(/\r$/, ""));
1102
+ if (match?.[1] === name) value = unquote((match[2] ?? "").trim());
1103
+ }
1104
+ return value;
1105
+ }
1106
+ function unquote(value) {
1107
+ const first = value.charAt(0);
1108
+ if (value.length >= 2 && (first === "\"" || first === "'") && value.endsWith(first)) return value.slice(1, -1);
1109
+ return value;
1110
+ }
1111
+ /** Adds the env file to `<dir>/.gitignore` when `<dir>` is in a git work tree and git does not
1112
+ * already ignore the file. `envPath` is absolute or relative to `dir`. Returns true when it added
1113
+ * the line. Outside a work tree, or with git missing, nothing changes. */
1114
+ async function ignoreInGit(dir, envPath) {
1115
+ const root = resolve(dir);
1116
+ const relativePath = relative(root, resolve(root, envPath));
1117
+ if (relativePath === "" || isAbsolute(relativePath) || relativePath.split(sep)[0] === "..") return false;
1118
+ if (await gitExitCode(root, ["rev-parse", "--is-inside-work-tree"]) !== 0) return false;
1119
+ const entry = relativePath.split(sep).join("/");
1120
+ if (await gitExitCode(root, [
1121
+ "check-ignore",
1122
+ "-q",
1123
+ "--",
1124
+ entry
1125
+ ]) !== 1) return false;
1126
+ const gitignore = join(root, ".gitignore");
1127
+ let existing = "";
1128
+ try {
1129
+ existing = await readFile(gitignore, "utf8");
1130
+ } catch (error) {
1131
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw new CliError("could not read .gitignore", Exit.Write);
1132
+ }
1133
+ const lead = existing !== "" && !existing.endsWith("\n") ? "\n" : "";
1134
+ try {
1135
+ await appendFile(gitignore, `${lead}${entry}\n`, "utf8");
1136
+ } catch {
1137
+ throw new CliError("could not write .gitignore", Exit.Write);
1138
+ }
1139
+ return true;
1140
+ }
1141
+ /** The exit status of a git command run in `cwd`; undefined when git cannot run. */
1142
+ async function gitExitCode(cwd, args) {
1143
+ const env = { ...process.env };
1144
+ delete env.GIT_DIR;
1145
+ delete env.GIT_INDEX_FILE;
1146
+ try {
1147
+ await run$1("git", args, {
1148
+ cwd,
1149
+ env
1150
+ });
1151
+ return 0;
1152
+ } catch (error) {
1153
+ return error instanceof Error && "code" in error && typeof error.code === "number" ? error.code : void 0;
1154
+ }
1155
+ }
1156
+ // src/credentials.ts
1157
+ /** The credentials file of `cetra login`, shared with the Rust CLI (D-AO-17): the same path,
1158
+ * the same `[servers."<url>"]` / `token = "…"` format, mode 0600. */
1159
+ const FILE_NAME = "credentials.toml";
1160
+ const BAD_URL = "--url must start with http:// or https://";
1161
+ /** `credentials.toml`'s path, as the Rust CLI's `dirs::config_dir()` finds it. Linux:
1162
+ * `$XDG_CONFIG_HOME` when it is absolute, else `~/.config`; macOS: `~/Library/Application Support`;
1163
+ * Windows: `%APPDATA%`. `platform` and `home` are parameters so tests can check every platform. */
1164
+ function credentialsPath(env, platform = process.platform, home = homedir()) {
1165
+ if (platform === "win32") {
1166
+ const appData = env.APPDATA;
1167
+ if (appData === void 0 || appData === "") throw new CliError("could not find the config directory", Exit.Error);
1168
+ return win32.join(appData, "cetra", FILE_NAME);
1169
+ }
1170
+ if (platform === "darwin") return posix.join(home, "Library", "Application Support", "cetra", FILE_NAME);
1171
+ const xdg = env.XDG_CONFIG_HOME;
1172
+ const base = xdg !== void 0 && posix.isAbsolute(xdg) ? xdg : posix.join(home, ".config");
1173
+ return posix.join(base, "cetra", FILE_NAME);
1174
+ }
1175
+ /** Trims and drops every trailing `/`, so one server is one key. */
1176
+ function normalizeServerUrl(raw) {
1177
+ let url = raw.trim();
1178
+ while (url.endsWith("/")) url = url.slice(0, -1);
1179
+ return url;
1180
+ }
1181
+ /** Whether a server URL is usable: no control character, an `http` or `https` URL, no user or
1182
+ * password. The messages never include the URL. Every path a URL arrives on runs this. */
1183
+ function checkServerUrl(url) {
1184
+ if (url.search(CONTROL) !== -1) throw new CliError(BAD_URL, Exit.Usage);
1185
+ let parsed;
1186
+ try {
1187
+ parsed = new URL(url);
1188
+ } catch {
1189
+ throw new CliError(BAD_URL, Exit.Usage);
1190
+ }
1191
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new CliError(BAD_URL, Exit.Usage);
1192
+ if (parsed.username !== "" || parsed.password !== "") throw new CliError("the server URL must not contain credentials", Exit.Usage);
1193
+ }
1194
+ /** The stored form of a raw server URL: trim, check, then normalize (the Rust order). */
1195
+ function serverUrl(raw) {
1196
+ const trimmed = raw.trim();
1197
+ checkServerUrl(trimmed);
1198
+ return normalizeServerUrl(trimmed);
1199
+ }
1200
+ /** The server URL when no `--url` is given: the only saved server. Several saved servers, or none,
1201
+ * need `--url`. */
1202
+ function chosenServer$1(saved) {
1203
+ if (saved.size === 0) throw new CliError("no saved server; run `cetra-cli login --url <URL>`", Exit.Usage);
1204
+ if (saved.size > 1) throw new CliError("more than one saved server; pass --url", Exit.Usage);
1205
+ const [server] = [...saved.keys()];
1206
+ if (server === void 0) throw new CliError("no saved server; run `cetra-cli login --url <URL>`", Exit.Usage);
1207
+ checkServerUrl(server);
1208
+ return server;
1209
+ }
1210
+ /** The saved tokens, server URL → token. A missing file is empty; a file that does not parse, or
1211
+ * whose `servers` is not a table of `{ token }` tables, is an error. */
1212
+ async function loadCredentials(path) {
1213
+ let text;
1214
+ try {
1215
+ text = await readFile(path, "utf8");
1216
+ } catch (error) {
1217
+ if (isErrorCode$1(error, "ENOENT")) return /* @__PURE__ */ new Map();
1218
+ throw new CliError(`could not read ${FILE_NAME}`, Exit.Error);
1219
+ }
1220
+ const invalid = () => new CliError("credentials file is invalid", Exit.Error);
1221
+ let parsed;
1222
+ try {
1223
+ parsed = parse(text);
1224
+ } catch {
1225
+ throw invalid();
1226
+ }
1227
+ if (!isRecord$5(parsed)) throw invalid();
1228
+ const servers = parsed.servers ?? {};
1229
+ if (!isRecord$5(servers)) throw invalid();
1230
+ const tokens = /* @__PURE__ */ new Map();
1231
+ for (const [server, entry] of Object.entries(servers)) {
1232
+ if (!isRecord$5(entry) || typeof entry.token !== "string") throw invalid();
1233
+ tokens.set(server, entry.token);
1234
+ }
1235
+ return tokens;
1236
+ }
1237
+ /** Saves `token` for `server` and keeps the other servers. The directory becomes 0700 (its mode
1238
+ * is changed on every save, as in Rust), the file 0600, and the servers are written sorted. */
1239
+ async function saveToken(path, server, token) {
1240
+ const tokens = await loadCredentials(path);
1241
+ tokens.set(server, token);
1242
+ const servers = {};
1243
+ for (const url of [...tokens.keys()].sort()) servers[url] = { token: tokens.get(url) ?? "" };
1244
+ const directory = dirname(path);
1245
+ try {
1246
+ await mkdir(directory, { recursive: true });
1247
+ if (process.platform !== "win32") await chmod(directory, 448);
1248
+ } catch {
1249
+ throw new CliError("could not create the credentials directory", Exit.Write);
1250
+ }
1251
+ await writeEnvFile(path, stringify({ servers }));
1252
+ }
1253
+ function isRecord$5(value) {
1254
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1255
+ }
1256
+ function isErrorCode$1(error, code) {
1257
+ return isRecord$5(error) && error.code === code;
1258
+ }
1259
+ // src/browser.ts
1260
+ /** Opens `url` in the browser, detached and without a shell. A missing opener program is harmless
1261
+ * (the error listener), and on Linux without a display nothing is started. */
1262
+ function openBrowser(url, deps = {}, env = process.env, platform = process.platform) {
1263
+ if (platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY) return;
1264
+ const launch = deps.spawn ?? spawn;
1265
+ let child;
1266
+ if (platform === "darwin") child = launch("open", [url], {
1267
+ detached: true,
1268
+ stdio: "ignore"
1269
+ });
1270
+ else if (platform === "win32") child = launch("rundll32", ["url.dll,FileProtocolHandler", url], {
1271
+ detached: true,
1272
+ stdio: "ignore"
1273
+ });
1274
+ else child = launch("xdg-open", [url], {
1275
+ detached: true,
1276
+ stdio: "ignore"
1277
+ });
1278
+ child.on("error", () => {});
1279
+ child.unref();
1280
+ }
1281
+ // src/host.ts
1282
+ /** The machine's name for the approval page: `[A-Za-z0-9.-]` only, at most 64 characters.
1283
+ * Undefined when nothing is left. The server sanitises it again. */
1284
+ function localHost() {
1285
+ const cleaned = hostname().replace(/[^A-Za-z0-9.-]/g, "").slice(0, 64);
1286
+ return cleaned === "" ? void 0 : cleaned;
1287
+ }
1288
+ // src/version.ts
1289
+ const VERSION = "0.0.0";
1290
+ // src/http.ts
1291
+ /** The most of an error body that is read (bytes past this are dropped). */
1292
+ const PROBLEM_LIMIT = 65536;
1293
+ const DEFAULT_TIMEOUT_MS = 3e4;
1294
+ /** One JSON request. Never sends `Origin` unless `origin` is given; never logs. */
1295
+ async function requestJson(method, url, options = {}) {
1296
+ const headers = {
1297
+ Accept: "application/json",
1298
+ "User-Agent": `cetra-cli/${VERSION}`
1299
+ };
1300
+ if (options.body !== void 0) headers["Content-Type"] = "application/json";
1301
+ if (options.token !== void 0) headers.Authorization = `Bearer ${options.token}`;
1302
+ if (options.cookie !== void 0) headers.Cookie = options.cookie;
1303
+ if (options.origin !== void 0) headers.Origin = options.origin;
1304
+ const server = new URL(url).origin;
1305
+ let response;
1306
+ let text;
1307
+ try {
1308
+ response = await fetch(url, {
1309
+ method,
1310
+ headers,
1311
+ body: options.body === void 0 ? void 0 : JSON.stringify(options.body),
1312
+ redirect: "manual",
1313
+ signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
1314
+ });
1315
+ text = response.ok ? await response.text() : await readLimited(response);
1316
+ } catch {
1317
+ throw new CliError(`could not reach ${server}`, Exit.Unreachable);
1318
+ }
1319
+ return {
1320
+ status: response.status,
1321
+ headers: response.headers,
1322
+ body: parseJson(text),
1323
+ text
1324
+ };
1325
+ }
1326
+ async function readLimited(response) {
1327
+ const reader = response.body?.getReader();
1328
+ if (reader === void 0) return "";
1329
+ const chunks = [];
1330
+ let total = 0;
1331
+ while (total < PROBLEM_LIMIT) {
1332
+ const { done, value } = await reader.read();
1333
+ if (done) break;
1334
+ const room = PROBLEM_LIMIT - total;
1335
+ const kept = value.length > room ? value.subarray(0, room) : value;
1336
+ chunks.push(kept);
1337
+ total += kept.length;
1338
+ }
1339
+ await reader.cancel();
1340
+ return new TextDecoder().decode(Buffer.concat(chunks));
1341
+ }
1342
+ function parseJson(text) {
1343
+ try {
1344
+ return JSON.parse(text);
1345
+ } catch {
1346
+ return;
1347
+ }
1348
+ }
1349
+ /** Replaces control characters with spaces, so a server text cannot write terminal codes. */
1350
+ function clean$1(text) {
1351
+ return text.replace(CONTROL, " ");
1352
+ }
1353
+ function isRecord$4(value) {
1354
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1355
+ }
1356
+ /** The message for a non-2xx answer, as the Rust CLI words it: `"{title} ({code})"`, `": {detail}"`,
1357
+ * one `"\n {field}: {message}"` per field error (with ` (line L, column C)`), control characters
1358
+ * replaced by spaces. 401 names the sign-in command; any other body that is not a problem gives
1359
+ * "the server answered <status>". */
1360
+ function problemMessage(status, body, server) {
1361
+ if (status === 401) return `the server rejected the token; run \`cetra-cli login --url ${server}\``;
1362
+ if (isRecord$4(body) && typeof body.title === "string") {
1363
+ const code = typeof body.code === "string" ? body.code : "";
1364
+ let text = `${clean$1(body.title)} (${clean$1(code)})`;
1365
+ if (typeof body.detail === "string") text += `: ${clean$1(body.detail)}`;
1366
+ if (Array.isArray(body.errors)) for (const entry of body.errors) {
1367
+ if (!isRecord$4(entry) || typeof entry.field !== "string" || typeof entry.message !== "string") continue;
1368
+ text += `\n ${clean$1(entry.field)}: ${clean$1(entry.message)}`;
1369
+ const position = entry.position;
1370
+ if (isRecord$4(position) && typeof position.line === "number" && typeof position.column === "number") text += ` (line ${position.line}, column ${position.column})`;
1371
+ }
1372
+ return text;
1373
+ }
1374
+ return `the server answered ${status}`;
1375
+ }
1376
+ // src/device.ts
1377
+ const MIN_INTERVAL_MS = 1e3;
1378
+ const SLOW_DOWN_STEP_MS = 5e3;
1379
+ const DEADLINE_SLACK_MS = 5e3;
1380
+ /** The poll interval never exceeds the code's longest lifetime, so a huge `interval` from the
1381
+ * server cannot overflow `setTimeout` (which would fire at once). */
1382
+ const MAX_INTERVAL_MS = 9e5;
1383
+ const EXPIRED = "the sign-in code expired; run the command again";
1384
+ const INVALID_URL = "the server sent an invalid sign-in URL";
1385
+ const INVALID_SERVER = "the server sent an invalid sign-in server";
1386
+ const MOVED_TWICE = "sign-in failed: the server moved the sign-in twice";
1387
+ const INVALID_CODE = "the server sent an invalid sign-in code";
1388
+ /** The message for every grant the CLI cannot use, here and in the local password sign-in. */
1389
+ const INVALID_GRANT = "the server returned an invalid grant";
1390
+ /** The meaning of one poll answer. 429 and 502 to 504 keep the code alive; a 400 carries an
1391
+ * RFC 8628 code in its problem body; a 400 `moved` names the cell in its `server` member; anything
1392
+ * else fails the sign-in. */
1393
+ function step(status, body) {
1394
+ if ([
1395
+ 429,
1396
+ 502,
1397
+ 503,
1398
+ 504
1399
+ ].includes(status)) return "wait";
1400
+ if (status !== 400) return { failed: status };
1401
+ switch (isRecord$3(body) && typeof body.code === "string" ? body.code : void 0) {
1402
+ case "authorization_pending": return "wait";
1403
+ case "slow_down": return "slow_down";
1404
+ case "access_denied": return "denied";
1405
+ case "expired_token": return "expired";
1406
+ case "moved": {
1407
+ const server = isRecord$3(body) ? body.server : void 0;
1408
+ return typeof server === "string" ? { moved: server } : { failed: status };
1409
+ }
1410
+ default: return { failed: status };
1411
+ }
1412
+ }
1413
+ /** `XXXX-XXXX` in ASCII capitals. */
1414
+ function isUserCode(text) {
1415
+ return /^[A-Z]{4}-[A-Z]{4}$/.test(text);
1416
+ }
1417
+ /** `pat-cetra-` and 32 ASCII letters or digits. */
1418
+ function isPersonalToken(text) {
1419
+ return /^pat-cetra-[A-Za-z0-9]{32}$/.test(text);
1420
+ }
1421
+ /** `sk-cetra-` and 32 ASCII letters or digits. */
1422
+ function isSecretKey(text) {
1423
+ return /^sk-cetra-[A-Za-z0-9]{32}$/.test(text);
1424
+ }
1425
+ /** An organization or project slug: lower-case words of letters and digits joined by single `-`,
1426
+ * 1 to 48 characters. Slugs are written into the agent prompt and the env files, so nothing else
1427
+ * is accepted. */
1428
+ function isSlug(text) {
1429
+ return text.length <= 48 && /^[a-z0-9]+(-[a-z0-9]+)*$/.test(text);
1430
+ }
1431
+ /** A project id: a UUID in the usual 8-4-4-4-12 hexadecimal form. */
1432
+ function isUuid(text) {
1433
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(text);
1434
+ }
1435
+ /** Keeps a poll interval within the bounds above. */
1436
+ function clampInterval(ms) {
1437
+ return Math.min(Math.max(ms, MIN_INTERVAL_MS), MAX_INTERVAL_MS);
1438
+ }
1439
+ const defaultSleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1440
+ /** Requests a code, prints the URL and the code on stderr, opens the browser unless `noBrowser`,
1441
+ * and polls until the grant arrives, the user denies, or the code expires. One `moved` answer
1442
+ * moves the polling to the cell it names (D-AO-14); a second one fails the sign-in. */
1443
+ async function deviceSignIn(options) {
1444
+ const { server, purpose, noBrowser, project, stderr } = options;
1445
+ const deps = options.deps ?? {};
1446
+ const sleep = deps.sleep ?? defaultSleep$1;
1447
+ const now = deps.now ?? Date.now;
1448
+ const host = localHost();
1449
+ const codeBody = host === void 0 ? { purpose } : {
1450
+ purpose,
1451
+ host
1452
+ };
1453
+ const codeAnswer = await requestJson("POST", `${server}/api/auth/device/code`, { body: codeBody });
1454
+ if (codeAnswer.status !== 200) throw new CliError(`the server refused a sign-in code (HTTP ${codeAnswer.status})`, Exit.SignIn);
1455
+ const answer = isRecord$3(codeAnswer.body) ? codeAnswer.body : {};
1456
+ const url = signInUrl(answer.verification_uri_complete, project);
1457
+ if (typeof answer.user_code !== "string" || !isUserCode(answer.user_code) || typeof answer.device_code !== "string" || !isFiniteNumber(answer.expires_in) || !isFiniteNumber(answer.interval)) throw new CliError(INVALID_CODE, Exit.SignIn);
1458
+ const deviceCode = answer.device_code;
1459
+ stderr(`Open ${url.href} in your browser and approve the code.`);
1460
+ stderr(`Code: ${answer.user_code}`);
1461
+ if (!noBrowser) openBrowser(url.href, deps);
1462
+ let intervalMs = clampInterval(answer.interval * 1e3);
1463
+ const lifetimeMs = Math.min(answer.expires_in, 900) * 1e3;
1464
+ const deadline = now() + lifetimeMs + DEADLINE_SLACK_MS;
1465
+ let warned = false;
1466
+ let pollServer = server;
1467
+ let moved = false;
1468
+ for (;;) {
1469
+ await sleep(intervalMs);
1470
+ if (now() >= deadline) throw new CliError(EXPIRED, Exit.SignIn);
1471
+ let poll;
1472
+ try {
1473
+ poll = await requestJson("POST", `${pollServer}/api/auth/device/token`, { body: { device_code: deviceCode } });
1474
+ } catch (error) {
1475
+ if (!(error instanceof CliError && error.code === Exit.Unreachable)) throw error;
1476
+ if (!warned) {
1477
+ stderr("warning: cannot reach the server; still waiting");
1478
+ warned = true;
1479
+ }
1480
+ continue;
1481
+ }
1482
+ if (poll.status === 200) return {
1483
+ grant: checkGrant(poll.body, purpose),
1484
+ server: pollServer
1485
+ };
1486
+ const next = step(poll.status, poll.body);
1487
+ if (next === "wait") continue;
1488
+ if (next === "slow_down") {
1489
+ intervalMs = clampInterval(intervalMs + SLOW_DOWN_STEP_MS);
1490
+ continue;
1491
+ }
1492
+ if (next === "denied") throw new CliError("sign-in denied in the browser", Exit.SignIn);
1493
+ if (next === "expired") throw new CliError(EXPIRED, Exit.SignIn);
1494
+ if ("moved" in next) {
1495
+ if (moved) throw new CliError(MOVED_TWICE, Exit.SignIn);
1496
+ pollServer = movedOrigin(next.moved, server);
1497
+ moved = true;
1498
+ stderr(`Continuing the sign-in at ${pollServer}`);
1499
+ continue;
1500
+ }
1501
+ throw new CliError(`sign-in failed (HTTP ${next.failed})`, Exit.SignIn);
1502
+ }
1503
+ }
1504
+ /** The origin a `moved` answer names. Only an https origin, or a loopback http origin when the
1505
+ * typed server is loopback too (tests), is followed; the path, query and fragment are dropped.
1506
+ * Loopback is tested here, not with `local.ts`, which imports this module. */
1507
+ function movedOrigin(value, typed) {
1508
+ const invalid = () => new CliError(INVALID_SERVER, Exit.SignIn);
1509
+ let target;
1510
+ let typedHost;
1511
+ try {
1512
+ checkServerUrl(value);
1513
+ target = new URL(value);
1514
+ typedHost = new URL(typed).hostname;
1515
+ } catch {
1516
+ throw invalid();
1517
+ }
1518
+ if (target.protocol === "https:") return target.origin;
1519
+ if (target.protocol === "http:" && isLoopbackHost(target.hostname) && isLoopbackHost(typedHost)) return target.origin;
1520
+ throw invalid();
1521
+ }
1522
+ /** `localhost`, `127.0.0.0/8` and `[::1]`, as `URL.hostname` spells them. */
1523
+ function isLoopbackHost(hostname) {
1524
+ return hostname === "localhost" || hostname === "[::1]" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname);
1525
+ }
1526
+ /** The sign-in URL the server sent, with `project` added when given. Only http and https. */
1527
+ function signInUrl(value, project) {
1528
+ if (typeof value !== "string") throw new CliError(INVALID_URL, Exit.SignIn);
1529
+ let url;
1530
+ try {
1531
+ url = new URL(value);
1532
+ } catch {
1533
+ throw new CliError(INVALID_URL, Exit.SignIn);
1534
+ }
1535
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new CliError(INVALID_URL, Exit.SignIn);
1536
+ if (project !== void 0) url.searchParams.set("project", project);
1537
+ return url;
1538
+ }
1539
+ /** Checks the grant of a 200 answer and keeps only the fields the CLI uses. The server is stored in
1540
+ * its normalized form. For `init` it must also be a valid `.env` value, since `init` writes it. */
1541
+ function checkGrant(body, purpose) {
1542
+ const invalid = () => new CliError(INVALID_GRANT, Exit.SignIn);
1543
+ if (!isRecord$3(body) || typeof body.server !== "string" || typeof body.token !== "string") throw invalid();
1544
+ if (!isPersonalToken(body.token)) throw invalid();
1545
+ let server;
1546
+ try {
1547
+ server = serverUrl(body.server);
1548
+ } catch {
1549
+ throw invalid();
1550
+ }
1551
+ const project = parseProject(body.project);
1552
+ const ingestKey = typeof body.ingest_key === "string" && isSecretKey(body.ingest_key) ? body.ingest_key : void 0;
1553
+ if (purpose === "init") {
1554
+ try {
1555
+ setVariables(void 0, { CETRA_BASE_URL: server });
1556
+ } catch {
1557
+ throw invalid();
1558
+ }
1559
+ if (project === void 0 || ingestKey === void 0) throw invalid();
1560
+ }
1561
+ const grant = {
1562
+ server,
1563
+ token: body.token
1564
+ };
1565
+ if (project !== void 0) grant.project = project;
1566
+ if (ingestKey !== void 0) grant.ingest_key = ingestKey;
1567
+ return grant;
1568
+ }
1569
+ /** The grant's project, or undefined when the answer has none. Its ids and slugs are checked
1570
+ * against the server's rules, and `name` loses its control characters: the values reach the
1571
+ * agent prompt and the env file, so a server cannot put other lines or terminal codes there. */
1572
+ function parseProject(value) {
1573
+ if (value === void 0 || value === null) return void 0;
1574
+ const invalid = () => new CliError(INVALID_GRANT, Exit.SignIn);
1575
+ if (!isRecord$3(value)) throw invalid();
1576
+ const { id, org_slug, slug, name } = value;
1577
+ if (typeof id !== "string" || !isUuid(id) || typeof org_slug !== "string" || !isSlug(org_slug) || typeof slug !== "string" || !isSlug(slug) || typeof name !== "string") throw invalid();
1578
+ return {
1579
+ id,
1580
+ org_slug,
1581
+ slug,
1582
+ name: name.replace(CONTROL, "")
1583
+ };
1584
+ }
1585
+ function isRecord$3(value) {
1586
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1587
+ }
1588
+ function isFiniteNumber(value) {
1589
+ return typeof value === "number" && Number.isFinite(value);
1590
+ }
1591
+ // src/link.ts
1592
+ const LINK_FILE = ".cetra/project.json";
1593
+ /** The first directory, `dir` itself included, that holds a `.git` entry (a directory or a file,
1594
+ * as in a worktree); undefined when there is none up to the filesystem root. */
1595
+ async function gitTop(dir) {
1596
+ let current = resolve(dir);
1597
+ for (;;) {
1598
+ if (await exists$2(join(current, ".git"))) return current;
1599
+ const parent = dirname(current);
1600
+ if (parent === current) return void 0;
1601
+ current = parent;
1602
+ }
1603
+ }
1604
+ /** Writes the link under `dir` (creating `.cetra/`) and returns its absolute path. */
1605
+ async function writeLink(dir, link) {
1606
+ const path = join(resolve(dir), LINK_FILE);
1607
+ const text = `${JSON.stringify({
1608
+ server: link.server,
1609
+ org: link.org,
1610
+ project: link.project,
1611
+ project_id: link.project_id
1612
+ }, null, 2)}\n`;
1613
+ try {
1614
+ await mkdir(dirname(path), { recursive: true });
1615
+ await writeFile(path, text, {
1616
+ encoding: "utf8",
1617
+ mode: 420
1618
+ });
1619
+ } catch {
1620
+ throw new CliError(`could not write ${LINK_FILE}`, Exit.Write);
1621
+ }
1622
+ return path;
1623
+ }
1624
+ /** The link of `cwd`, else of its nearest parent that has one. The walk stops at the top of the
1625
+ * git work tree that holds `cwd` (or at the filesystem root outside a repository). */
1626
+ async function findLink(cwd) {
1627
+ const top = await gitTop(cwd);
1628
+ let current = resolve(cwd);
1629
+ for (;;) {
1630
+ const link = await readLink(join(current, LINK_FILE));
1631
+ if (link !== void 0) return link;
1632
+ if (current === top) return void 0;
1633
+ const parent = dirname(current);
1634
+ if (parent === current) return void 0;
1635
+ current = parent;
1636
+ }
1637
+ }
1638
+ async function readLink(path) {
1639
+ let text;
1640
+ try {
1641
+ text = await readFile(path, "utf8");
1642
+ } catch (error) {
1643
+ if (isErrorCode(error, "ENOENT") || isErrorCode(error, "ENOTDIR")) return void 0;
1644
+ throw new CliError(`could not read ${LINK_FILE}`, Exit.Error);
1645
+ }
1646
+ const invalid = () => new CliError(`${LINK_FILE} is invalid`, Exit.Error);
1647
+ let parsed;
1648
+ try {
1649
+ parsed = JSON.parse(text);
1650
+ } catch {
1651
+ throw invalid();
1652
+ }
1653
+ if (!isRecord$2(parsed)) throw invalid();
1654
+ const { server, org, project, project_id: projectId } = parsed;
1655
+ if (typeof server !== "string" || typeof org !== "string" || typeof project !== "string" || typeof projectId !== "string") throw invalid();
1656
+ return {
1657
+ server,
1658
+ org,
1659
+ project,
1660
+ project_id: projectId
1661
+ };
1662
+ }
1663
+ async function exists$2(path) {
1664
+ try {
1665
+ await stat(path);
1666
+ return true;
1667
+ } catch {
1668
+ return false;
1669
+ }
1670
+ }
1671
+ function isRecord$2(value) {
1672
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1673
+ }
1674
+ function isErrorCode(error, code) {
1675
+ return error instanceof Error && "code" in error && error.code === code;
1676
+ }
1677
+ // src/prompt-io.ts
1678
+ /** True when both stdin and stderr are terminals, so questions can be asked. */
1679
+ function interactive() {
1680
+ return Boolean(process.stdin.isTTY && process.stderr.isTTY);
1681
+ }
1682
+ /** Asks one question on `output` and reads one answer from `input`. An empty answer gives
1683
+ * `fallback`. The interface is closed in every case, or the process would not exit. If the
1684
+ * input closes first (Ctrl-D, Ctrl-C, or an input that ended), the question is cancelled. */
1685
+ async function ask(question, fallback, input = process.stdin, output = process.stderr) {
1686
+ const rl = createInterface({
1687
+ input,
1688
+ output
1689
+ });
1690
+ let onClose = () => void 0;
1691
+ const closed = new Promise((_, reject) => {
1692
+ onClose = () => reject(new CliError("cancelled", Exit.Error));
1693
+ rl.once("close", onClose);
1694
+ });
1695
+ try {
1696
+ const answer = (await Promise.race([rl.question(question), closed])).trim();
1697
+ return answer === "" ? fallback : answer;
1698
+ } finally {
1699
+ rl.off("close", onClose);
1700
+ rl.close();
1701
+ }
1702
+ }
1703
+ /** Reads a yes/no answer: an empty answer gives `defaultYes`, `y` and `yes` (any case) give true,
1704
+ * anything else gives false. */
1705
+ function yes(answer, defaultYes) {
1706
+ const normalized = answer.trim().toLowerCase();
1707
+ if (normalized === "") return defaultYes;
1708
+ return normalized === "y" || normalized === "yes";
1709
+ }
1710
+ // src/local.ts
1711
+ /** The local server `init` starts when none answers (D-AO-11): `cetra serve` if it is on PATH,
1712
+ * else Docker, else install steps. The server's first start creates the admin from the
1713
+ * `CETRA_INIT_*` variables; the generated password is used once, by `passwordSignIn`. */
1714
+ const DEFAULT_ADMIN_EMAIL = "admin@cetra.local";
1715
+ const CONTAINER = "cetra-local";
1716
+ const IMAGE = `ghcr.io/cetra-ai/cetra:${VERSION}`;
1717
+ const READY_TIMEOUT_MS = 3e4;
1718
+ const READY_POLL_MS = 500;
1719
+ const READY_CHECK_MS = 2e3;
1720
+ const TOKEN_LIFETIME_MS = 7776e6;
1721
+ const PASSWORD_LENGTH = 24;
1722
+ const PASSWORD_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
1723
+ const INSTALL_HINT = "Install cetra: curl -fsSL https://github.com/cetra-ai/cetra/releases/latest/download/install.sh | sh";
1724
+ const DOCKER_NOT_STARTED = `cetra did not start; see docker logs ${CONTAINER}`;
1725
+ /** Whether the URL points at this machine: localhost, 127.0.0.0/8 or [::1] (URL keeps the brackets). */
1726
+ function isLoopback(url) {
1727
+ const host = url.hostname;
1728
+ return host === "localhost" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host) || host === "[::1]";
1729
+ }
1730
+ /** The server URL a local start uses: `http://localhost:<port>`, whatever loopback spelling was typed.
1731
+ * The server only speaks plain http, and a port of 80 (or none, which is 80) reads as the default
1732
+ * port, so both are refused. */
1733
+ function localServer(url) {
1734
+ if (url.protocol !== "http:") throw new CliError("a local server is started over http; use an http:// --url", Exit.Usage);
1735
+ if (url.port === "") throw new CliError("--url needs an explicit port other than 80 for a local server", Exit.Usage);
1736
+ return `http://localhost:${url.port}`;
1737
+ }
1738
+ /** Whether the server answers `GET /readyz` with 200 within two seconds. Never throws. */
1739
+ async function isReady(server) {
1740
+ try {
1741
+ const response = await fetch(`${server}/readyz`, {
1742
+ redirect: "manual",
1743
+ signal: AbortSignal.timeout(READY_CHECK_MS)
1744
+ });
1745
+ const ready = response.status === 200;
1746
+ await response.text();
1747
+ return ready;
1748
+ } catch {
1749
+ return false;
1750
+ }
1751
+ }
1752
+ /** The local data directory of the server, as the platform's data dir with `cetra/local` added.
1753
+ * Linux: `$XDG_DATA_HOME` when absolute, else `~/.local/share`; macOS: `~/Library/Application
1754
+ * Support`; Windows: `%LOCALAPPDATA%`. `platform` and `home` are parameters so tests can check
1755
+ * every platform. */
1756
+ function localDataDir(env, platform = process.platform, home = homedir()) {
1757
+ if (platform === "win32") {
1758
+ const local = env.LOCALAPPDATA;
1759
+ if (local === void 0 || local === "") throw new CliError("could not find the data directory", Exit.Error);
1760
+ return win32.join(local, "cetra", "local");
1761
+ }
1762
+ if (platform === "darwin") return posix.join(home, "Library", "Application Support", "cetra", "local");
1763
+ const xdg = env.XDG_DATA_HOME;
1764
+ const base = xdg !== void 0 && posix.isAbsolute(xdg) ? xdg : posix.join(home, ".local", "share");
1765
+ return posix.join(base, "cetra", "local");
1766
+ }
1767
+ /** Whether the text is an email the server accepts: one `@`, a local part of 1 to 64 characters,
1768
+ * a domain with a `.` and no empty label, no whitespace, at most 254 characters. */
1769
+ function isEmail(text) {
1770
+ if (text.length > 254 || /\s/.test(text)) return false;
1771
+ const parts = text.split("@");
1772
+ if (parts.length !== 2) return false;
1773
+ const local = parts[0] ?? "";
1774
+ const domain = parts[1] ?? "";
1775
+ if (local.length < 1 || local.length > 64) return false;
1776
+ if (!domain.includes(".")) return false;
1777
+ return domain.split(".").every((label) => label !== "");
1778
+ }
1779
+ /** A random password of 24 letters and digits, from `crypto.randomInt`. */
1780
+ function generatedPassword() {
1781
+ let password = "";
1782
+ for (let i = 0; i < PASSWORD_LENGTH; i += 1) password += PASSWORD_ALPHABET.charAt(randomInt(62));
1783
+ return password;
1784
+ }
1785
+ /** The `cetra serve` config of a local start. The data dir is a TOML basic string: `\` and `"`
1786
+ * are escaped. Every listener is on 127.0.0.1. */
1787
+ function configToml(dataDir, port) {
1788
+ return [
1789
+ `data_dir = "${dataDir.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`,
1790
+ `public_url = "http://localhost:${port}"`,
1791
+ `http_addr = "127.0.0.1:${port}"`,
1792
+ "otlp_http_addr = \"127.0.0.1:4318\"",
1793
+ "grpc_addr = \"127.0.0.1:4317\"",
1794
+ ""
1795
+ ].join("\n");
1796
+ }
1797
+ /** Starts the local server when none answers at `url`, and waits until it is ready (30 s). A
1798
+ * first start that fails removes what it created, so the next run is a first start again. */
1799
+ async function startLocal(url, dir, options) {
1800
+ const deps = options.deps ?? {};
1801
+ const server = localServer(url);
1802
+ const port = Number(url.port);
1803
+ const binary = (await run(deps, "cetra", ["version"])).ok;
1804
+ const docker = binary ? false : (await run(deps, "docker", ["version"])).ok;
1805
+ if (!binary && !docker) throw new CliError(`no cetra server at ${server}, and neither cetra nor docker is installed. ${INSTALL_HINT}`, Exit.Unreachable);
1806
+ if (!options.yes && !interactive()) throw new CliError(`no cetra server at ${server}; pass --yes to start one`, Exit.Unreachable);
1807
+ if (!options.yes) {
1808
+ if (!yes(await ask(`No cetra server at ${server}. Start one with ${binary ? "`cetra serve`" : "Docker"}? [Y/n] `, ""), true)) throw new CliError(`no cetra server at ${server}`, Exit.Unreachable);
1809
+ }
1810
+ if (binary) return startBinary({
1811
+ server,
1812
+ port,
1813
+ dir,
1814
+ options,
1815
+ deps
1816
+ });
1817
+ return startDocker({
1818
+ server,
1819
+ port,
1820
+ dir,
1821
+ options,
1822
+ deps
1823
+ });
1824
+ }
1825
+ /** The `cetra serve` path: a detached child with its output in `server.log`. */
1826
+ async function startBinary(context) {
1827
+ const { server, port, dir, options, deps } = context;
1828
+ const dataDir = localDataDir(options.io.env);
1829
+ const firstStart = !await exists$1(join(dataDir, "meta.db"));
1830
+ const admin = firstStart ? await adminAnswers(options.yes, dir) : void 0;
1831
+ const toml = join(dirname(dataDir), "local.toml");
1832
+ const log = join(dataDir, "server.log");
1833
+ let child;
1834
+ try {
1835
+ await mkdir(dataDir, {
1836
+ recursive: true,
1837
+ mode: 448
1838
+ });
1839
+ if (process.platform !== "win32") await chmod(dataDir, 448);
1840
+ if (firstStart || !await configKeepsPort(toml, port)) await writeFile(toml, configToml(dataDir, port), "utf8");
1841
+ const fd = openSync(log, "a", 384);
1842
+ let spawned;
1843
+ try {
1844
+ spawned = (deps.spawn ?? spawn)("cetra", [
1845
+ "serve",
1846
+ "--config",
1847
+ toml
1848
+ ], {
1849
+ detached: true,
1850
+ stdio: [
1851
+ "ignore",
1852
+ fd,
1853
+ fd
1854
+ ],
1855
+ env: childEnvironment(admin?.variables)
1856
+ });
1857
+ } finally {
1858
+ closeSync(fd);
1859
+ }
1860
+ child = spawned;
1861
+ let spawnFailed = false;
1862
+ spawned.on("error", () => {
1863
+ spawnFailed = true;
1864
+ });
1865
+ spawned.unref();
1866
+ if (spawned.pid !== void 0) await writeFile(join(dataDir, "server.pid"), `${spawned.pid}\n`);
1867
+ await waitReady(server, deps, () => spawnFailed, `cetra did not start; see ${log} (another program may use port ${port}, 4317 or 4318)`);
1868
+ const pid = spawned.pid;
1869
+ if (pid === void 0) throw new CliError(`cetra did not start; see ${log}`, Exit.Unreachable);
1870
+ return {
1871
+ firstStart,
1872
+ server,
1873
+ stop: `kill ${pid}`,
1874
+ start: `cetra serve --config ${toml}`,
1875
+ ...admin?.started
1876
+ };
1877
+ } catch (error) {
1878
+ if (firstStart) {
1879
+ killChild(child);
1880
+ await rm(dataDir, {
1881
+ recursive: true,
1882
+ force: true
1883
+ });
1884
+ }
1885
+ throw error;
1886
+ }
1887
+ }
1888
+ /** Whether the config file exists and listens on `port`. A missing or unreadable file is no. */
1889
+ async function configKeepsPort(path, port) {
1890
+ try {
1891
+ return (await readFile(path, "utf8")).split("\n").includes(`http_addr = "127.0.0.1:${port}"`);
1892
+ } catch {
1893
+ return false;
1894
+ }
1895
+ }
1896
+ /** Kills a first start's child before its data dir is removed. A child that has already exited
1897
+ * makes `process.kill` throw, which is ignored. */
1898
+ function killChild(child) {
1899
+ if (child?.pid === void 0) return;
1900
+ try {
1901
+ process.kill(child.pid);
1902
+ } catch {}
1903
+ }
1904
+ /** The Docker path: the existing `cetra-local` container, else a new one on the `cetra-local`
1905
+ * volume. The init values reach the container by name only (`-e NAME`); their values go in the
1906
+ * environment of the `docker` process, so they are not in the process list. */
1907
+ async function startDocker(context) {
1908
+ const { server, port, dir, options, deps } = context;
1909
+ if ((await run(deps, "docker", [
1910
+ "ps",
1911
+ "-a",
1912
+ "--filter",
1913
+ `name=^${CONTAINER}$`,
1914
+ "--format",
1915
+ "{{.Names}}"
1916
+ ])).stdout.split("\n").some((line) => line.trim() === CONTAINER)) {
1917
+ const started = await run(deps, "docker", ["start", CONTAINER]);
1918
+ if (!started.ok) throw new CliError(`docker could not start cetra: ${firstLine(started.stderr)}`, Exit.Unreachable);
1919
+ const hostPort = await publishedPort(deps, port);
1920
+ if (hostPort !== port) throw new CliError(`the cetra-local container listens on port ${hostPort}; run again with --url http://localhost:${hostPort}`, Exit.Usage);
1921
+ await waitReady(server, deps, () => false, DOCKER_NOT_STARTED);
1922
+ return {
1923
+ firstStart: false,
1924
+ server,
1925
+ stop: `docker stop ${CONTAINER}`,
1926
+ start: `docker start ${CONTAINER}`
1927
+ };
1928
+ }
1929
+ const firstStart = !(await run(deps, "docker", [
1930
+ "volume",
1931
+ "inspect",
1932
+ CONTAINER
1933
+ ])).ok;
1934
+ const admin = firstStart ? await adminAnswers(options.yes, dir) : void 0;
1935
+ const names = admin === void 0 ? [] : Object.keys(admin.variables);
1936
+ const args = [
1937
+ "run",
1938
+ "-d",
1939
+ "--name",
1940
+ CONTAINER,
1941
+ "-p",
1942
+ `127.0.0.1:${port}:8080`,
1943
+ "-p",
1944
+ "127.0.0.1:4317:4317",
1945
+ "-p",
1946
+ "127.0.0.1:4318:4318",
1947
+ "-v",
1948
+ `${CONTAINER}:/data`,
1949
+ "-e",
1950
+ `CETRA_PUBLIC_URL=${server}`
1951
+ ];
1952
+ for (const name of names) args.push("-e", name);
1953
+ args.push(IMAGE);
1954
+ const ran = await run(deps, "docker", args, childEnvironment(admin?.variables));
1955
+ if (!ran.ok) {
1956
+ if (firstStart) await cleanupContainer(deps);
1957
+ if (/pull access denied|not found|unauthorized/i.test(ran.stderr)) throw new CliError(`docker could not pull ${IMAGE} (the image is public from the first release); install the binary instead: curl -fsSL https://github.com/cetra-ai/cetra/releases/latest/download/install.sh | sh`, Exit.Unreachable);
1958
+ throw new CliError(`docker could not start cetra: ${firstLine(ran.stderr)}`, Exit.Unreachable);
1959
+ }
1960
+ try {
1961
+ await waitReady(server, deps, () => false, DOCKER_NOT_STARTED);
1962
+ } catch (error) {
1963
+ if (firstStart) await cleanupContainer(deps);
1964
+ throw error;
1965
+ }
1966
+ return {
1967
+ firstStart,
1968
+ server,
1969
+ stop: `docker stop ${CONTAINER}`,
1970
+ start: `docker start ${CONTAINER}`,
1971
+ ...admin?.started
1972
+ };
1973
+ }
1974
+ /** The first-start answers: the admin email (asked unless `--yes`, which takes the default) and a
1975
+ * generated password, with the `CETRA_INIT_*` values the child needs. */
1976
+ async function adminAnswers(yes, dir) {
1977
+ const answer = yes ? DEFAULT_ADMIN_EMAIL : await ask(`Admin email for the local server [${DEFAULT_ADMIN_EMAIL}]: `, DEFAULT_ADMIN_EMAIL);
1978
+ if (!isEmail(answer)) throw new CliError("invalid email", Exit.Usage);
1979
+ const password = generatedPassword();
1980
+ const name = basename(dir).slice(0, 100);
1981
+ return {
1982
+ variables: {
1983
+ CETRA_INIT_ADMIN_EMAIL: answer,
1984
+ CETRA_INIT_ADMIN_PASSWORD: password,
1985
+ CETRA_INIT_ORG: "local",
1986
+ CETRA_INIT_PROJECT: name === "" ? "default" : name
1987
+ },
1988
+ started: {
1989
+ email: answer,
1990
+ password
1991
+ }
1992
+ };
1993
+ }
1994
+ /** The child's environment: the parent's, without any inherited `CETRA_INIT_*` name, plus the
1995
+ * first-start values when there are some. */
1996
+ function childEnvironment(variables) {
1997
+ const env = { ...process.env };
1998
+ for (const name of Object.keys(env)) if (name.startsWith("CETRA_INIT_")) delete env[name];
1999
+ return {
2000
+ ...env,
2001
+ ...variables
2002
+ };
2003
+ }
2004
+ /** Polls `isReady` every 500 ms for up to 30 s. `failed` ends the wait at once (a spawn error);
2005
+ * both ends throw `message`. */
2006
+ async function waitReady(server, deps, failed, message) {
2007
+ const sleep = deps.sleep ?? defaultSleep;
2008
+ const now = deps.now ?? Date.now;
2009
+ const started = now();
2010
+ for (;;) {
2011
+ if (failed()) throw new CliError(message, Exit.Unreachable);
2012
+ if (await isReady(server)) return;
2013
+ if (now() - started >= READY_TIMEOUT_MS) throw new CliError(message, Exit.Unreachable);
2014
+ await sleep(READY_POLL_MS);
2015
+ }
2016
+ }
2017
+ /** The host port Docker publishes for the container's 8080, from `docker port`; `fallback` when
2018
+ * the answer has no port. */
2019
+ async function publishedPort(deps, fallback) {
2020
+ const answer = await run(deps, "docker", [
2021
+ "port",
2022
+ CONTAINER,
2023
+ "8080"
2024
+ ]);
2025
+ const match = /:(\d+)$/.exec(firstLine(answer.stdout));
2026
+ if (match === null || match[1] === void 0) return fallback;
2027
+ return Number(match[1]);
2028
+ }
2029
+ /** Removes a first start's container and volume. Errors are ignored: the start has already failed. */
2030
+ async function cleanupContainer(deps) {
2031
+ await run(deps, "docker", [
2032
+ "rm",
2033
+ "-f",
2034
+ CONTAINER
2035
+ ]);
2036
+ await run(deps, "docker", [
2037
+ "volume",
2038
+ "rm",
2039
+ CONTAINER
2040
+ ]);
2041
+ }
2042
+ /** Signs in to a local server with its password and creates the two secrets `init` writes: a
2043
+ * `read` personal token (90 days) and an `ingest` secret key on the first project of the first
2044
+ * organization. Every request carries `Origin: <server>`, which the server requires. */
2045
+ async function passwordSignIn(server, email, password, host) {
2046
+ const signIn = "could not sign in to the local server";
2047
+ const login = await requestJson("POST", `${server}/api/auth/login`, {
2048
+ body: {
2049
+ email,
2050
+ password
2051
+ },
2052
+ origin: server
2053
+ });
2054
+ if (login.status === 429) throw new CliError("the local server refused the sign-in for now; try again in a minute", Exit.SignIn);
2055
+ if (login.status !== 200) throw new CliError(signIn, Exit.SignIn);
2056
+ const cookie = sessionCookie(login.headers);
2057
+ if (cookie === void 0) throw new CliError(signIn, Exit.SignIn);
2058
+ const me = await requestJson("GET", `${server}/api/auth/me`, {
2059
+ cookie,
2060
+ origin: server
2061
+ });
2062
+ if (me.status !== 200) throw new CliError(signIn, Exit.SignIn);
2063
+ const org = firstOrganization(me.body);
2064
+ if (org === void 0) throw new CliError("the local server has no organization", Exit.SignIn);
2065
+ const projects = await requestJson("GET", `${server}/api/v1/orgs/${encodeURIComponent(org)}/projects?limit=1000`, {
2066
+ cookie,
2067
+ origin: server
2068
+ });
2069
+ if (projects.status !== 200) throw new CliError(signIn, Exit.SignIn);
2070
+ const project = firstProject(projects.body);
2071
+ if (project === void 0) throw new CliError("the local server has no project", Exit.SignIn);
2072
+ const name = host === void 0 ? "CLI init" : `CLI init on ${host}`;
2073
+ const expires = new Date(Date.now() + TOKEN_LIFETIME_MS).toISOString();
2074
+ const token = await requestJson("POST", `${server}/api/v1/me/tokens`, {
2075
+ body: {
2076
+ name,
2077
+ scopes: ["read"],
2078
+ expires_at: expires
2079
+ },
2080
+ cookie,
2081
+ origin: server
2082
+ });
2083
+ if (token.status !== 201) throw new CliError(problemMessage(token.status, token.body, server), Exit.SignIn);
2084
+ const key = await requestJson("POST", `${server}/api/v1/projects/${encodeURIComponent(`${org}/${project.slug}`)}/api-keys`, {
2085
+ body: {
2086
+ kind: "secret",
2087
+ name,
2088
+ scopes: ["ingest"]
2089
+ },
2090
+ cookie,
2091
+ origin: server
2092
+ });
2093
+ if (key.status !== 201) throw new CliError(problemMessage(key.status, key.body, server), Exit.SignIn);
2094
+ await requestJson("POST", `${server}/api/auth/logout`, {
2095
+ cookie,
2096
+ origin: server
2097
+ }).catch(() => void 0);
2098
+ const tokenSecret = secretOf(token.body);
2099
+ const keySecret = secretOf(key.body);
2100
+ if (tokenSecret === void 0 || keySecret === void 0 || !isPersonalToken(tokenSecret) || !isSecretKey(keySecret)) throw new CliError("the server returned an invalid grant", Exit.SignIn);
2101
+ return {
2102
+ token: tokenSecret,
2103
+ key: keySecret,
2104
+ org,
2105
+ project: project.slug,
2106
+ projectId: project.id
2107
+ };
2108
+ }
2109
+ /** The `cetra_session=<value>` pair of the login answer, as a `Cookie` header. */
2110
+ function sessionCookie(headers) {
2111
+ for (const line of headers.getSetCookie()) {
2112
+ const pair = (line.split(";")[0] ?? "").trim();
2113
+ if (pair.startsWith("cetra_session=") && pair.length > 14) return pair;
2114
+ }
2115
+ }
2116
+ /** The slug of the first organization that is not the demo one. A slug the server's rule refuses
2117
+ * is an invalid grant: the slug is written into the prompt and the env file. */
2118
+ function firstOrganization(body) {
2119
+ if (!isRecord$1(body) || !Array.isArray(body.orgs)) return void 0;
2120
+ for (const org of body.orgs) if (isRecord$1(org) && org.demo === false && typeof org.slug === "string") {
2121
+ if (!isSlug(org.slug)) throw new CliError(INVALID_GRANT, Exit.SignIn);
2122
+ return org.slug;
2123
+ }
2124
+ }
2125
+ /** The id and slug of the first project of a project page; undefined when the page is empty. The
2126
+ * id must be a UUID and the slug must follow the server's rule, as for the device grant. */
2127
+ function firstProject(body) {
2128
+ if (!isRecord$1(body) || !Array.isArray(body.data)) return void 0;
2129
+ const first = body.data[0];
2130
+ if (first === void 0) return void 0;
2131
+ if (!isRecord$1(first) || typeof first.id !== "string" || !isUuid(first.id) || typeof first.slug !== "string" || !isSlug(first.slug)) throw new CliError(INVALID_GRANT, Exit.SignIn);
2132
+ return {
2133
+ id: first.id,
2134
+ slug: first.slug
2135
+ };
2136
+ }
2137
+ function secretOf(body) {
2138
+ if (!isRecord$1(body) || typeof body.secret !== "string") return void 0;
2139
+ return body.secret;
2140
+ }
2141
+ function isRecord$1(value) {
2142
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2143
+ }
2144
+ /** The first line of a command's output, trimmed. */
2145
+ function firstLine(text) {
2146
+ return (text.split("\n")[0] ?? "").trim();
2147
+ }
2148
+ /** Runs a command without a shell, through `deps.execFile` when given. `ok` is false for a missing
2149
+ * program and for a non-zero exit. */
2150
+ function run(deps, file, args, env = process.env) {
2151
+ const exec = deps.execFile ?? execFile;
2152
+ return new Promise((resolve) => {
2153
+ exec(file, args, {
2154
+ env,
2155
+ encoding: "utf8"
2156
+ }, (error, stdout, stderr) => {
2157
+ resolve({
2158
+ ok: error === null,
2159
+ stdout: String(stdout),
2160
+ stderr: String(stderr)
2161
+ });
2162
+ });
2163
+ });
2164
+ }
2165
+ async function exists$1(path) {
2166
+ try {
2167
+ await access(path);
2168
+ return true;
2169
+ } catch {
2170
+ return false;
2171
+ }
2172
+ }
2173
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2174
+ // src/prompt.ts
2175
+ /** The check step's statement. It is the same as skills/cetra/SKILL.md's step 5 (a test checks it). */
2176
+ const CHECK_QUERY = "SELECT trace_id, name, start_time, span_count, llm_count, error_count FROM traces ORDER BY start_time DESC LIMIT 5";
2177
+ /** The text `init` prints for the coding agent. */
2178
+ function agentPrompt(values) {
2179
+ return [
2180
+ "Add cetra tracing to this app.",
2181
+ "",
2182
+ values.skill ? "1. Read the cetra skill (.claude/skills/cetra or .agents/skills/cetra). If it is not there, read https://cetra.sh/llms.txt." : "1. Read https://cetra.sh/llms.txt.",
2183
+ `2. Find the app's language and LLM libraries, and install the cetra SDK with the matching extras or instrumentations. Call init once at startup. The API key and URL are CETRA_API_KEY and CETRA_BASE_URL in ${values.envFile}: load that file the way the app loads its settings. Never paste the key into code or chat.`,
2184
+ "3. Run the app, or its tests, once so that it makes at least one LLM call. Flush before exit in short scripts.",
2185
+ "4. Check that traces arrived:",
2186
+ ` npx @cetra-ai/cli query "${CHECK_QUERY}" --since 15m --json`,
2187
+ " If it returns no rows, follow the troubleshooting steps of the skill.",
2188
+ `5. Tell me what you changed, and give me this link: ${values.tracesUrl}`
2189
+ ].join("\n");
2190
+ }
2191
+ // src/skill.ts
2192
+ /** Where the skill goes, relative to the project root (D-AO-9): Claude Code and the Agent Skills
2193
+ * convention. */
2194
+ const SKILL_TARGETS = {
2195
+ claude: ".claude/skills/cetra",
2196
+ agents: ".agents/skills/cetra"
2197
+ };
2198
+ /** Written inside an installed skill: its presence says cetra-cli installed the directory. */
2199
+ const MARKER = ".cetra-skill";
2200
+ /** The skill shipped in the package: dist/skills/cetra next to the running bundle (dist/cli.js). */
2201
+ function bundledSkill() {
2202
+ return fileURLToPath(new URL("./skills/cetra/", import.meta.url));
2203
+ }
2204
+ /** Copies `source` into each target under `root` and writes the marker (the version and a
2205
+ * newline). A target that exists without the marker is left alone. The copy is built in a
2206
+ * sibling `<target>.tmp-<random>` directory, marker included, and only then put in place, so a
2207
+ * failed or interrupted install keeps the earlier one (and a missing source touches nothing). A
2208
+ * target that fails is skipped with its error message; this function does not throw. */
2209
+ async function installSkill(source, root, targets, version) {
2210
+ const installed = [];
2211
+ const skipped = [];
2212
+ for (const target of targets) {
2213
+ const path = join(root, SKILL_TARGETS[target]);
2214
+ if (await exists(path) && !await exists(join(path, ".cetra-skill"))) {
2215
+ skipped.push({
2216
+ path,
2217
+ reason: "not installed by cetra-cli; left alone"
2218
+ });
2219
+ continue;
2220
+ }
2221
+ const temporary = `${path}.tmp-${randomBytes(6).toString("hex")}`;
2222
+ try {
2223
+ await cp(source, temporary, { recursive: true });
2224
+ await writeFile(join(temporary, MARKER), `${version}\n`, "utf8");
2225
+ await rm(path, {
2226
+ recursive: true,
2227
+ force: true
2228
+ });
2229
+ await rename(temporary, path);
2230
+ installed.push(path);
2231
+ } catch (error) {
2232
+ await rm(temporary, {
2233
+ recursive: true,
2234
+ force: true
2235
+ }).catch(() => void 0);
2236
+ skipped.push({
2237
+ path,
2238
+ reason: error instanceof Error ? error.message : String(error)
2239
+ });
2240
+ }
2241
+ }
2242
+ return {
2243
+ installed,
2244
+ skipped
2245
+ };
2246
+ }
2247
+ /** The project root for the skill: the top of the git work tree holding `dir`, else `dir`. */
2248
+ async function skillRoot(dir) {
2249
+ return await gitTop(dir) ?? dir;
2250
+ }
2251
+ async function exists(path) {
2252
+ try {
2253
+ await stat(path);
2254
+ return true;
2255
+ } catch {
2256
+ return false;
2257
+ }
2258
+ }
2259
+ // src/init.ts
2260
+ const SUMMARY$2 = "Sign in, pick a project, write .env and install the cetra skill.";
2261
+ const CLOUD = "https://app.cetra.sh";
2262
+ const LINES$2 = [
2263
+ ["--url <URL>", "The server. Defaults to CETRA_URL, then the project link, then the cloud"],
2264
+ ["--project <org/project>", "Preselect the project on the approval page"],
2265
+ ["--dir <PATH>", "The project directory. Defaults to the current directory"],
2266
+ ["--env-file <PATH>", "The env file, relative to --dir. Defaults to .env"],
2267
+ ["--agents <LIST>", "Where the skill goes: claude, agents or both (default)"],
2268
+ ["--no-skill", "Do not install the skill"],
2269
+ ["--no-browser", "Print the sign-in URL and do not open a browser"],
2270
+ ["--yes", "Start a local server and replace an existing API key without asking"],
2271
+ ["--json", "Print one JSON object on stdout"],
2272
+ ["-h, --help", "Show this help"]
2273
+ ];
2274
+ const NOTE = "--project is ignored when init starts a local server: a first start has one project.";
2275
+ /** `cetra-cli init` (design § `@cetra-ai/cli` § `init`): choose the server, start a local one if
2276
+ * needed, sign in, save the token, write `.env`, the project link and the skill, and print the
2277
+ * agent prompt. Human text goes to stderr; `--json` is the only thing on stdout. */
2278
+ async function init(args, io, deps = {}) {
2279
+ const { values, positionals } = parseOptions(args, {
2280
+ url: { type: "string" },
2281
+ project: { type: "string" },
2282
+ dir: { type: "string" },
2283
+ "env-file": { type: "string" },
2284
+ agents: { type: "string" },
2285
+ "no-skill": { type: "boolean" },
2286
+ "no-browser": { type: "boolean" },
2287
+ yes: { type: "boolean" },
2288
+ json: { type: "boolean" },
2289
+ help: {
2290
+ type: "boolean",
2291
+ short: "h"
2292
+ }
2293
+ });
2294
+ if (values.help === true) {
2295
+ io.stderr(optionsHelp("init", SUMMARY$2, LINES$2));
2296
+ io.stderr(NOTE);
2297
+ return Exit.Ok;
2298
+ }
2299
+ if (positionals.length > 0) throw new CliError("init takes no positional arguments", Exit.Usage);
2300
+ const targets = skillTargets(values.agents, values["no-skill"] === true);
2301
+ const dir = await projectDirectory(values.dir, io.cwd);
2302
+ const envPath = resolve(dir, values["env-file"] ?? ".env");
2303
+ const noBrowser = values["no-browser"] === true;
2304
+ const yesToAll = values.yes === true;
2305
+ let server = serverUrl(await chosenServer(values.url, io.env, dir));
2306
+ checkEnvValue(server);
2307
+ let started;
2308
+ if (!await isReady(server)) {
2309
+ const url = new URL(server);
2310
+ if (!isLoopback(url)) throw new CliError(`no cetra server at ${server}`, Exit.Unreachable);
2311
+ started = await startLocal(url, dir, {
2312
+ yes: yesToAll,
2313
+ io,
2314
+ deps
2315
+ });
2316
+ server = started.server;
2317
+ }
2318
+ const signedIn = started?.firstStart === true && started.email !== void 0 && started.password !== void 0 ? await signInWithPassword(server, started.email, started.password) : await signInWithDevice(server, values.project, noBrowser, io, deps);
2319
+ await saveToken(credentialsPath(io.env), signedIn.server, signedIn.token);
2320
+ const envName = basename(envPath);
2321
+ const existing = await readEnvFile(envPath);
2322
+ const assignments = { CETRA_BASE_URL: signedIn.grantServer };
2323
+ if (existing !== void 0 && readVariable(existing, "CETRA_API_KEY") !== void 0) {
2324
+ if (yesToAll || interactive() && yes(await ask(`Replace the CETRA_API_KEY in ${envName}? [y/N] `, ""), false)) assignments.CETRA_API_KEY = signedIn.key;
2325
+ else io.stderr(`kept the existing CETRA_API_KEY in ${envName}`);
2326
+ } else assignments.CETRA_API_KEY = signedIn.key;
2327
+ await writeEnvFile(envPath, setVariables(existing, assignments));
2328
+ if (await ignoreInGit(dir, envPath)) io.stderr(`Added ${displayPath(dir, envPath)} to .gitignore.`);
2329
+ const linkPath = await writeLink(dir, {
2330
+ server: signedIn.server,
2331
+ org: signedIn.org,
2332
+ project: signedIn.project,
2333
+ project_id: signedIn.projectId
2334
+ });
2335
+ const skills = [];
2336
+ if (targets.length > 0) {
2337
+ const result = await installSkill(deps.skillSource ?? bundledSkill(), await skillRoot(dir), targets, VERSION);
2338
+ for (const path of result.installed) {
2339
+ skills.push(path);
2340
+ io.stderr(`Installed the cetra skill in ${path}`);
2341
+ }
2342
+ for (const skip of result.skipped) io.stderr(`warning: ${skip.path}: ${skip.reason}`);
2343
+ }
2344
+ const project = `${signedIn.org}/${signedIn.project}`;
2345
+ const tracesUrl = `${signedIn.grantServer}/${project}/traces`;
2346
+ const prompt = agentPrompt({
2347
+ envFile: displayPath(dir, envPath),
2348
+ tracesUrl,
2349
+ skill: values["no-skill"] !== true
2350
+ });
2351
+ io.stderr("");
2352
+ io.stderr("Paste this prompt into your coding agent:");
2353
+ io.stderr("");
2354
+ for (const line of prompt.split("\n")) io.stderr(line);
2355
+ io.stderr("");
2356
+ io.stderr(`Traces: ${tracesUrl}`);
2357
+ if (started !== void 0) {
2358
+ io.stderr(`Stop the server: ${started.stop}`);
2359
+ io.stderr(`Start it again: ${started.start}`);
2360
+ if (started.firstStart && started.email !== void 0 && started.password !== void 0) {
2361
+ io.stderr(`UI: ${started.server}`);
2362
+ io.stderr(`Admin: ${started.email}`);
2363
+ if (process.stderr.isTTY === true) io.stderr(`Password: ${started.password}`);
2364
+ else io.stderr(`The admin password is in no file; reset it with cetra admin reset-password ${started.email}`);
2365
+ }
2366
+ }
2367
+ if (values.json === true) io.stdout(JSON.stringify({
2368
+ server: signedIn.grantServer,
2369
+ project,
2370
+ env_file: envPath,
2371
+ link_file: linkPath,
2372
+ skills,
2373
+ prompt,
2374
+ traces_url: tracesUrl
2375
+ }));
2376
+ return Exit.Ok;
2377
+ }
2378
+ /** The skill targets: `--agents` (a comma list, default both), none with `--no-skill`. */
2379
+ function skillTargets(list, noSkill) {
2380
+ if (list !== void 0 && noSkill) throw new CliError("--agents and --no-skill cannot be combined", Exit.Usage);
2381
+ if (noSkill) return [];
2382
+ if (list === void 0) return Object.keys(SKILL_TARGETS).filter(isTarget);
2383
+ const picked = [];
2384
+ for (const name of list.split(",").map((part) => part.trim())) {
2385
+ if (!isTarget(name)) throw new CliError(`unknown agent ${name}; use claude or agents`, Exit.Usage);
2386
+ if (!picked.includes(name)) picked.push(name);
2387
+ }
2388
+ return picked;
2389
+ }
2390
+ function isTarget(name) {
2391
+ return Object.hasOwn(SKILL_TARGETS, name);
2392
+ }
2393
+ /** The project directory: `--dir` relative to the working directory, default the working directory.
2394
+ * It must be an existing directory. */
2395
+ async function projectDirectory(flag, cwd) {
2396
+ const dir = resolve(cwd, flag ?? ".");
2397
+ const info = await stat(dir).catch(() => void 0);
2398
+ if (info === void 0 || !info.isDirectory()) throw new CliError("--dir must be an existing directory", Exit.Usage);
2399
+ return dir;
2400
+ }
2401
+ /** The server URL before any sign-in: `--url`, else `CETRA_URL`, else the project link, else the
2402
+ * cloud. An environment value that is empty or only spaces counts as unset. */
2403
+ async function chosenServer(flag, env, dir) {
2404
+ const given = flag ?? nonEmpty$2(env.CETRA_URL);
2405
+ if (given !== void 0) return given;
2406
+ const link = await findLink(dir);
2407
+ if (link !== void 0) return linkServer$1(link);
2408
+ return CLOUD;
2409
+ }
2410
+ /** The link's server, checked as `serverUrl` checks it; a bad one makes the link invalid. */
2411
+ function linkServer$1(link) {
2412
+ try {
2413
+ return serverUrl(link.server);
2414
+ } catch {
2415
+ throw new CliError(`${LINK_FILE} is invalid`);
2416
+ }
2417
+ }
2418
+ /** The server URL must be a valid `.env` value, so that nothing fails after the secrets exist. */
2419
+ function checkEnvValue(server) {
2420
+ try {
2421
+ setVariables(void 0, { CETRA_BASE_URL: server });
2422
+ } catch {
2423
+ throw new CliError("the server URL cannot be written to the env file", Exit.Usage);
2424
+ }
2425
+ }
2426
+ /** Signs in to a local first start with its generated admin password. The password is shown only
2427
+ * after a successful sign-in, so a failure names the reset command instead. */
2428
+ async function signInWithPassword(server, email, password) {
2429
+ let local;
2430
+ try {
2431
+ local = await passwordSignIn(server, email, password, localHost());
2432
+ } catch (error) {
2433
+ if (!(error instanceof CliError)) throw error;
2434
+ throw new CliError(`${error.message}; the generated admin password is not kept, reset it with \`cetra admin reset-password ${email}\``, error.code);
2435
+ }
2436
+ return {
2437
+ server,
2438
+ grantServer: server,
2439
+ token: local.token,
2440
+ key: local.key,
2441
+ org: local.org,
2442
+ project: local.project,
2443
+ projectId: local.projectId
2444
+ };
2445
+ }
2446
+ /** Signs in with the device flow (`purpose: init`); the grant brings the project and the key. */
2447
+ async function signInWithDevice(server, project, noBrowser, io, deps) {
2448
+ const { grant, server: answering } = await deviceSignIn({
2449
+ server,
2450
+ purpose: "init",
2451
+ noBrowser,
2452
+ project,
2453
+ stderr: io.stderr,
2454
+ deps
2455
+ });
2456
+ const granted = grant.project;
2457
+ const key = grant.ingest_key;
2458
+ if (granted === void 0 || key === void 0) throw new CliError("the server returned an invalid grant", Exit.SignIn);
2459
+ return {
2460
+ server: answering,
2461
+ grantServer: grant.server,
2462
+ token: grant.token,
2463
+ key,
2464
+ org: granted.org_slug,
2465
+ project: granted.slug,
2466
+ projectId: granted.id
2467
+ };
2468
+ }
2469
+ /** The env file's text, or undefined when it does not exist. Any other read error stops `init`
2470
+ * before the file could be overwritten. */
2471
+ async function readEnvFile(path) {
2472
+ try {
2473
+ return await readFile(path, "utf8");
2474
+ } catch (error) {
2475
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return void 0;
2476
+ throw new CliError(`could not write ${basename(path)}`, Exit.Write);
2477
+ }
2478
+ }
2479
+ /** A path relative to the project directory, with `/` separators; the absolute path when it lies
2480
+ * outside the directory. */
2481
+ function displayPath(dir, path) {
2482
+ const relativePath = relative(dir, path);
2483
+ if (relativePath === "" || isAbsolute(relativePath) || relativePath.split(sep)[0] === "..") return path;
2484
+ return relativePath.split(sep).join("/");
2485
+ }
2486
+ /** An environment value that is empty or only spaces counts as unset. */
2487
+ function nonEmpty$2(value) {
2488
+ return value === void 0 || value.trim() === "" ? void 0 : value;
2489
+ }
2490
+ // src/login.ts
2491
+ const SUMMARY$1 = "Sign in again and save a new token.";
2492
+ const LINES$1 = [
2493
+ ["--url <URL>", "The server. Defaults to CETRA_URL, then the only saved server"],
2494
+ ["--no-browser", "Print the sign-in URL and do not open a browser"],
2495
+ ["--json", "Print {\"server\": ...} on stdout"],
2496
+ ["-h, --help", "Show this help"]
2497
+ ];
2498
+ /** `cetra-cli login`: the device flow, a check of the token with `/api/auth/me`, then the token
2499
+ * is saved in the shared credentials file. Human text goes to stderr. */
2500
+ async function login(args, io, deps = {}) {
2501
+ const { values, positionals } = parseOptions(args, {
2502
+ url: { type: "string" },
2503
+ "no-browser": { type: "boolean" },
2504
+ json: { type: "boolean" },
2505
+ help: {
2506
+ type: "boolean",
2507
+ short: "h"
2508
+ }
2509
+ });
2510
+ if (values.help === true) {
2511
+ io.stderr(optionsHelp("login", SUMMARY$1, LINES$1));
2512
+ return Exit.Ok;
2513
+ }
2514
+ if (positionals.length > 0) throw new CliError("login takes no positional arguments", Exit.Usage);
2515
+ const credentials = credentialsPath(io.env);
2516
+ const flag = values.url ?? nonEmpty$1(io.env.CETRA_URL);
2517
+ const { grant, server: answering } = await deviceSignIn({
2518
+ server: flag !== void 0 ? serverUrl(flag) : chosenServer$1(await loadCredentials(credentials)),
2519
+ purpose: "login",
2520
+ noBrowser: values["no-browser"] === true,
2521
+ stderr: io.stderr,
2522
+ deps
2523
+ });
2524
+ const me = await requestJson("GET", `${answering}/api/auth/me`, { token: grant.token });
2525
+ if (me.status < 200 || me.status > 299) throw new CliError("the server rejected the token", Exit.SignIn);
2526
+ await saveToken(credentials, answering, grant.token);
2527
+ io.stderr(`Signed in to ${answering}. The token expires in 90 days.`);
2528
+ if (values.json === true) io.stdout(JSON.stringify({ server: answering }));
2529
+ return Exit.Ok;
2530
+ }
2531
+ /** An environment value that is empty or only spaces counts as unset. */
2532
+ function nonEmpty$1(value) {
2533
+ return value === void 0 || value.trim() === "" ? void 0 : value;
2534
+ }
2535
+ // src/since.ts
2536
+ const DURATION_ERROR = "--since expects a duration such as 30m, 24h or 7d";
2537
+ const UNIT_SECONDS = {
2538
+ s: 1,
2539
+ m: 60,
2540
+ h: 3600,
2541
+ d: 86400
2542
+ };
2543
+ /** An instant as RFC 3339 with nine fractional digits and `Z`, the form the Rust CLI sends. */
2544
+ function rfc3339Nanos(time) {
2545
+ return time.toISOString().replace(/\.(\d{3})Z$/, ".$1000000Z");
2546
+ }
2547
+ /** `[now - duration, now)` for `--since`, as the Rust `since_window`: the last character is the
2548
+ * unit (`s`, `m`, `h` or `d`), the rest is 1 to 9 digits with no leading `0` and no sign. A window
2549
+ * that starts before 1970-01-01 is refused. */
2550
+ function sinceWindow(text, now) {
2551
+ const unit = text.slice(-1);
2552
+ const digits = text.slice(0, -1);
2553
+ const multiplier = Object.hasOwn(UNIT_SECONDS, unit) ? UNIT_SECONDS[unit] : void 0;
2554
+ if (multiplier === void 0 || !/^[1-9][0-9]{0,8}$/.test(digits)) throw new CliError(DURATION_ERROR, Exit.Usage);
2555
+ const from = /* @__PURE__ */ new Date(now.getTime() - Number(digits) * multiplier * 1e3);
2556
+ if (from.getTime() < 0) throw new CliError(DURATION_ERROR, Exit.Usage);
2557
+ return {
2558
+ from: rfc3339Nanos(from),
2559
+ to: rfc3339Nanos(now)
2560
+ };
2561
+ }
2562
+ // src/table.ts
2563
+ /** Most characters a cell shows; a longer one keeps its first 59 characters and `…`. */
2564
+ const CELL_MAX_CHARS = 60;
2565
+ /** Characters, counted as code points (as Rust's `chars()` does). */
2566
+ function length(text) {
2567
+ return Array.from(text).length;
2568
+ }
2569
+ /** Every control character becomes one space; nothing else changes. */
2570
+ function clean(text) {
2571
+ return text.replace(CONTROL, " ");
2572
+ }
2573
+ function cut(text) {
2574
+ const points = Array.from(text);
2575
+ if (points.length <= CELL_MAX_CHARS) return text;
2576
+ return `${points.slice(0, 59).join("")}…`;
2577
+ }
2578
+ /** Cell text of one JSON value: `NULL` for null or a missing key, the raw text of a string,
2579
+ * compact JSON for an array or object. */
2580
+ function cellText(value) {
2581
+ if (value === null || value === void 0) return "NULL";
2582
+ if (typeof value === "string") return value;
2583
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
2584
+ return JSON.stringify(value);
2585
+ }
2586
+ /** A column is right-aligned when some row has a number in it and no row has a non-null value
2587
+ * that is not a number. */
2588
+ function isNumeric(rows, name) {
2589
+ let anyNumber = false;
2590
+ for (const row of rows) {
2591
+ const value = Object.hasOwn(row, name) ? row[name] : null;
2592
+ if (typeof value === "number") anyNumber = true;
2593
+ else if (value !== null && value !== void 0) return false;
2594
+ }
2595
+ return anyNumber;
2596
+ }
2597
+ /** An aligned table: a header line, a rule line, then one line per row, each ending in `\n`.
2598
+ * Columns are two spaces apart, trailing spaces are trimmed, and no columns gives "". */
2599
+ function renderTable(columns, rows) {
2600
+ if (columns.length === 0) return "";
2601
+ const right = columns.map((column) => isNumeric(rows, column.name));
2602
+ const headers = columns.map((column) => cut(clean(column.name)));
2603
+ const cells = rows.map((row) => columns.map((column) => cut(clean(cellText(Object.hasOwn(row, column.name) ? row[column.name] : null)))));
2604
+ const widths = columns.map((_, index) => {
2605
+ let width = length(headers[index] ?? "");
2606
+ for (const row of cells) width = Math.max(width, length(row[index] ?? ""));
2607
+ return width;
2608
+ });
2609
+ const line = (values) => {
2610
+ return `${values.map((value, index) => {
2611
+ const padding = " ".repeat(Math.max(0, (widths[index] ?? 0) - length(value)));
2612
+ return right[index] ? padding + value : value + padding;
2613
+ }).join(" ").replace(/ +$/, "")}\n`;
2614
+ };
2615
+ const rules = widths.map((width) => "-".repeat(width));
2616
+ return [
2617
+ line(headers),
2618
+ line(rules),
2619
+ ...cells.map(line)
2620
+ ].join("");
2621
+ }
2622
+ // src/query.ts
2623
+ const SUMMARY = "Run one SQL statement on the linked project.";
2624
+ const LINES = [
2625
+ ["--since <DURATION>", "The window ending now: 30m, 24h or 7d. Default 24h"],
2626
+ ["--from <TIME>", "The window start, RFC 3339. Needs --to"],
2627
+ ["--to <TIME>", "The window end (exclusive), RFC 3339. Needs --from"],
2628
+ ["--limit <N>", "Most rows, from 1 to 10000. Default 100"],
2629
+ ["--json", "Print {columns, rows, truncated} on stdout"],
2630
+ ["--url <URL>", "The server. Defaults to CETRA_URL, then the project link"],
2631
+ ["--project <PROJECT>", "org/project. Defaults to CETRA_PROJECT, then the project link"],
2632
+ ["-h, --help", "Show this help"]
2633
+ ];
2634
+ /** `cetra-cli query "<sql>"`: one statement on the linked project, as a table or as JSON.
2635
+ * Human text goes to stderr; results go to stdout. */
2636
+ async function query(args, io, deps = {}) {
2637
+ const { values, positionals } = parseOptions(args, {
2638
+ since: { type: "string" },
2639
+ from: { type: "string" },
2640
+ to: { type: "string" },
2641
+ limit: { type: "string" },
2642
+ json: { type: "boolean" },
2643
+ url: { type: "string" },
2644
+ project: { type: "string" },
2645
+ help: {
2646
+ type: "boolean",
2647
+ short: "h"
2648
+ }
2649
+ });
2650
+ if (values.help === true) {
2651
+ io.stderr(optionsHelp("query", SUMMARY, LINES));
2652
+ return Exit.Ok;
2653
+ }
2654
+ if (positionals.length !== 1) throw new CliError("query takes one SQL statement in quotes", Exit.Usage);
2655
+ const statement = positionals[0] ?? "";
2656
+ if (statement.trim() === "") throw new CliError("the query is empty", Exit.Usage);
2657
+ const now = new Date(deps.now?.() ?? Date.now());
2658
+ let window;
2659
+ if (values.from !== void 0 || values.to !== void 0) {
2660
+ if (values.from === void 0 || values.to === void 0) throw new CliError("--from and --to need each other", Exit.Usage);
2661
+ if (values.since !== void 0) throw new CliError("--since cannot be combined with --from and --to", Exit.Usage);
2662
+ window = {
2663
+ from: values.from,
2664
+ to: values.to
2665
+ };
2666
+ } else window = sinceWindow(values.since ?? "24h", now);
2667
+ const limit = parseLimit(values.limit);
2668
+ const flagServer = values.url ?? nonEmpty(io.env.CETRA_URL);
2669
+ const flagProject = values.project ?? nonEmpty(io.env.CETRA_PROJECT);
2670
+ const link = flagServer === void 0 || flagProject === void 0 ? await findLink(io.cwd) : void 0;
2671
+ let server;
2672
+ if (flagServer !== void 0) server = serverUrl(flagServer);
2673
+ else if (link !== void 0) server = linkServer(link);
2674
+ else throw new CliError("no server: run `cetra-cli init`, or pass --url", Exit.Usage);
2675
+ let project;
2676
+ if (flagProject !== void 0) project = flagProject;
2677
+ else if (link !== void 0) project = `${link.org}/${link.project}`;
2678
+ else throw new CliError("no project: run `cetra-cli init`, or pass --project", Exit.Usage);
2679
+ let token = flagServer !== void 0 ? nonEmpty(io.env.CETRA_TOKEN) : void 0;
2680
+ if (token === void 0) token = (await loadCredentials(credentialsPath(io.env))).get(server);
2681
+ if (token === void 0) throw new CliError(`no saved token for ${server}; run \`cetra-cli login --url ${server}\``, Exit.SignIn);
2682
+ const answer = await requestJson("POST", `${server}/api/v1/projects/${encodeURIComponent(project)}/sql`, {
2683
+ body: {
2684
+ query: statement,
2685
+ from: window.from,
2686
+ to: window.to,
2687
+ limit
2688
+ },
2689
+ token,
2690
+ timeoutMs: 9e4
2691
+ });
2692
+ if (answer.status < 200 || answer.status > 299) {
2693
+ const code = answer.status === 401 ? Exit.SignIn : Exit.Query;
2694
+ throw new CliError(problemMessage(answer.status, answer.body, server), code);
2695
+ }
2696
+ const result = sqlResult(answer.body);
2697
+ if (values.json === true) {
2698
+ io.stdout(JSON.stringify(result));
2699
+ return Exit.Ok;
2700
+ }
2701
+ const table = renderTable(result.columns, result.rows);
2702
+ if (table !== "") for (const line of table.slice(0, -1).split("\n")) io.stdout(line);
2703
+ const count = result.rows.length;
2704
+ const rows = count === 1 ? "1 row" : `${count} rows`;
2705
+ io.stderr(result.truncated ? `${rows}; more rows matched, raise --limit` : rows);
2706
+ return Exit.Ok;
2707
+ }
2708
+ /** `--limit` (or the default 100): a whole number from 1 to 10000. */
2709
+ function parseLimit(text) {
2710
+ if (text === void 0) return 100;
2711
+ const value = /^[0-9]+$/.test(text) ? Number(text) : NaN;
2712
+ if (!(value >= 1 && value <= 1e4)) throw new CliError("--limit expects a whole number from 1 to 10000", Exit.Usage);
2713
+ return value;
2714
+ }
2715
+ /** The server a project link names, checked as `serverUrl` does; a bad one makes the link invalid. */
2716
+ function linkServer(link) {
2717
+ try {
2718
+ return serverUrl(link.server);
2719
+ } catch {
2720
+ throw new CliError(`${LINK_FILE} is invalid`);
2721
+ }
2722
+ }
2723
+ /** The answer's `columns`, `rows` and `truncated`; anything else is an invalid response. */
2724
+ function sqlResult(body) {
2725
+ const invalid = () => new CliError("the server sent an invalid response");
2726
+ if (!isRecord(body) || !Array.isArray(body.columns) || !Array.isArray(body.rows) || typeof body.truncated !== "boolean") throw invalid();
2727
+ const columns = [];
2728
+ for (const column of body.columns) {
2729
+ if (!isRecord(column) || typeof column.name !== "string" || typeof column.type !== "string") throw invalid();
2730
+ columns.push({
2731
+ name: column.name,
2732
+ type: column.type
2733
+ });
2734
+ }
2735
+ const rows = [];
2736
+ for (const row of body.rows) {
2737
+ if (!isRecord(row)) throw invalid();
2738
+ rows.push(row);
2739
+ }
2740
+ return {
2741
+ columns,
2742
+ rows,
2743
+ truncated: body.truncated
2744
+ };
2745
+ }
2746
+ function isRecord(value) {
2747
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2748
+ }
2749
+ /** An environment value that is empty or only spaces counts as unset. */
2750
+ function nonEmpty(value) {
2751
+ return value === void 0 || value.trim() === "" ? void 0 : value;
2752
+ }
2753
+ // src/cli.ts
2754
+ /** Commands register here. */
2755
+ const COMMANDS = {
2756
+ init: (args, io) => init(args, io),
2757
+ login: (args, io) => login(args, io),
2758
+ query: (args, io) => query(args, io)
2759
+ };
2760
+ const USAGE = `Usage: cetra-cli <command> [options]
2761
+
2762
+ Commands:
2763
+ init Sign in, pick a project, write .env and install the cetra skill
2764
+ query Run a SQL query on the linked project
2765
+ login Sign in again and save a new token
2766
+
2767
+ Run \`cetra-cli <command> --help\` for a command's options.`;
2768
+ function message(error) {
2769
+ return error instanceof Error ? error.message : String(error);
2770
+ }
2771
+ async function main(argv, io, commands = COMMANDS) {
2772
+ const [first, ...rest] = argv;
2773
+ if (first === void 0) {
2774
+ io.stderr(USAGE);
2775
+ return Exit.Usage;
2776
+ }
2777
+ if (first === "--version") {
2778
+ io.stdout(VERSION);
2779
+ return Exit.Ok;
2780
+ }
2781
+ if (first === "--help" || first === "-h") {
2782
+ io.stderr(USAGE);
2783
+ return Exit.Ok;
2784
+ }
2785
+ if (first.startsWith("-")) {
2786
+ io.stderr(`cetra-cli: unknown option ${first}`);
2787
+ io.stderr(USAGE);
2788
+ return Exit.Usage;
2789
+ }
2790
+ const command = Object.hasOwn(commands, first) ? commands[first] : void 0;
2791
+ if (command === void 0) {
2792
+ io.stderr(`cetra-cli: unknown command ${first}`);
2793
+ io.stderr(USAGE);
2794
+ return Exit.Usage;
2795
+ }
2796
+ try {
2797
+ return await command(rest, io);
2798
+ } catch (error) {
2799
+ io.stderr(`cetra-cli: ${message(error)}`);
2800
+ return error instanceof CliError ? error.code : Exit.Error;
2801
+ }
2802
+ }
2803
+ /** True when this module is the file node was started with (through the npm bin symlink too). */
2804
+ function isEntryPoint() {
2805
+ const entry = process.argv[1];
2806
+ if (entry === void 0) return false;
2807
+ try {
2808
+ return import.meta.url === pathToFileURL(realpathSync(entry)).href;
2809
+ } catch {
2810
+ return false;
2811
+ }
2812
+ }
2813
+ if (isEntryPoint()) main(process.argv.slice(2), realIo()).then((code) => {
2814
+ process.exitCode = code;
2815
+ });
2816
+ export { COMMANDS, main };