Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 58 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ name: CI
on:
push:
branches:
- master
- main

pull_request:
branches:
- master
- main

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
Expand All @@ -33,3 +33,59 @@ jobs:
- run: npm test -- --run
- run: npm run build
- run: node bin/cli.mjs --help

docs:
runs-on: ubuntu-latest
defaults:
run:
working-directory: docs
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22.x
cache: npm
cache-dependency-path: |
package-lock.json
docs/package-lock.json

# the site links the library from the repository root (file:..) and uses its dist/
- name: Install and build the library
working-directory: .
run: |
npm ci
npm run build

- run: npm ci
- run: npm run typecheck
- run: npm test
- run: npx next build

- name: Check the /api/generate trace
run: |
node -e '
const files = require("./.next/server/app/api/generate/route.js.nft.json").files;
const required = ["dist/index.mjs", "dist/templates/base/http-client.ejs", "node_modules/swagger2openapi/", "node_modules/oxfmt/", "oxfmt.linux-x64-gnu.node"];
const missing = required.filter((r) => !files.some((f) => f.includes(r)));
if (missing.length) { console.error("missing from the trace:", missing); process.exit(1); }
'

# ---- e2e (playwright): runs only when docs/playwright.config.ts exists ----
- name: Check for playwright config
id: e2e
run: echo "enabled=$([ -f playwright.config.ts ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
- name: Install Playwright browsers
if: steps.e2e.outputs.enabled == 'true'
run: npx playwright install --with-deps chromium
- name: E2E tests
if: steps.e2e.outputs.enabled == 'true'
run: npm run test:e2e
env:
E2E_SKIP_BUILD: '1'
GENERATE_RATE_LIMIT: '0'
- uses: actions/upload-artifact@v4
if: failure() && steps.e2e.outputs.enabled == 'true'
with:
name: playwright-report
path: docs/playwright-report
retention-days: 7
4 changes: 4 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ This is **ESM only** (`"type": "module"` in package.json). No CommonJS interop.
- `dist/cli.mjs` — CLI entry
- `dist/templates/` — copied from `templates/` post-build

### Docs site

`docs/` is a separate Next.js 16 app (own `package.json`, deps installed in `docs/`), deployed on Vercel with Root Directory `docs`. It depends on the library via `file:..` and loads `../dist/index.mjs` at runtime in `lib/server/generate.ts` (run `npm run build` at the root first). Pages: `/` landing, `/docs` (renders the root `README.md`), `/playground`; API: `POST /api/generate` (`lib/server/*`: option whitelist, spec parsing, SSRF-safe URL download, rate limit). Contract in `docs/lib/api-types.ts`. Tests: `cd docs && npm test` (vitest) and `npm run test:e2e` (Playwright). Root lint/format ignore `docs/**`.

## Key Hooks for Customization

Users can provide hooks in their config to customize generation:
Expand Down
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -788,13 +788,27 @@ Tests live in `tests/`:

To run a single file: `npx vitest run tests/core/cli-start.test.ts`.

### Docs site and online playground

`docs/` is a Next.js app with the documentation (rendered from this README) and a playground that
generates clients in a serverless function (`POST /api/generate`), so you can try options, view the
generated files and download them (one by one or as a `.zip`).

```bash
npm run build # the docs app uses the library from ../dist
cd docs && npm install
npm run dev # http://localhost:3000
```

See [`docs/README.md`](docs/README.md) for the API, its security limits and how to deploy it on Vercel.

CI runs lint, `fmt:check`, typecheck, the tests and the build on Node 20 and 22. Commit messages
follow [Conventional Commits](https://www.conventionalcommits.org/) (`feat:`, `fix:`, `docs:`,
`chore:`, ...).

## License

