@tracken/cli 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/CHANGELOG.md +404 -0
  2. package/LICENSE +21 -0
  3. package/README.md +310 -2
  4. package/dist/bin/tracken.d.ts +2 -0
  5. package/dist/bin/tracken.js +5 -0
  6. package/dist/cli/args.d.ts +17 -0
  7. package/dist/cli/args.js +114 -0
  8. package/dist/cli/commands/api.d.ts +2 -0
  9. package/dist/cli/commands/api.js +73 -0
  10. package/dist/cli/commands/auth.d.ts +8 -0
  11. package/dist/cli/commands/auth.js +141 -0
  12. package/dist/cli/commands/mcp.d.ts +19 -0
  13. package/dist/cli/commands/mcp.js +89 -0
  14. package/dist/cli/commands/org.d.ts +24 -0
  15. package/dist/cli/commands/org.js +123 -0
  16. package/dist/cli/context.d.ts +54 -0
  17. package/dist/cli/context.js +135 -0
  18. package/dist/cli/execute.d.ts +16 -0
  19. package/dist/cli/execute.js +112 -0
  20. package/dist/cli/help.d.ts +8 -0
  21. package/dist/cli/help.js +153 -0
  22. package/dist/cli/main.d.ts +2 -0
  23. package/dist/cli/main.js +114 -0
  24. package/dist/cli/operation-args.d.ts +25 -0
  25. package/dist/cli/operation-args.js +245 -0
  26. package/dist/core/auth/oauth.d.ts +39 -0
  27. package/dist/core/auth/oauth.js +102 -0
  28. package/dist/core/auth/scopes.d.ts +19 -0
  29. package/dist/core/auth/scopes.js +49 -0
  30. package/dist/core/auth/secret-store.d.ts +60 -0
  31. package/dist/core/auth/secret-store.js +141 -0
  32. package/dist/core/auth/session.d.ts +75 -0
  33. package/dist/core/auth/session.js +200 -0
  34. package/dist/core/catalog.d.ts +12 -0
  35. package/dist/core/catalog.js +33 -0
  36. package/dist/core/client.d.ts +22 -0
  37. package/dist/core/client.js +45 -0
  38. package/dist/core/config.d.ts +27 -0
  39. package/dist/core/config.js +109 -0
  40. package/dist/core/environments.d.ts +21 -0
  41. package/dist/core/environments.js +53 -0
  42. package/dist/core/errors.d.ts +96 -0
  43. package/dist/core/errors.js +248 -0
  44. package/dist/core/index.d.ts +21 -0
  45. package/dist/core/index.js +22 -0
  46. package/dist/core/jobs.d.ts +15 -0
  47. package/dist/core/jobs.js +19 -0
  48. package/dist/core/operations.d.ts +108 -0
  49. package/dist/core/operations.js +7 -0
  50. package/dist/core/output/format.d.ts +19 -0
  51. package/dist/core/output/format.js +62 -0
  52. package/dist/core/output/render.d.ts +53 -0
  53. package/dist/core/output/render.js +229 -0
  54. package/dist/core/pagination.d.ts +2 -0
  55. package/dist/core/pagination.js +3 -0
  56. package/dist/core/request.d.ts +29 -0
  57. package/dist/core/request.js +109 -0
  58. package/dist/core/version.d.ts +10 -0
  59. package/dist/core/version.js +13 -0
  60. package/dist/generated/mcp-tools.d.ts +2 -0
  61. package/dist/generated/mcp-tools.js +5937 -0
  62. package/dist/generated/operations.d.ts +4 -0
  63. package/dist/generated/operations.js +17701 -0
  64. package/dist/mcp/errors.d.ts +34 -0
  65. package/dist/mcp/errors.js +100 -0
  66. package/dist/mcp/live.d.ts +3 -0
  67. package/dist/mcp/live.js +5 -0
  68. package/dist/mcp/prompts.d.ts +23 -0
  69. package/dist/mcp/prompts.js +101 -0
  70. package/dist/mcp/resources.d.ts +25 -0
  71. package/dist/mcp/resources.js +125 -0
  72. package/dist/mcp/server.d.ts +20 -0
  73. package/dist/mcp/server.js +59 -0
  74. package/dist/mcp/session.d.ts +60 -0
  75. package/dist/mcp/session.js +105 -0
  76. package/dist/mcp/tools.d.ts +17 -0
  77. package/dist/mcp/tools.js +181 -0
  78. package/dist/mcp/types.d.ts +25 -0
  79. package/dist/mcp/types.js +2 -0
  80. package/node_modules/@tracken/sdk/LICENSE +21 -0
  81. package/node_modules/@tracken/sdk/README.md +76 -0
  82. package/node_modules/@tracken/sdk/SOURCE.json +10 -0
  83. package/node_modules/@tracken/sdk/dist/client.d.ts +94 -0
  84. package/node_modules/@tracken/sdk/dist/client.js +258 -0
  85. package/node_modules/@tracken/sdk/dist/credentials.d.ts +60 -0
  86. package/node_modules/@tracken/sdk/dist/credentials.js +122 -0
  87. package/node_modules/@tracken/sdk/dist/decimal.d.ts +20 -0
  88. package/node_modules/@tracken/sdk/dist/decimal.js +67 -0
  89. package/node_modules/@tracken/sdk/dist/environments.d.ts +14 -0
  90. package/node_modules/@tracken/sdk/dist/environments.js +16 -0
  91. package/node_modules/@tracken/sdk/dist/errors.d.ts +150 -0
  92. package/node_modules/@tracken/sdk/dist/errors.js +190 -0
  93. package/node_modules/@tracken/sdk/dist/generated/operations.d.ts +1955 -0
  94. package/node_modules/@tracken/sdk/dist/generated/operations.js +2746 -0
  95. package/node_modules/@tracken/sdk/dist/generated/schema.d.ts +17988 -0
  96. package/node_modules/@tracken/sdk/dist/generated/schema.js +5 -0
  97. package/node_modules/@tracken/sdk/dist/index.d.ts +27 -0
  98. package/node_modules/@tracken/sdk/dist/index.js +24 -0
  99. package/node_modules/@tracken/sdk/dist/jobs.d.ts +23 -0
  100. package/node_modules/@tracken/sdk/dist/jobs.js +80 -0
  101. package/node_modules/@tracken/sdk/dist/operations.d.ts +23 -0
  102. package/node_modules/@tracken/sdk/dist/operations.js +2 -0
  103. package/node_modules/@tracken/sdk/dist/pagination.d.ts +19 -0
  104. package/node_modules/@tracken/sdk/dist/pagination.js +49 -0
  105. package/node_modules/@tracken/sdk/dist/request.d.ts +27 -0
  106. package/node_modules/@tracken/sdk/dist/request.js +10 -0
  107. package/node_modules/@tracken/sdk/dist/runtime.d.ts +22 -0
  108. package/node_modules/@tracken/sdk/dist/runtime.js +33 -0
  109. package/node_modules/@tracken/sdk/dist/tracken.d.ts +74 -0
  110. package/node_modules/@tracken/sdk/dist/tracken.js +203 -0
  111. package/node_modules/@tracken/sdk/dist/types.d.ts +130 -0
  112. package/node_modules/@tracken/sdk/dist/types.js +1 -0
  113. package/node_modules/@tracken/sdk/dist/version.d.ts +2 -0
  114. package/node_modules/@tracken/sdk/dist/version.js +2 -0
  115. package/node_modules/@tracken/sdk/package.json +42 -0
  116. package/node_modules/openapi-fetch/CHANGELOG.md +565 -0
  117. package/node_modules/openapi-fetch/CONTRIBUTING.md +102 -0
  118. package/node_modules/openapi-fetch/LICENSE +21 -0
  119. package/node_modules/openapi-fetch/README.md +122 -0
  120. package/node_modules/openapi-fetch/dist/index.cjs +547 -0
  121. package/node_modules/openapi-fetch/dist/index.cjs.map +1 -0
  122. package/node_modules/openapi-fetch/dist/index.d.cts +337 -0
  123. package/node_modules/openapi-fetch/dist/index.d.mts +335 -0
  124. package/node_modules/openapi-fetch/dist/index.d.ts +337 -0
  125. package/node_modules/openapi-fetch/dist/index.mjs +531 -0
  126. package/node_modules/openapi-fetch/dist/index.mjs.map +1 -0
  127. package/node_modules/openapi-fetch/package.json +77 -0
  128. package/node_modules/openapi-fetch/src/index.d.ts +345 -0
  129. package/node_modules/openapi-fetch/src/index.js +689 -0
  130. package/node_modules/openapi-typescript-helpers/CHANGELOG.md +98 -0
  131. package/node_modules/openapi-typescript-helpers/LICENSE +21 -0
  132. package/node_modules/openapi-typescript-helpers/README.md +5 -0
  133. package/node_modules/openapi-typescript-helpers/dist/index.cjs +3 -0
  134. package/node_modules/openapi-typescript-helpers/dist/index.cjs.map +1 -0
  135. package/node_modules/openapi-typescript-helpers/dist/index.d.cts +167 -0
  136. package/node_modules/openapi-typescript-helpers/dist/index.d.mts +167 -0
  137. package/node_modules/openapi-typescript-helpers/dist/index.d.ts +167 -0
  138. package/node_modules/openapi-typescript-helpers/dist/index.mjs +2 -0
  139. package/node_modules/openapi-typescript-helpers/dist/index.mjs.map +1 -0
  140. package/node_modules/openapi-typescript-helpers/package.json +39 -0
  141. package/openapi/SOURCE.json +10 -0
  142. package/openapi/openapi.yaml +30514 -0
  143. package/package.json +63 -4
