swagger-digest 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.js ADDED
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ VERSION,
4
+ defaultFilename,
5
+ defaultOutputDirectory,
6
+ estimateTokens,
7
+ fetchOpenApiSpec,
8
+ transformOpenApiToMarkdown,
9
+ writeDigest
10
+ } from "./chunk-CBSDTIKN.js";
11
+
12
+ // src/cli.ts
13
+ import { input } from "@inquirer/prompts";
14
+ import chalk from "chalk";
15
+ import { Command } from "commander";
16
+ import ora from "ora";
17
+
18
+ // src/headers.ts
19
+ var HEADER_NAME_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
20
+ function validateHeaderName(name) {
21
+ if (!name) throw new Error('Header name must not be empty. Expected "Name: value".');
22
+ if (/[\r\n]/.test(name)) {
23
+ throw new Error(`Invalid header name: header names must not contain CR/LF characters.`);
24
+ }
25
+ if (!HEADER_NAME_PATTERN.test(name)) {
26
+ throw new Error(`Invalid header name "${name}": use a valid HTTP header token (letters, digits and -_).`);
27
+ }
28
+ }
29
+ function validateHeaderValue(name, value) {
30
+ if (/[\r\n]/.test(value)) {
31
+ throw new Error(`Invalid value for header "${name}": values must not contain CR/LF.`);
32
+ }
33
+ if (/\0/.test(value)) {
34
+ throw new Error(`Invalid value for header "${name}": values must not contain NUL bytes.`);
35
+ }
36
+ }
37
+ function parseHeaderArgument(raw) {
38
+ const separator = raw.indexOf(":");
39
+ if (separator === -1) {
40
+ if (/[\r\n]/.test(raw)) {
41
+ throw new Error(`Invalid header: names and values must not contain CR/LF.`);
42
+ }
43
+ throw new Error(`Invalid header \u2014 expected "Name: value" format (for example "Authorization: Bearer <token>").`);
44
+ }
45
+ const name = raw.slice(0, separator).trim();
46
+ const value = raw.slice(separator + 1).trim();
47
+ validateHeaderName(name);
48
+ validateHeaderValue(name, value);
49
+ return { [name.toLowerCase()]: value };
50
+ }
51
+ function parseHeaderPairs(raw) {
52
+ const result = {};
53
+ for (const line of raw.split(/\r?\n/)) {
54
+ if (!line.trim()) continue;
55
+ Object.assign(result, parseHeaderArgument(line));
56
+ }
57
+ return result;
58
+ }
59
+ function mergeHeaders(...sources) {
60
+ const result = {};
61
+ for (const source of sources) {
62
+ if (!source) continue;
63
+ for (const [name, value] of Object.entries(source)) {
64
+ if (/[\r\n]/.test(name) || /[\r\n]/.test(value)) {
65
+ throw new Error(`Invalid header "${name}": CR/LF is not allowed in header names or values.`);
66
+ }
67
+ result[name.toLowerCase()] = value;
68
+ }
69
+ }
70
+ return result;
71
+ }
72
+
73
+ // src/cli.ts
74
+ function validateUrl(value) {
75
+ try {
76
+ const url = new URL(value);
77
+ if (url.protocol !== "http:" && url.protocol !== "https:") return "Use an http:// or https:// URL.";
78
+ return true;
79
+ } catch {
80
+ return "Enter a valid URL, including https://.";
81
+ }
82
+ }
83
+ function isInteractive() {
84
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
85
+ }
86
+ function parseMaxBytes(value) {
87
+ if (value === void 0) return void 0;
88
+ const parsed = Number(value);
89
+ if (!Number.isFinite(parsed) || parsed <= 0 || !Number.isInteger(parsed)) {
90
+ throw new Error(`Invalid --max-bytes value: ${value}. Use a positive integer number of bytes.`);
91
+ }
92
+ return parsed;
93
+ }
94
+ function parseMaxTokens(value) {
95
+ if (value === void 0) return void 0;
96
+ const parsed = Number(value);
97
+ if (!Number.isFinite(parsed) || parsed <= 0 || !Number.isInteger(parsed)) {
98
+ throw new Error(`Invalid --max-tokens value: ${value}. Use a positive integer number of tokens.`);
99
+ }
100
+ return parsed;
101
+ }
102
+ function collectOption(value, previous) {
103
+ return [...previous ?? [], value];
104
+ }
105
+ function buildRequestHeaders(options) {
106
+ const fromEnv = process.env.SWAGGER_DIGEST_HEADER ? parseHeaderPairs(process.env.SWAGGER_DIGEST_HEADER) : {};
107
+ const fromFlags = (options.headers ?? []).map(parseHeaderArgument);
108
+ const cookieHeader = options.cookie !== void 0 ? parseHeaderArgument(`Cookie: ${options.cookie}`) : {};
109
+ return mergeHeaders(fromEnv, ...fromFlags, cookieHeader);
110
+ }
111
+ async function main() {
112
+ const program = new Command();
113
+ program.name("swagger-digest").description("Convert a Swagger UI page or OpenAPI URL into compact, AI-friendly Markdown.").version(VERSION).option("-u, --url <url>", "Swagger UI page URL or direct OpenAPI spec URL").option("-d, --out-dir <directory>", "Directory where the Markdown digest will be saved").option("-f, --filename <filename>", "Output filename (defaults to <api-title>-digest.md)").option("--no-browser", "Disable the optional Playwright headless-browser fallback").option("--max-bytes <bytes>", "Maximum response size in bytes (default 10000000 = 10 MB)", "10000000").option(
114
+ '-H, --header <"Name: value">',
115
+ "Custom request header, repeatable. Sent only to the URL you supplied.",
116
+ collectOption,
117
+ []
118
+ ).option("--cookie <string>", "Convenience for a Cookie request header (same-origin scoping applies)").option("--include-tag <tag>", "Keep only operations with this tag, repeatable", collectOption, []).option("--exclude-tag <tag>", "Drop operations with this tag, repeatable", collectOption, []).option("--path-prefix <prefix>", "Keep only operations whose path starts with this prefix").option("--max-tokens <n>", "Trim the digest until the approximate token estimate fits this budget").option("--spec <url>", "Explicit OpenAPI spec URL; overrides discovery from the Swagger UI page").option("--stdout", "Print the digest to standard output instead of writing a file").addHelpText(
119
+ "after",
120
+ [
121
+ "",
122
+ "Examples:",
123
+ " npx swagger-digest",
124
+ " npx swagger-digest --url https://petstore.swagger.io/ --out-dir ./docs",
125
+ " npx swagger-digest -u https://example.com/openapi.yaml -f payments-api.md",
126
+ ' npx swagger-digest -u https://api.example.com/swagger-ui -H "Authorization: Bearer <token>"',
127
+ "",
128
+ "Authentication:",
129
+ " -H/--header and --cookie values are sent ONLY to the origin of --url.",
130
+ ' You can also set SWAGGER_DIGEST_HEADER with newline-separated "Name: value" pairs;',
131
+ " -H flags override it on conflicts. Avoid passing secrets on the command line if",
132
+ " your shell saves history \u2014 prefer the environment variable.",
133
+ "",
134
+ "Filtering and token budget:",
135
+ " --include-tag/--exclude-tag/--path-prefix remove operations (and the data",
136
+ " models only they referenced) before rendering.",
137
+ " --max-tokens trims the digest in this order until the estimate fits:",
138
+ " 1. drop declared example payloads \u2192 2. shorten descriptions \u2192",
139
+ " 3. collapse parameter/response detail per tag (lowest-priority tag first:",
140
+ " the tag that appears last in the document is collapsed first) \u2192",
141
+ ' 4. keep only the Quick index entries. A "Trimmed" note records what was',
142
+ " removed. The estimator is a heuristic, NOT tokenizer-accurate \u2014 treat the",
143
+ " budget as a guide, not a guarantee."
144
+ ].join("\n")
145
+ );
146
+ program.parse(process.argv);
147
+ const options = program.opts();
148
+ if (!options.url && !isInteractive()) {
149
+ throw new Error("An interactive terminal or --url is required. Run `swagger-digest --help` for usage.");
150
+ }
151
+ const url = options.url ?? await input({
152
+ message: "Swagger UI or OpenAPI spec URL",
153
+ validate: validateUrl
154
+ });
155
+ const validUrl = validateUrl(url);
156
+ if (validUrl !== true) throw new Error(validUrl);
157
+ if (options.stdout && (options.outDir !== void 0 || options.filename !== void 0)) {
158
+ throw new Error(
159
+ "--stdout cannot be combined with --out-dir or --filename: it prints the digest to standard output instead of writing a file. Drop --stdout, or remove --out-dir/--filename."
160
+ );
161
+ }
162
+ const outputDirectory = options.outDir ?? (isInteractive() && !options.stdout ? await input({
163
+ message: "Destination directory",
164
+ default: defaultOutputDirectory(),
165
+ validate: (value) => value.trim() ? true : "Enter a destination directory."
166
+ }) : defaultOutputDirectory());
167
+ const maxBytes = parseMaxBytes(options.maxBytes);
168
+ const requestHeaders = buildRequestHeaders(options);
169
+ const spinner = ora({ text: "Fetching and parsing OpenAPI definition\u2026", color: "cyan" }).start();
170
+ let result;
171
+ try {
172
+ result = await fetchOpenApiSpec(url, {
173
+ useBrowserFallback: options.browser !== false,
174
+ maxBytes,
175
+ headers: requestHeaders,
176
+ specUrl: options.spec,
177
+ warn: (message) => console.error(chalk.yellow(`Warning: ${message}`))
178
+ });
179
+ } catch (error) {
180
+ spinner.fail("Could not extract an OpenAPI definition");
181
+ throw error;
182
+ }
183
+ const title = typeof result.spec.info?.title === "string" ? result.spec.info.title : "API";
184
+ const markdown = transformOpenApiToMarkdown(result.spec, result.sourceUrl, {
185
+ includeTags: options.includeTag,
186
+ excludeTags: options.excludeTag,
187
+ pathPrefix: options.pathPrefix,
188
+ maxTokens: parseMaxTokens(options.maxTokens),
189
+ onWarning: (message) => console.error(chalk.yellow(`Warning: ${message}`))
190
+ });
191
+ spinner.succeed(`Parsed ${title} (${result.retrievalMethod})`);
192
+ if (options.stdout) {
193
+ process.stdout.write(markdown);
194
+ return;
195
+ }
196
+ const filename = options.filename ?? (isInteractive() ? await input({
197
+ message: "Output filename",
198
+ default: defaultFilename(title),
199
+ validate: (value) => value.trim() ? true : "Enter a filename."
200
+ }) : defaultFilename(title));
201
+ const writeSpinner = ora({ text: "Writing Markdown digest\u2026", color: "cyan" }).start();
202
+ try {
203
+ const outputPath = await writeDigest({ markdown, directory: outputDirectory, filename });
204
+ writeSpinner.succeed(`Saved ${chalk.green(outputPath)}`);
205
+ const report = estimateTokens(markdown);
206
+ const endpointCount = Object.values(result.spec.paths ?? {}).reduce((count, pathItem) => {
207
+ if (!pathItem || typeof pathItem !== "object") return count;
208
+ const methods = ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
209
+ const operations = pathItem;
210
+ return count + methods.filter((method) => operations[method] && typeof operations[method] === "object").length;
211
+ }, 0);
212
+ const modelCount = Object.keys(result.spec.components?.schemas ?? result.spec.definitions ?? {}).length;
213
+ console.log("");
214
+ console.log(chalk.bold("Digest summary:"));
215
+ console.log(` ${chalk.dim("\u2022")} Endpoints: ${chalk.cyan(endpointCount)} operations`);
216
+ if (modelCount > 0) {
217
+ console.log(` ${chalk.dim("\u2022")} Data models: ${chalk.cyan(modelCount)} schemas`);
218
+ }
219
+ console.log(` ${chalk.dim("\u2022")} Characters: ${chalk.dim(report.characters.toLocaleString())}`);
220
+ console.log("");
221
+ console.log(chalk.bold("Estimated token usage (approximate):"));
222
+ for (const model of Object.values(report.models)) {
223
+ const windowLabel = model.contextWindow >= 1e6 ? `${model.contextWindow / 1e6}M` : `${model.contextWindow / 1e3}k`;
224
+ const paddedName = `${model.name}:`.padEnd(30, " ");
225
+ const tokenStr = `~${model.tokens.toLocaleString()} tokens`.padEnd(16, " ");
226
+ const percentStr = chalk.dim(`(${model.contextPercent}% of ${windowLabel} context)`);
227
+ console.log(` ${chalk.dim("\u2022")} ${paddedName} ${chalk.green(tokenStr)} ${percentStr}`);
228
+ }
229
+ console.log("");
230
+ } catch (error) {
231
+ writeSpinner.fail("Could not write digest");
232
+ throw error;
233
+ }
234
+ }
235
+ main().catch((error) => {
236
+ const message = error instanceof Error ? error.message : String(error);
237
+ console.error(chalk.red(`
238
+ Error: ${message}`));
239
+ process.exitCode = 1;
240
+ });
@@ -0,0 +1,95 @@
1
+ type JsonObject = Record<string, any>;
2
+ interface FetchOptions {
3
+ timeoutMs?: number;
4
+ useBrowserFallback?: boolean;
5
+ /** Maximum response body size in bytes (default 10 MB). */
6
+ maxBytes?: number;
7
+ /** Maximum number of redirects to follow (default 5). */
8
+ maxRedirects?: number;
9
+ /** Opt-in: reject hostnames resolving to private/loopback/metadata addresses. */
10
+ blockPrivateNetworks?: boolean;
11
+ /** Timeout for fallback-path probes (default 5000ms; main requests use timeoutMs). */
12
+ probeTimeoutMs?: number;
13
+ /**
14
+ * Custom request headers (e.g. Authorization or Cookie). These are sent ONLY
15
+ * to the origin of the URL passed to fetchOpenApiSpec; cross-origin requests
16
+ * (including cross-origin redirects and third-party browser requests) never
17
+ * receive them.
18
+ */
19
+ headers?: Record<string, string>;
20
+ /** Receives non-fatal notices, e.g. headers withheld on a cross-origin fetch. */
21
+ warn?: (message: string) => void;
22
+ /**
23
+ * Explicit spec URL that overrides discovery entirely: it is fetched first
24
+ * (with the same header scoping as the main URL) and the page is never
25
+ * consulted when it parses successfully.
26
+ */
27
+ specUrl?: string;
28
+ }
29
+ interface FetchResult {
30
+ spec: JsonObject;
31
+ sourceUrl: string;
32
+ retrievalMethod: 'direct-spec' | 'html-config' | 'inline-spec' | 'fallback-path' | 'headless-browser';
33
+ }
34
+
35
+ declare function isOpenApiSpec(value: unknown): value is JsonObject;
36
+ /** Parse JSON or YAML and reject arbitrary documents that are not OpenAPI/Swagger specs. */
37
+ declare function parseSpecText(text: string, source?: string): JsonObject;
38
+ /** Resolve a Swagger UI page or a direct OpenAPI JSON/YAML URL into a parsed spec. */
39
+ declare function fetchOpenApiSpec(input: string, options?: FetchOptions): Promise<FetchResult>;
40
+
41
+ declare function toTypeScriptIdentifier(value: string): string;
42
+
43
+ interface TransformOptions {
44
+ /** Keep only operations carrying at least one of these tags. Repeatable. */
45
+ includeTags?: string[];
46
+ /** Drop operations carrying any of these tags. Repeatable. */
47
+ excludeTags?: string[];
48
+ /** Keep only operations whose path starts with this prefix. */
49
+ pathPrefix?: string;
50
+ /**
51
+ * Trim the digest until the (approximate, heuristic) token estimate fits this
52
+ * budget. The estimator is not tokenizer-accurate; treat the budget as a guide.
53
+ */
54
+ maxTokens?: number;
55
+ /** Receives non-fatal notices, e.g. unknown tag names. */
56
+ onWarning?: (message: string) => void;
57
+ }
58
+ /** Convert an OpenAPI 2.0, 3.0, or 3.1 document to a compact Markdown digest. */
59
+ declare function transformOpenApiToMarkdown(spec: JsonObject, sourceUrl?: string, options?: TransformOptions): string;
60
+
61
+ interface ModelTokenEstimate {
62
+ name: string;
63
+ tokens: number;
64
+ contextWindow: number;
65
+ contextPercent: number;
66
+ }
67
+ interface DigestTokenReport {
68
+ characters: number;
69
+ models: {
70
+ claude: ModelTokenEstimate;
71
+ openai: ModelTokenEstimate;
72
+ gemini: ModelTokenEstimate;
73
+ deepseek: ModelTokenEstimate;
74
+ llama: ModelTokenEstimate;
75
+ };
76
+ }
77
+ /**
78
+ * Produces ROUGH token-count estimates for Markdown/code. The numbers are a
79
+ * heuristic (word + symbol density with per-model multipliers), not accurate
80
+ * tokenizer counts — use them as an order-of-magnitude guide only.
81
+ */
82
+ declare function estimateTokens(text: string): DigestTokenReport;
83
+
84
+ declare function defaultOutputDirectory(): string;
85
+ declare function defaultFilename(apiTitle?: string): string;
86
+ declare function resolveOutputDirectory(directory: string, cwd?: string): string;
87
+ declare function normalizeFilename(filename: string, fallback?: string): string;
88
+ declare function writeDigest(options: {
89
+ markdown: string;
90
+ directory: string;
91
+ filename: string;
92
+ }): Promise<string>;
93
+
94
+ export { defaultFilename, defaultOutputDirectory, estimateTokens, fetchOpenApiSpec, isOpenApiSpec, normalizeFilename, parseSpecText, resolveOutputDirectory, toTypeScriptIdentifier, transformOpenApiToMarkdown, writeDigest };
95
+ export type { DigestTokenReport, FetchOptions, FetchResult, JsonObject, ModelTokenEstimate, TransformOptions };
package/dist/index.js ADDED
@@ -0,0 +1,26 @@
1
+ import {
2
+ defaultFilename,
3
+ defaultOutputDirectory,
4
+ estimateTokens,
5
+ fetchOpenApiSpec,
6
+ isOpenApiSpec,
7
+ normalizeFilename,
8
+ parseSpecText,
9
+ resolveOutputDirectory,
10
+ toTypeScriptIdentifier,
11
+ transformOpenApiToMarkdown,
12
+ writeDigest
13
+ } from "./chunk-CBSDTIKN.js";
14
+ export {
15
+ defaultFilename,
16
+ defaultOutputDirectory,
17
+ estimateTokens,
18
+ fetchOpenApiSpec,
19
+ isOpenApiSpec,
20
+ normalizeFilename,
21
+ parseSpecText,
22
+ resolveOutputDirectory,
23
+ toTypeScriptIdentifier,
24
+ transformOpenApiToMarkdown,
25
+ writeDigest
26
+ };
package/package.json CHANGED
@@ -1,6 +1,84 @@
1
1
  {
2
2
  "name": "swagger-digest",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "description": "Turn Swagger UI pages and OpenAPI specs into compact, AI-friendly Markdown API digests.",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "bin": {
15
+ "swagger-digest": "./dist/cli.js"
16
+ },
17
+ "author": "VladLegkowski <VladLegkowski@users.noreply.github.com>",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/VladLegkowski/swagger-digest.git"
21
+ },
22
+ "homepage": "https://github.com/VladLegkowski/swagger-digest#readme",
23
+ "bugs": {
24
+ "url": "https://github.com/VladLegkowski/swagger-digest/issues"
25
+ },
26
+ "sideEffects": false,
27
+ "files": [
28
+ "dist",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
32
+ "scripts": {
33
+ "build": "tsup src/index.ts src/cli.ts --format esm --dts --clean",
34
+ "dev": "tsx src/cli.ts",
35
+ "start": "node dist/cli.js",
36
+ "typecheck": "tsc --noEmit",
37
+ "test": "npm run typecheck && tsx --test test/*.test.ts",
38
+ "check:exports": "publint",
39
+ "lint": "eslint .",
40
+ "prepare": "husky",
41
+ "prepack": "npm run build",
42
+ "prepublishOnly": "npm test"
43
+ },
44
+ "engines": {
45
+ "node": ">=20"
46
+ },
47
+ "dependencies": {
48
+ "@inquirer/prompts": "^7.3.2",
49
+ "chalk": "^5.4.1",
50
+ "cheerio": "^1.0.0",
51
+ "commander": "^13.1.0",
52
+ "ora": "^8.2.0",
53
+ "yaml": "^2.7.0"
54
+ },
55
+ "devDependencies": {
56
+ "@types/node": "^22.15.0",
57
+ "eslint": "^9.27.0",
58
+ "husky": "^9.1.7",
59
+ "lint-staged": "^17.6.0",
60
+ "prettier": "^3.9.10",
61
+ "publint": "^0.3.25",
62
+ "tsup": "^9.0.0",
63
+ "tsx": "^4.19.4",
64
+ "typescript": "^5.8.3",
65
+ "typescript-eslint": "^8.32.0"
66
+ },
67
+ "peerDependencies": {
68
+ "playwright": "^1.50.0"
69
+ },
70
+ "peerDependenciesMeta": {
71
+ "playwright": {
72
+ "optional": true
73
+ }
74
+ },
75
+ "keywords": [
76
+ "openapi",
77
+ "swagger",
78
+ "markdown",
79
+ "llm",
80
+ "ai-coding-agent",
81
+ "cli"
82
+ ],
83
+ "license": "MIT"
84
+ }