Licensed under the [MIT License](https://github.com/hunghg255/swagger-typescript-api-es/blob/master/LICENSE).
Licensed under the [MIT License](https://github.com/hunghg255/swagger-typescript-api-es/blob/main/LICENSE).

Based on [swagger-typescript-api](https://github.com/acacode/swagger-typescript-api) by
[acacode](https://github.com/acacode) (MIT). Rewritten to TypeScript and ES modules by
Expand Down
Empty file modified bin/cli.mjs
100644 → 100755
Empty file.
7 changes: 7 additions & 0 deletions docs/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
node_modules
.next
out
next-env.d.ts
*.tsbuildinfo
test-results
playwright-report
.vercel
1 change: 1 addition & 0 deletions docs/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
legacy-peer-deps=true
9 changes: 9 additions & 0 deletions docs/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->

# This is NOT the Next.js you know

This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.

This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.

<!-- END:nextjs-agent-rules -->
1 change: 1 addition & 0 deletions docs/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@AGENTS.md
118 changes: 117 additions & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
@@ -1 +1,117 @@
# Tiny docs template for markdown
# swagger-typescript-api-es — docs & playground

Next.js 16 (App Router) site with the documentation and an online playground.
The playground calls `POST /api/generate`, which runs the generator of this repository
(`swagger-typescript-api-es` is linked from the repository root with `file:..` and uses the
root `dist/`).

## Development

```bash
# 1. build the library (repository root)
cd ..
npm ci
npm run build

# 2. run the site (docs/)
cd docs
npm ci
npm run dev # http://localhost:3000
```

Rebuild the library (`npm run build` in the root) after changing `src/` or `templates/`.

| Command | What |
| ---------------------------------------- | ----------------------------------------------------------------------- |
| `npm run dev` | dev server |
| `npm run build` / `npm start` | production build / server |
| `npm run typecheck` | `tsc --noEmit` |
| `npm test` | unit tests (vitest, `tests/unit`) |
| `npm run test:e2e` | end-to-end tests (playwright, `tests/e2e`) |
| `NEXT_OUTPUT_STANDALONE=1 npx next build` | self-contained build in `.next/standalone` (checks the traced files) |

Try the API:

```bash
curl -s localhost:3000/api/generate -H 'content-type: application/json' \
-d "{\"spec\": $(node -p 'JSON.stringify(require("fs").readFileSync("../tests/fixtures/petstore.json","utf8"))'), \"options\": {\"modular\": true}}"
```

## `POST /api/generate`

Request / response types: [`lib/api-types.ts`](lib/api-types.ts).

```jsonc
// request (Content-Type: application/json)
{ "spec": "<JSON or YAML text>", "options": { "modular": true, "httpClientType": "axios" } }
{ "url": "https://example.com/openapi.json", "options": {} }

// 200
{ "ok": true, "files": [{ "name": "Api.ts", "content": "..." }], "durationMs": 123 }
// 4xx / 5xx
{ "ok": false, "error": "user facing message" }
```

| Status | When |
| ------ | --------------------------------------------------------------------------------------------- |
| 400 | invalid body / option / schema text, blocked URL (private network, credentials, scheme) |
| 413 | request or schema over `MAX_SPEC_BYTES` (3 MB), too complex schema, response over ~4.4 MB |
| 415 | `Content-Type` is not `application/json` |
| 422 | the schema could not be downloaded (HTTP error, timeout, redirects) or the generation failed |
| 429 | rate limited (`Retry-After` header) |
| 500 | unexpected error (details are only logged on the server) |

Code: `app/api/generate/route.ts` → `lib/server/` (`handler.ts`, `validate.ts`, `parse-spec.ts`,
`fetch-spec.ts`, `ip.ts`, `rate-limit.ts`, `generate.ts`).

### Security

- **Options are whitelisted** (`BOOLEAN_OPTIONS`, `STRING_OPTIONS`, `httpClientType`,
`moduleNameIndex`); unknown keys are dropped, known keys are type/format checked. Hooks,
templates, paths, custom functions etc. can never reach the generator, which always runs with
`output: false`, `silent: true`, `cleanOutput: false` and the document passed as `spec`.
- **Schema text**: max 3 MB, JSON or YAML (js-yaml safe schema), must have `openapi` / `swagger`;
documents are walked with a node budget and a depth limit (YAML alias bombs, recursion);
external `$ref`s (files / URLs) are rejected.
- **URLs (SSRF)**: the server downloads the schema itself (the library never fetches):
`http`/`https` only, no credentials, `localhost` / `*.local` / `*.internal` names are blocked, the
host is resolved once and **every** address must be public (private, loopback, link-local /
cloud metadata, CGNAT, multicast, reserved, documentation ranges, IPv4-mapped / NAT64 / 6to4
IPv6 forms of those, …). The connection is made to the checked address (pinned DNS lookup, so
DNS rebinding between the check and the connection is not possible; TLS still validates the
original host name). Redirects are followed manually (max 3) and every hop is checked again.
10 s timeout, 3 MB limit on the (decompressed) body, environment proxies are ignored.
- **Limits**: generation timeout 20 s, `maxDuration` 30 s. The timeout only stops waiting —
a pathological schema keeps the CPU busy until Vercel stops the function at `maxDuration`.
- **Rate limit**: 30 requests / minute / IP (`x-real-ip`, then `x-forwarded-for`), in memory.
Set `GENERATE_RATE_LIMIT` to change it (`0` disables it, e.g. for e2e tests). Each Vercel
instance has its own counters, so this is only a speed bump: **configure the Vercel Firewall**
(a rate limiting rule on `/api/generate`, attack challenge mode if needed) for real protection.

## Deploy on Vercel

1. Import the repository, set **Root Directory** to `docs` and keep
_Include files outside the root directory in the Build Step_ enabled (the library is built
from the repository root).
2. [`vercel.json`](vercel.json) does the rest:
- install: `cd .. && npm ci && npm run build && cd docs && npm ci` (root deps + library build,
then the site deps),
- build: `next build`, framework `nextjs`.
3. Node.js 20+ (22 recommended) in the project settings.
4. Add a Firewall rate limiting rule for `/api/generate`.

### How the generator gets into the function

The library is linked from `..`, so Turbopack would bundle it and break it (it replaces its
`__dirname`, so the templates are not found and the output is empty). `lib/server/generate.ts`
therefore imports `../dist/index.mjs` at runtime (not analysed by the bundler) and
[`next.config.ts`](next.config.ts) adds to the `/api/generate` function trace
(`outputFileTracingRoot` = repository root):

- `../dist/index.mjs`, `../dist/shared/**`, `../dist/templates/**`,
- the library's runtime dependency tree, computed from the root `package-lock.json`
(`swagger2openapi`, `oxfmt` + its native `@oxfmt/binding-*`, `typescript`, `eta`, …).

Check it with `NEXT_OUTPUT_STANDALONE=1 npx next build`, copy `.next/standalone` somewhere outside
the repository and run `node docs/server.js` there, or inspect
`.next/server/app/api/generate/route.js.nft.json`.
8 changes: 8 additions & 0 deletions docs/app/api/generate/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { createGenerateHandler } from '@/lib/server/handler';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
/** seconds; downloading (10s) + generation (20s) are bounded below this */
export const maxDuration = 30;

export const POST = createGenerateHandler();
83 changes: 83 additions & 0 deletions docs/app/docs/_lib/markdown-components.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import type { Components } from 'react-markdown';

import { CopyButton } from '@/components/copy-button';
import { site } from '@/components/site-config';

const LANG_LABEL: Record<string, string> = {
ts: 'TypeScript',
typescript: 'TypeScript',
js: 'JavaScript',
javascript: 'JavaScript',
json: 'JSON',
yaml: 'YAML',
yml: 'YAML',
bash: 'Terminal',
sh: 'Terminal',
diff: 'Diff',
text: 'Text',
};

function resolveHref(href: string | undefined): { href?: string; external: boolean } {
if (!href) return { href, external: false };
if (href.startsWith('#') || href.startsWith('/')) return { href, external: false };
if (/^[a-z]+:/i.test(href)) return { href, external: /^https?:/i.test(href) };
// relative repository link (e.g. `./skills`, `LICENSE`)
return { href: `${site.repo}/blob/main/${href.replace(/^\.\//, '')}`, external: true };
}

function Heading({ as: Tag, id, children }: { as: 'h2' | 'h3' | 'h4'; id?: string; children?: React.ReactNode }) {
return (
<Tag id={id}>
{id ? (
<a href={`#${id}`} className="heading-anchor">
{children}
<span className="anchor-hash" aria-hidden>
#
</span>
</a>
) : (
children
)}
</Tag>
);
}

export const markdownComponents: Components = {
h1: ({ id, children }) => <Heading as="h2" id={id}>{children}</Heading>,
h2: ({ id, children }) => <Heading as="h2" id={id}>{children}</Heading>,
h3: ({ id, children }) => <Heading as="h3" id={id}>{children}</Heading>,
h4: ({ id, children }) => <Heading as="h4" id={id}>{children}</Heading>,
a: ({ href, children, node: _node, ...rest }) => {
const resolved = resolveHref(href);
return (
<a
{...rest}
href={resolved.href}
{...(resolved.external ? { target: '_blank', rel: 'noreferrer' } : {})}
>
{children}
</a>
);
},
table: ({ children, node: _node, ...rest }) => (
<div className="scrollbar-thin my-6 overflow-x-auto rounded-xl border border-border" role="region" aria-label="Table" tabIndex={0}>
<table {...rest}>{children}</table>
</div>
),
pre: ({ children, node: _node, className, style: _style, tabIndex: _tabIndex, ...rest }) => {
const props = rest as Record<string, unknown>;
const code = typeof props['data-code'] === 'string' ? (props['data-code'] as string) : '';
const lang = typeof props['data-lang'] === 'string' ? (props['data-lang'] as string) : 'text';
return (
<div className="group relative my-5 overflow-hidden rounded-xl border border-border bg-code">
<div className="flex h-9 items-center justify-between border-b border-border bg-bg-subtle pr-1 pl-4">
<span className="text-xs font-medium text-fg-subtle">{LANG_LABEL[lang] ?? lang}</span>
<CopyButton text={code} />
</div>
<div className="code-surface scrollbar-thin">
<pre className={className}>{children}</pre>
</div>
</div>
);
},
};
38 changes: 38 additions & 0 deletions docs/app/docs/_lib/readme.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import 'server-only';

import { readRepoFile } from '@/components/repo-files';

export interface ReadmeContent {
/** intro paragraph (markdown) shown in the page header */
intro: string;
/** body markdown, starting at the first `##` section */
body: string;
}

const FALLBACK: ReadmeContent = {
intro: 'Generate a fully typed TypeScript API client from an OpenAPI 3 or Swagger 2 schema.',
body: '## Documentation unavailable\n\nThe repository README could not be found at build time. See the [README on GitHub](https://github.com/hunghg255/swagger-typescript-api-es#readme).',
};

/** Reads the repository README and strips the parts that do not fit a website. */
export function loadReadme(): ReadmeContent {
const raw = readRepoFile('README.md', '## Options reference');
if (!raw) return FALLBACK;
const text = raw.replace(/\r\n/g, '\n');

const firstSection = text.search(/^## /m);
if (firstSection === -1) return { intro: '', body: text };

// the header is a logo + badges HTML block followed by a short intro paragraph
const header = text.slice(0, firstSection);
const intro = header
.replace(/<p[\s\S]*?<\/p>/g, '')
.replace(/<[^>]+>/g, '')
.trim();

let body = text.slice(firstSection);
// the site renders its own navigation, so drop the "Table of contents" section
body = body.replace(/^## Table of contents\n[\s\S]*?(?=^## )/m, '');

return { intro, body };
}
Loading
Loading