@@ -0,0 +1,112 @@
1
+ import { UsageError } from "../core/errors.js";
2
+ import { waitForJob } from "../core/jobs.js";
3
+ import { ListWriter, renderBody } from "../core/output/render.js";
4
+ import { nextSince, pageItems, pages } from "../core/pagination.js";
5
+ /** `--wait` gives up after this long unless `--wait-timeout` says otherwise. */
6
+ const DEFAULT_WAIT_S = 600;
7
+ function waitTimeout(context) {
8
+ const raw = context.args.value("wait-timeout");
9
+ if (raw === undefined)
10
+ return DEFAULT_WAIT_S * 1000;
11
+ if (!/^\d+$/.test(raw) || Number(raw) <= 0)
12
+ throw new UsageError("--wait-timeout takes seconds, a whole number above 0.");
13
+ return Number(raw) * 1000;
14
+ }
15
+ async function emit(context, text) {
16
+ const out = context.args.value("out");
17
+ if (out) {
18
+ await context.io.writeFile(out, text);
19
+ context.warn(`Wrote ${out}.`);
20
+ return;
21
+ }
22
+ context.io.stdout.write(text);
23
+ }
24
+ /** Table, CSV and NDJSON carry no `meta`, so the next pass's start goes to stderr, ready to paste. */
25
+ function reportNextSince(context, mode, since) {
26
+ if (since && mode !== "json")
27
+ context.warn(`next: --since ${since}`);
28
+ }
29
+ async function printResponse(context, response, mode, hints) {
30
+ if (response.binary) {
31
+ if (!context.args.value("out") && context.interactive) {
32
+ throw new UsageError(`The answer is ${response.contentType || "binary"}; save it with --out <file> or pipe it.`);
33
+ }
34
+ await emit(context, response.body);
35
+ return;
36
+ }
37
+ if (response.body === undefined) {
38
+ if (context.interactive)
39
+ context.warn(response.status === 204 ? "Done." : `Done (${response.status}).`);
40
+ return;
41
+ }
42
+ if (typeof response.body === "string") {
43
+ await emit(context, response.body.endsWith("\n") ? response.body : `${response.body}\n`);
44
+ return;
45
+ }
46
+ const text = renderBody(response.body, mode, { hints, columns: context.columns(), timeZone: context.io.timeZone });
47
+ // An empty list is no lines at all in NDJSON, not one blank line.
48
+ if (text || mode !== "ndjson")
49
+ await emit(context, `${text}\n`);
50
+ reportNextSince(context, mode, nextSince(response.body));
51
+ }
52
+ async function printAll(context, client, request, mode, hints) {
53
+ const out = context.args.value("out");
54
+ const chunks = [];
55
+ const write = (text) => (out ? chunks.push(text) : context.io.stdout.write(text));
56
+ const writer = new ListWriter(mode, write, { hints, columns: context.columns(), timeZone: context.io.timeZone });
57
+ let report;
58
+ let since;
59
+ for await (const page of pages(client, request)) {
60
+ since ??= nextSince(page.body);
61
+ const data = page.body?.data;
62
+ // A paginated report (the general ledger) keeps its columns; its pages' rows are joined.
63
+ if (!Array.isArray(data) && typeof data === "object" && data !== null && Array.isArray(data.rows)) {
64
+ if (!report)
65
+ report = { data: { ...data, rows: [] } };
66
+ report.data.rows.push(...pageItems(page.body));
67
+ continue;
68
+ }
69
+ writer.add(pageItems(page.body));
70
+ }
71
+ if (report)
72
+ write(`${renderBody(report, mode, { columns: context.columns(), timeZone: context.io.timeZone })}\n`);
73
+ // One document for the whole read: its records, and where the next pass starts.
74
+ else
75
+ writer.end(since ? { sync: { next_since: since } } : undefined);
76
+ if (out)
77
+ await emit(context, chunks.join(""));
78
+ reportNextSince(context, mode, since);
79
+ }
80
+ export async function execute(context, client, request, options) {
81
+ const mode = context.outputMode();
82
+ if (context.args.switch("all")) {
83
+ if (!options.pageable)
84
+ throw new UsageError("--all applies to lists only.");
85
+ await printAll(context, client, request, mode, options.hints);
86
+ return;
87
+ }
88
+ let response = await client.send(request);
89
+ if (options.dryRun) {
90
+ context.warn(response.dryRun
91
+ ? "Dry run: the API checked the request and stored, posted and sent nothing."
92
+ : "Warning: the API did not confirm the dry run (no Tracken-Dry-Run header); check what it did.");
93
+ }
94
+ if (response.status === 202) {
95
+ if (context.args.switch("wait") && !options.dryRun) {
96
+ response = await waitForJob(client, response, request, {
97
+ timeoutMs: waitTimeout(context),
98
+ now: () => context.io.clock.now(),
99
+ sleep: (ms) => context.io.clock.sleep(ms),
100
+ onProgress: context.interactive ? (status, progress) => context.warn(` ${status}${progress !== undefined ? ` ${progress} %` : ""}`) : undefined,
101
+ });
102
+ }
103
+ else if (!context.args.switch("wait")) {
104
+ context.warn("Accepted: the work continues in the background. Add --wait to wait for it.");
105
+ }
106
+ }
107
+ else if (context.args.switch("wait")) {
108
+ context.warn("Note: the API answered at once; there was nothing to wait for.");
109
+ }
110
+ await printResponse(context, response, mode, options.hints);
111
+ }
112
+ //# sourceMappingURL=execute.js.map
@@ -0,0 +1,8 @@
1
+ import type { OperationSpec } from "../core/operations.js";
2
+ /** `tracken --version`: the CLI's version and the public document its commands were generated from. */
3
+ export declare function versionText(): string;
4
+ export declare function mainHelp(): string;
5
+ export declare function resourceHelp(resource: string): string;
6
+ /** Why a planned operation's command does nothing yet, and the way around it when an environment is ahead. */
7
+ export declare function notYetServed(operation: OperationSpec): string;
8
+ export declare function operationHelp(operation: OperationSpec): string;
@@ -0,0 +1,153 @@
1
+ /** Help text, generated from the same operations the commands are. */
2
+ import { operationsOf, resources } from "../core/catalog.js";
3
+ import { DOCUMENT } from "../generated/operations.js";
4
+ import { VERSION } from "../core/version.js";
5
+ const wrap = (text, indent, width = 96) => {
6
+ const words = text.replace(/\s+/g, " ").trim().split(" ");
7
+ const lines = [];
8
+ let line = "";
9
+ for (const word of words) {
10
+ if (line && line.length + word.length + 1 > width - indent.length) {
11
+ lines.push(line);
12
+ line = word;
13
+ }
14
+ else
15
+ line = line ? `${line} ${word}` : word;
16
+ }
17
+ if (line)
18
+ lines.push(line);
19
+ return lines.map((entry) => indent + entry).join("\n");
20
+ };
21
+ const firstSentence = (text) => (text.match(/^.*?[.!?](\s|$)/)?.[0] ?? text).trim();
22
+ /** `tracken --version`: the CLI's version and the public document its commands were generated from. */
23
+ export function versionText() {
24
+ const source = `${DOCUMENT.commit.slice(0, 12)}${DOCUMENT.ref ? ` (${DOCUMENT.ref})` : ""}`;
25
+ return `tracken ${VERSION}\nAPI document ${DOCUMENT.version}, tracken_accounts ${source}\n`;
26
+ }
27
+ function groupByTag(entries) {
28
+ const byTag = new Map();
29
+ for (const { resource, tag } of entries)
30
+ byTag.set(tag, [...(byTag.get(tag) ?? []), resource]);
31
+ return [...byTag].map(([tag, names]) => wrap(names.join(", "), " ".repeat(23)).replace(/^ {23}/, ` ${`${tag}:`.padEnd(20)} `));
32
+ }
33
+ export function mainHelp() {
34
+ const all = resources();
35
+ const coming = all.filter((entry) => !entry.live);
36
+ const comingSection = coming.length
37
+ ? `\nComing (in the API document, not yet served; \`tracken <resource> --help\` lists them):\n${groupByTag(coming).join("\n")}\n`
38
+ : "";
39
+ return `tracken ${VERSION} — Tracken Accounts from the command line (API ${DOCUMENT.version})
40
+
41
+ Usage:
42
+ tracken <resource> <verb> [ids…] [flags] e.g. tracken sales-invoices list --status issued
43
+ tracken api <METHOD> <path> [--data …] any request, as the API takes it
44
+
45
+ Sign-in and setup:
46
+ login Sign in through the browser (device code). Read-only unless --write or --scope.
47
+ logout Revoke and forget this environment's session.
48
+ whoami Who and where the CLI acts, without calling the API; --verify asks the API.
49
+ org list|use|current
50
+ The organizations you may act in; choose one for every later command.
51
+ mcp The local MCP server on stdio, for Claude, Cursor or VS Code.
52
+ --print-config claude|cursor|vscode prints the client's configuration.
53
+
54
+ Resources:
55
+ ${groupByTag(all.filter((entry) => entry.live)).join("\n")}
56
+ ${comingSection}
57
+ Flags for every command:
58
+ --env prod|dev|local Environment (default: TRACKEN_ENV, else prod).
59
+ --org <id> Organization for this command (default: tracken org use, TRACKEN_ORG).
60
+ -o, --output json|table|csv|ndjson
61
+ json is the API's answer as it is; table shows 1 234,50 and 12.10.2026;
62
+ ndjson (or --ndjson) is one record per line. Default: table in a
63
+ terminal, json in a pipe.
64
+ --columns a,b,c Fields to show in table and csv output.
65
+ --out <file> Write the answer (or a PDF) to a file.
66
+ --all Follow pagination to the end of a list.
67
+ --wait Wait for an accepted (202) job to finish; --wait-timeout <s> (600).
68
+ --since <when> Only records changed since (2026-10-24T09:30:00Z, 2026-10-24, 2h, 7d),
69
+ in the order they changed. The answer says where the next read starts
70
+ (json: meta.sync.next_since; otherwise "next: --since …" on stderr):
71
+ start the next read there, never at "now". A record may come twice;
72
+ keep the one with the newer updated_at.
73
+ --dry-run Ask the API to check a write and store, post and send nothing.
74
+ --idempotency-key <key> For a POST: run it again with the same key (within 24 hours) and the
75
+ API answers the first result instead of creating twice.
76
+ --debug Print each request and its request id to stderr.
77
+
78
+ Machine mode: set TRACKEN_CLIENT_ID and TRACKEN_CLIENT_SECRET (an API credential from Settings →
79
+ API access); TRACKEN_SCOPE narrows the token. The credential names its own organization.
80
+
81
+ Run \`tracken <resource> --help\` or \`tracken <resource> <verb> --help\` for details.
82
+ `;
83
+ }
84
+ const usage = (operation) => ["tracken", operation.resource, operation.verb, ...operation.positionals.map((name) => `<${name}>`)].join(" ");
85
+ export function resourceHelp(resource) {
86
+ const operations = operationsOf(resource);
87
+ const width = Math.max(...operations.map((operation) => usage(operation).length));
88
+ const lines = (entries) => entries.map((operation) => ` ${usage(operation).padEnd(width)} ${operation.summary}`).join("\n");
89
+ const live = operations.filter((operation) => operation.availability === "live");
90
+ const planned = operations.filter((operation) => operation.availability === "planned");
91
+ const sections = [`Commands for ${resource} (${operations[0]?.tag ?? ""}):`];
92
+ if (live.length)
93
+ sections.push(lines(live));
94
+ if (planned.length)
95
+ sections.push(`Coming (in the API document, not yet served):\n${lines(planned)}`);
96
+ sections.push(`Run \`tracken ${resource} <verb> --help\` for a command's flags.`);
97
+ return `${sections.join("\n\n")}\n`;
98
+ }
99
+ /** Why a planned operation's command does nothing yet, and the way around it when an environment is ahead. */
100
+ export function notYetServed(operation) {
101
+ const example = `tracken api ${operation.method.toUpperCase()} ${operation.path.replace(/\{([^}]+)\}/g, "<$1>")}`;
102
+ return `tracken ${operation.resource} ${operation.verb} is not yet in the public API (document ${DOCUMENT.version}). Where an environment already serves it, \`${example}\` reaches it.`;
103
+ }
104
+ function paramLine(param) {
105
+ const kind = param.type === "array" ? `${param.items ?? "string"}…` : param.type === "boolean" ? "" : param.format ?? param.type;
106
+ const name = `--${param.flag}${kind ? ` <${kind}>` : ""}`;
107
+ const notes = [
108
+ param.required && param.in !== "path" ? "required" : "",
109
+ param.enum ? `one of ${param.enum.join(", ")}` : "",
110
+ param.default !== undefined ? `default ${String(param.default)}` : "",
111
+ ].filter(Boolean);
112
+ const description = [param.description, notes.length ? `(${notes.join("; ")})` : ""].filter(Boolean).join(" ");
113
+ return ` ${name}\n${wrap(description || " ", " ")}`;
114
+ }
115
+ function fieldLine(field, prefix) {
116
+ const kind = field.format ? `${field.type}, ${field.format}` : field.type;
117
+ const notes = [field.required ? "required" : "", field.nullable ? "nullable" : "", field.enum ? `one of ${field.enum.join(", ")}` : ""].filter(Boolean);
118
+ return ` ${prefix}${field.name} (${kind}${notes.length ? `; ${notes.join("; ")}` : ""})\n${wrap(firstSentence(field.description) || " ", " ")}`;
119
+ }
120
+ export function operationHelp(operation) {
121
+ const sections = [`${operation.summary}\n\n ${usage(operation)} [flags]\n\n${wrap(operation.description, " ")}`];
122
+ if (operation.availability === "planned")
123
+ sections.push(`Coming: ${notYetServed(operation)}`);
124
+ sections.push(`Operation ${operation.operationId}: ${operation.method.toUpperCase()} ${operation.path}${operation.scopes.length ? `; scope ${operation.scopes.join(" or ")}` : ""}.`);
125
+ const params = operation.params.filter((param) => param.in !== "path" && param.name !== "Idempotency-Key");
126
+ if (params.length)
127
+ sections.push(`Flags:\n${params.map(paramLine).join("\n")}`);
128
+ const body = operation.body;
129
+ if (body?.contentType === "application/json") {
130
+ const lines = [
131
+ "Body (the record inside {\"data\": …}):",
132
+ " --data '<json>' | --data @file.json | --data @-",
133
+ " --set field=value one field at a time (strings, numbers, true/false, null; JSON for lists)",
134
+ ];
135
+ if (body.fields.length)
136
+ lines.push(...body.fields.map((field) => fieldLine(field, "")));
137
+ if (body.options.length)
138
+ lines.push("", "Options:", ...body.options.map((field) => fieldLine(field, "--").replace(`--${field.name}`, `--${field.flag}`)));
139
+ sections.push(lines.join("\n"));
140
+ }
141
+ else if (body) {
142
+ sections.push(`Form:\n${body.form.map((field) => fieldLine(field, "--").replace(`--${field.name}`, `--${field.flag}`)).join("\n")}`);
143
+ }
144
+ const extras = [
145
+ operation.paginated ? "--all follows every page." : "",
146
+ operation.async ? "--wait waits for the accepted job." : "",
147
+ operation.method === "post" ? "An Idempotency-Key is sent automatically (--idempotency-key to choose one)." : "",
148
+ ].filter(Boolean);
149
+ if (extras.length)
150
+ sections.push(extras.join(" "));
151
+ return `${sections.join("\n\n")}\n`;
152
+ }
153
+ //# sourceMappingURL=help.js.map
@@ -0,0 +1,2 @@
1
+ import { type Io } from "./context.js";
2
+ export declare function run(argv: readonly string[], io: Io): Promise<number>;
@@ -0,0 +1,114 @@
1
+ /**
2
+ * The command dispatcher: `tracken <resource> <verb> [ids…] [flags]`, the sign-in and organization
3
+ * commands, and `tracken api`. Answers the process exit code; every failure is printed once, to stderr.
4
+ */
5
+ import { findOperation, operationsOf, resources } from "../core/catalog.js";
6
+ import { ApiError, EXIT, exitCodeOf, renderError, UsageError } from "../core/errors.js";
7
+ import { buildRequest } from "../core/request.js";
8
+ import { parseArgs } from "./args.js";
9
+ import { api } from "./commands/api.js";
10
+ import { login, logout, whoami } from "./commands/auth.js";
11
+ import { mcp } from "./commands/mcp.js";
12
+ import { org } from "./commands/org.js";
13
+ import { Context } from "./context.js";
14
+ import { execute } from "./execute.js";
15
+ import { mainHelp, notYetServed, operationHelp, resourceHelp, versionText } from "./help.js";
16
+ import { idempotencyKey, operationInput } from "./operation-args.js";
17
+ const BUILT_INS = { login, logout, whoami, org, api, mcp };
18
+ /** Levenshtein distance, for "did you mean". */
19
+ function distance(a, b) {
20
+ const row = Array.from({ length: b.length + 1 }, (_, index) => index);
21
+ for (let i = 1; i <= a.length; i++) {
22
+ let previous = row[0];
23
+ row[0] = i;
24
+ for (let j = 1; j <= b.length; j++) {
25
+ const current = row[j];
26
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));
27
+ previous = current;
28
+ }
29
+ }
30
+ return row[b.length];
31
+ }
32
+ function suggest(word, candidates) {
33
+ const best = candidates.map((candidate) => ({ candidate, score: distance(word, candidate) })).sort((x, y) => x.score - y.score)[0];
34
+ return best && best.score <= Math.max(2, Math.floor(word.length / 3)) ? ` Did you mean ${best.candidate}?` : "";
35
+ }
36
+ async function runResource(context, args) {
37
+ const [resource, word, ...rest] = args.positionals;
38
+ const operations = operationsOf(resource);
39
+ if (operations.length === 0) {
40
+ const names = [...resources().map((entry) => entry.resource), ...Object.keys(BUILT_INS)];
41
+ throw new UsageError(`Unknown command "${resource}".${suggest(resource, names)} Run \`tracken --help\` for the list.`);
42
+ }
43
+ let operation = word ? findOperation(resource, word) : undefined;
44
+ let positionals = rest;
45
+ // A resource with one operation needs no verb: `tracken search --q acme`, `tracken users`.
46
+ if (!operation && operations.length === 1) {
47
+ operation = operations[0];
48
+ positionals = word ? [word, ...rest] : rest;
49
+ }
50
+ if (!operation) {
51
+ if (!word || args.switch("help")) {
52
+ context.io.stdout.write(resourceHelp(resource));
53
+ return args.switch("help") ? 0 : EXIT.usage;
54
+ }
55
+ throw new UsageError(`Unknown verb "${word}" for ${resource}.${suggest(word, operations.map((entry) => entry.verb))} Run \`tracken ${resource} --help\`.`);
56
+ }
57
+ if (args.switch("help")) {
58
+ context.io.stdout.write(operationHelp(operation));
59
+ return 0;
60
+ }
61
+ // Refused before signing in or calling anything: the API would answer 403 OPERATION_NOT_PUBLIC.
62
+ if (operation.availability !== "live")
63
+ throw new UsageError(notYetServed(operation));
64
+ const input = await operationInput(operation, args, positionals, {
65
+ readFile: (path) => context.io.readFile(path),
66
+ readStdin: () => context.io.readStdin(),
67
+ now: () => context.io.clock.now(),
68
+ });
69
+ const request = buildRequest(operation, input);
70
+ const key = idempotencyKey(args, operation.method, `tracken ${operation.resource} ${operation.verb}`);
71
+ if (key)
72
+ request.headers["Idempotency-Key"] = key;
73
+ const client = await context.client();
74
+ await execute(context, client, request, { hints: operation.display, dryRun: input.query?.dry_run === true, pageable: operation.paginated });
75
+ return 0;
76
+ }
77
+ export async function run(argv, io) {
78
+ let jsonErrors = false;
79
+ let context;
80
+ try {
81
+ const args = parseArgs(argv);
82
+ if (args.switch("version")) {
83
+ io.stdout.write(versionText());
84
+ return 0;
85
+ }
86
+ const command = args.positionals[0];
87
+ if (!command || command === "help") {
88
+ const topic = args.positionals[1];
89
+ io.stdout.write(topic && operationsOf(topic).length ? resourceHelp(topic) : mainHelp());
90
+ return command || args.switch("help") ? 0 : EXIT.usage;
91
+ }
92
+ context = new Context(io, args);
93
+ const output = args.has("ndjson") ? "ndjson" : args.value("output");
94
+ jsonErrors = output === "json" || output === "ndjson" || (!io.stdout.isTTY && output === undefined && !io.env.TRACKEN_OUTPUT);
95
+ const builtIn = BUILT_INS[command];
96
+ if (builtIn) {
97
+ if (args.switch("help")) {
98
+ io.stdout.write(mainHelp());
99
+ return 0;
100
+ }
101
+ return await builtIn(context);
102
+ }
103
+ return await runResource(context, args);
104
+ }
105
+ catch (error) {
106
+ // A script reading JSON gets the API's error envelope as it came, on stderr.
107
+ if (jsonErrors && error instanceof ApiError && typeof error.body === "object" && error.body !== null)
108
+ io.stderr.write(`${JSON.stringify(error.body)}\n`);
109
+ else
110
+ io.stderr.write(`${renderError(error, context?.errorContext())}\n`);
111
+ return exitCodeOf(error);
112
+ }
113
+ }
114
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1,25 @@
1
+ import type { FieldSpec, OperationSpec } from "../core/operations.js";
2
+ import type { OperationInput } from "../core/request.js";
3
+ import type { ParsedArgs } from "./args.js";
4
+ /** Flags every command understands; they never reach an operation. */
5
+ export declare const GLOBAL_FLAGS: readonly ["env", "org", "output", "ndjson", "columns", "out", "debug", "help", "all", "wait", "wait-timeout", "data", "set", "since", "idempotency-key"];
6
+ /**
7
+ * `--idempotency-key K`: the key a re-runnable script chooses for a POST, so running it again
8
+ * replays the first answer instead of creating twice. Without it the client makes one per command.
9
+ */
10
+ export declare function idempotencyKey(args: ParsedArgs, method: string, command: string): string | undefined;
11
+ export interface ArgSources {
12
+ readFile(path: string): Promise<Buffer>;
13
+ readStdin(): Promise<Buffer>;
14
+ now(): number;
15
+ }
16
+ /**
17
+ * An instant for `--since` and other date-time parameters: RFC 3339 as given, a date as its UTC
18
+ * midnight, or a duration back from now (`15m`, `2h`, `7d`, `2w`).
19
+ */
20
+ export declare function parseInstant(value: string, now: number): string;
21
+ /** A `--set` or option value, typed by its field. */
22
+ export declare function fieldValue(field: FieldSpec, raw: string, where: string): unknown;
23
+ /** Flags this operation accepts, beside the global ones. */
24
+ export declare function operationFlags(operation: OperationSpec): string[];
25
+ export declare function operationInput(operation: OperationSpec, args: ParsedArgs, positionals: string[], sources: ArgSources): Promise<OperationInput>;
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Maps a command line onto an operation's input: positionals onto path parameters, flags onto query
3
+ * and header parameters (typed and checked against the schema), `--data`/`--set` onto the `{data}`
4
+ * record, option flags beside it, and form flags for an upload.
5
+ */
6
+ import { basename, extname } from "node:path";
7
+ import { UsageError } from "../core/errors.js";
8
+ /** Flags every command understands; they never reach an operation. */
9
+ export const GLOBAL_FLAGS = ["env", "org", "output", "ndjson", "columns", "out", "debug", "help", "all", "wait", "wait-timeout", "data", "set", "since", "idempotency-key"];
10
+ /** The API keeps an Idempotency-Key for 24 hours, per principal; it takes at most 255 characters. */
11
+ const IDEMPOTENCY_KEY = /^[\x21-\x7e]{1,255}$/;
12
+ /**
13
+ * `--idempotency-key K`: the key a re-runnable script chooses for a POST, so running it again
14
+ * replays the first answer instead of creating twice. Without it the client makes one per command.
15
+ */
16
+ export function idempotencyKey(args, method, command) {
17
+ const key = args.value("idempotency-key");
18
+ if (key === undefined)
19
+ return undefined;
20
+ if (method.toLowerCase() !== "post")
21
+ throw new UsageError(`${command} is not a POST; --idempotency-key applies to creates and actions only.`);
22
+ if (!IDEMPOTENCY_KEY.test(key))
23
+ throw new UsageError("--idempotency-key takes 1 to 255 printable characters, without spaces (a UUID is a good key).");
24
+ return key;
25
+ }
26
+ const UNITS = { m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 };
27
+ /**
28
+ * An instant for `--since` and other date-time parameters: RFC 3339 as given, a date as its UTC
29
+ * midnight, or a duration back from now (`15m`, `2h`, `7d`, `2w`).
30
+ */
31
+ export function parseInstant(value, now) {
32
+ const relative = /^(\d+)([mhdw])$/.exec(value);
33
+ if (relative)
34
+ return new Date(now - Number(relative[1]) * UNITS[relative[2]]).toISOString().replace(/\.\d{3}Z$/, "Z");
35
+ if (/^\d{4}-\d{2}-\d{2}$/.test(value) && !Number.isNaN(Date.parse(value)))
36
+ return `${value}T00:00:00Z`;
37
+ if (/^\d{4}-\d{2}-\d{2}T/.test(value) && !Number.isNaN(Date.parse(value)))
38
+ return value;
39
+ throw new UsageError(`"${value}" is not an instant: use 2026-10-24T09:30:00Z, 2026-10-24, or a duration back from now like 2h or 7d.`);
40
+ }
41
+ function scalar(type, raw, where, values) {
42
+ if (values && !values.includes(raw))
43
+ throw new UsageError(`${where} must be one of ${values.join(", ")}; got "${raw}".`);
44
+ if (type === "integer") {
45
+ if (!/^-?\d+$/.test(raw))
46
+ throw new UsageError(`${where} must be a whole number; got "${raw}".`);
47
+ return Number(raw);
48
+ }
49
+ if (type === "number") {
50
+ if (raw.trim() === "" || Number.isNaN(Number(raw)))
51
+ throw new UsageError(`${where} must be a number; got "${raw}".`);
52
+ return Number(raw);
53
+ }
54
+ if (type === "boolean") {
55
+ if (raw !== "true" && raw !== "false")
56
+ throw new UsageError(`${where} must be true or false; got "${raw}".`);
57
+ return raw === "true";
58
+ }
59
+ return raw;
60
+ }
61
+ function paramValue(param, raws, now) {
62
+ const where = `--${param.flag}`;
63
+ if (param.type === "array") {
64
+ // Enumerated values never contain commas, so `--expand lines,payments` lists two.
65
+ const split = param.enum ? raws.flatMap((raw) => raw.split(",")).map((raw) => raw.trim()).filter(Boolean) : raws;
66
+ return split.map((raw) => scalar(param.items ?? "string", raw, where, param.enum));
67
+ }
68
+ if (raws.length > 1)
69
+ throw new UsageError(`${where} takes one value.`);
70
+ const raw = raws[0];
71
+ if (param.format === "date-time")
72
+ return parseInstant(raw, now);
73
+ return scalar(param.type, raw, where, param.enum);
74
+ }
75
+ /** A `--set` or option value, typed by its field. */
76
+ export function fieldValue(field, raw, where) {
77
+ if (raw === "null" && field.nullable)
78
+ return null;
79
+ switch (field.type) {
80
+ case "string":
81
+ if (field.enum && !field.enum.includes(raw))
82
+ throw new UsageError(`${where} must be one of ${field.enum.join(", ")}; got "${raw}".`);
83
+ return raw;
84
+ case "integer":
85
+ case "number":
86
+ case "boolean":
87
+ return scalar(field.type, raw, where, undefined);
88
+ case "object":
89
+ case "array":
90
+ case "any":
91
+ try {
92
+ return JSON.parse(raw);
93
+ }
94
+ catch {
95
+ if (field.type === "any")
96
+ return raw;
97
+ throw new UsageError(`${where} must be JSON (${field.type}); got ${raw}.`);
98
+ }
99
+ case "file":
100
+ throw new UsageError(`${where} is a file; pass it as --${field.flag} <path>.`);
101
+ }
102
+ }
103
+ async function readJsonArgument(value, sources) {
104
+ let text = value;
105
+ if (value === "@-")
106
+ text = (await sources.readStdin()).toString("utf8");
107
+ else if (value.startsWith("@")) {
108
+ try {
109
+ text = (await sources.readFile(value.slice(1))).toString("utf8");
110
+ }
111
+ catch (error) {
112
+ throw new UsageError(`Cannot read ${value.slice(1)}: ${error.message}`);
113
+ }
114
+ }
115
+ try {
116
+ return JSON.parse(text);
117
+ }
118
+ catch (error) {
119
+ throw new UsageError(`--data is not valid JSON: ${error.message}`);
120
+ }
121
+ }
122
+ const MEDIA_TYPES = {
123
+ ".xml": "application/xml",
124
+ ".csv": "text/csv",
125
+ ".json": "application/json",
126
+ ".pdf": "application/pdf",
127
+ ".txt": "text/plain",
128
+ };
129
+ async function fileValue(raw, sources, where) {
130
+ const path = raw.startsWith("@") ? raw.slice(1) : raw;
131
+ let bytes;
132
+ try {
133
+ bytes = path === "-" ? await sources.readStdin() : await sources.readFile(path);
134
+ }
135
+ catch (error) {
136
+ throw new UsageError(`${where}: cannot read ${path}: ${error.message}`);
137
+ }
138
+ const name = path === "-" ? "stdin" : basename(path);
139
+ return new File([new Uint8Array(bytes)], name, { type: MEDIA_TYPES[extname(name).toLowerCase()] ?? "application/octet-stream" });
140
+ }
141
+ /** Flags this operation accepts, beside the global ones. */
142
+ export function operationFlags(operation) {
143
+ return [
144
+ ...operation.params.map((param) => param.flag),
145
+ ...(operation.body?.options ?? []).map((field) => field.flag),
146
+ ...(operation.body?.form ?? []).map((field) => field.flag),
147
+ ];
148
+ }
149
+ export async function operationInput(operation, args, positionals, sources) {
150
+ const command = `tracken ${operation.resource} ${operation.verb}`;
151
+ const unknown = args.others([...GLOBAL_FLAGS, ...operationFlags(operation)]);
152
+ if (unknown.includes("dry-run"))
153
+ throw new UsageError(`${command} changes nothing, so it has no --dry-run.`);
154
+ if (unknown.length > 0)
155
+ throw new UsageError(`Unknown flag${unknown.length > 1 ? "s" : ""} ${unknown.map((flag) => `--${flag}`).join(", ")} for ${command}; see ${command} --help.`);
156
+ if (positionals.length > operation.positionals.length) {
157
+ throw new UsageError(`${command} takes ${operation.positionals.length === 0 ? "no arguments" : operation.positionals.map((name) => `<${name}>`).join(" ")}; got ${positionals.join(" ")}.`);
158
+ }
159
+ const input = { path: {}, query: {}, headers: {} };
160
+ operation.positionals.forEach((name, index) => {
161
+ const given = positionals[index];
162
+ const flag = operation.params.find((param) => param.in === "path" && param.name === name).flag;
163
+ const value = given ?? args.value(flag);
164
+ if (given !== undefined && args.has(flag))
165
+ throw new UsageError(`<${name}> is given twice (as an argument and --${flag}).`);
166
+ if (value !== undefined)
167
+ input.path[name] = value;
168
+ });
169
+ const now = sources.now();
170
+ for (const param of operation.params) {
171
+ if (param.in === "path" || !args.has(param.flag))
172
+ continue;
173
+ const value = paramValue(param, args.values(param.flag), now);
174
+ if (param.in === "query")
175
+ input.query[param.name] = value;
176
+ else
177
+ input.headers[param.name] = String(value);
178
+ }
179
+ if (args.has("since") && !operation.params.some((param) => param.flag === "since")) {
180
+ const target = operation.params.find((param) => param.in === "query" && param.name === "updated_since");
181
+ if (!target)
182
+ throw new UsageError(`${command} has no updated_since, so --since does not apply.`);
183
+ if (args.has(target.flag))
184
+ throw new UsageError("Give --since or --updated-since, not both.");
185
+ input.query[target.name] = paramValue(target, args.values("since"), now);
186
+ }
187
+ // An incremental read pages in the order of change (sync rule 2a), unless --sort says otherwise.
188
+ if (input.query.updated_since !== undefined && !args.has("sort")) {
189
+ const sort = operation.params.find((param) => param.in === "query" && param.name === "sort");
190
+ if (sort?.enum?.includes("updated_at"))
191
+ input.query.sort = "updated_at";
192
+ }
193
+ const body = operation.body;
194
+ const sets = args.values("set");
195
+ if (!body) {
196
+ if (args.has("data") || sets.length > 0)
197
+ throw new UsageError(`${command} takes no body; --data and --set do not apply.`);
198
+ return input;
199
+ }
200
+ if (body.contentType === "multipart/form-data") {
201
+ if (args.has("data") || sets.length > 0)
202
+ throw new UsageError(`${command} uploads a form; pass ${body.form.map((field) => `--${field.flag}`).join(", ")}.`);
203
+ input.form = {};
204
+ for (const field of body.form) {
205
+ const raw = args.value(field.flag);
206
+ if (raw === undefined)
207
+ continue;
208
+ input.form[field.name] = field.type === "file" ? await fileValue(raw, sources, `--${field.flag}`) : String(fieldValue(field, raw, `--${field.flag}`));
209
+ }
210
+ return input;
211
+ }
212
+ const dataArg = args.value("data");
213
+ if (dataArg !== undefined)
214
+ input.data = await readJsonArgument(dataArg, sources);
215
+ if (sets.length > 0) {
216
+ const base = input.data === undefined ? {} : input.data;
217
+ if (typeof base !== "object" || base === null || Array.isArray(base))
218
+ throw new UsageError("--set needs --data to be a JSON object.");
219
+ // --set applies to the record; when --data holds the whole body, it applies inside its `data`.
220
+ const wrapped = "data" in base && !body.fields.some((field) => field.name === "data");
221
+ const record = { ...(wrapped ? (base.data ?? {}) : base) };
222
+ for (const assignment of sets) {
223
+ const equals = assignment.indexOf("=");
224
+ if (equals <= 0)
225
+ throw new UsageError(`--set takes field=value; got "${assignment}".`);
226
+ const name = assignment.slice(0, equals);
227
+ const field = body.fields.find((entry) => entry.name === name);
228
+ if (!field) {
229
+ throw new UsageError(`${command} has no field "${name}"${body.fields.length ? `; fields: ${body.fields.map((entry) => entry.name).join(", ")}` : ""}. Nested values go in --data.`);
230
+ }
231
+ record[name] = fieldValue(field, assignment.slice(equals + 1), `--set ${name}`);
232
+ }
233
+ input.data = wrapped ? { ...base, data: record } : record;
234
+ }
235
+ const options = {};
236
+ for (const option of body.options) {
237
+ const raw = args.value(option.flag);
238
+ if (raw !== undefined)
239
+ options[option.name] = fieldValue(option, raw, `--${option.flag}`);
240
+ }
241
+ if (Object.keys(options).length > 0)
242
+ input.options = options;
243
+ return input;
244
+ }
245
+ //# sourceMappingURL=operation-args.js.map