### handle usage example with status handlers Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Example from the README showing how to handle each status code and narrow the data type using the handle function. ```TypeScript import { handle } from "@oazapfts/runtime"; const userId = await handle(api.register({ email, password }), { 200: (user: User) => user.id, // data is User 400: (err: string) => console.log(err), // data is string }); ``` -------------------------------- ### ok usage example Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Example from the README showing how to use ok to selectively apply optimistic handling on top of an explicit-mode client. The result is typed as the 2xx data (Pet). ```TypeScript import { ok } from "@oazapfts/runtime"; const pet = await ok(api.getPetById(1)); // pet is typed as the 2xx data (Pet) ``` -------------------------------- ### Example: using okify on a single method Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Shows how to wrap one API method with okify so it returns the Pet directly and throws HttpError on failure. The example imports okify from @oazapfts/runtime and calls the wrapped function with await. ```ts import { okify } from "@oazapfts/runtime"; const createPet = okify(api.addPet); // returns Pet directly, throws HttpError const pet = await createPet({ name: "Rex", photoUrls: [] }); ``` -------------------------------- ### Pass RequestOpts to getPetById Source: https://github.com/oazapfts/oazapfts/blob/main/README.md The last argument of each function is an optional RequestOpts object for fetch options, such as credentials, headers, or an AbortSignal. This example passes credentials and an Authorization header. ```ts const res = getPetById(1, { credentials: "include", headers: { Authorization: `Bearer ${token}`, }, }); ``` -------------------------------- ### Install oazapfts with npm Source: https://github.com/oazapfts/oazapfts/blob/main/README.md Install the oazapfts package as a runtime dependency. Note that as of version 6.0.0 the runtime has been moved to a separate package, @oazapfts/runtime. ```bash npm install oazapfts ``` -------------------------------- ### Example: converting a whole module with optimistic Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Shows how to wrap an entire generated API module with optimistic so all functions return data directly without ApiResponse unwrapping. The example imports the generated module and calls getPetById. ```ts import { optimistic } from "@oazapfts/runtime"; import * as api from "./generated-api"; const optimisticApi = optimistic(api); const pet = await optimisticApi.getPetById(1); // no ApiResponse unwrapping ``` -------------------------------- ### json usage example with import Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime-query.md Shows how to import and use json. The example serializes an object and a number, producing filter=%7B%22a%22%3A1%7D&limit=5 (filter={"a":1}, limit=5). ```ts import { json } from "@oazapfts/runtime/query"; json({ filter: { a: 1 }, limit: 5 }); // → "filter=%7B%22a%22%3A1%7D&limit=5" (filter={"a":1}, limit=5) ``` -------------------------------- ### joinUrl usage example Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime-util.md Demonstrates joinUrl with various inputs. The first call returns 'https://api.example.com/v2/pets', the second returns '/a//b'. ```ts import { joinUrl } from "@oazapfts/runtime/util"; joinUrl("https://api.example.com/", "/v2", "pets"); // "https://api.example.com/v2/pets" joinUrl("/", undefined, "a//", "b"); // "/a//b" ``` -------------------------------- ### Usage example for getRefName, getRefBasename, getReferenceName Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/resolve.md Shows how to import and use the three functions. getRefBasename returns the last path component; getRefName returns the full property path joined with underscores when the base starts with a digit; getReferenceName returns the basename for reference objects and undefined otherwise. ```ts import { getRefName, getRefBasename, getReferenceName } from "@oazapfts/resolve"; getRefBasename("#/components/schemas/Pet"); // "Pet" getRefName("#/components/schemas/123Schema"); // "components_schemas_123Schema" (digits-led base) getReferenceName({ $ref: "#/components/schemas/Tag" }); // "Tag" getReferenceName({ type: "string" }); // undefined ``` -------------------------------- ### handle usage example with fallback handler Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Example showing a fallback handler for unexpected statuses. The catch block only runs when the status has no handler and no default handler exists. ```TypeScript try { await handle(api.getPetById(1), { 200(pet) { /* ... */ }, default(status, data) { console.error(`unexpected ${status}:`, data); }, }); } catch (e) { // only reaches here when status had no handler AND no default handler existed } ``` -------------------------------- ### Override defaults: basePath, headers, credentials, fetch Source: https://github.com/oazapfts/oazapfts/blob/main/README.md The generated file exports a defaults constant to override basePath, provide a custom fetch implementation, send additional headers, or set any fetch option. Example imports node-fetch and sets credentials for CORS requests. ```TypeScript import * as api from "./api.ts"; import nodeFetch from "node-fetch"; // Override the spec's basePath api.defaults.basePath = "https://example.com/api"; // Send this header with each request api.defaults.headers = { access_token: "secret", }; // Include credentials in CORS requests, too api.defaults.credentials = "include"; // Use this instead of the global fetch api.defaults.fetch = nodeFetch; ``` -------------------------------- ### Install @oazapfts/resolve via npm Source: https://github.com/oazapfts/oazapfts/blob/main/packages/resolve/README.md Install the package using npm. This is the standard installation command for the @oazapfts/resolve package. ```bash npm install @oazapfts/resolve ``` -------------------------------- ### Customizing defaults in application code Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Example from the README showing how to customize the generated `defaults` object in application code. Sets baseUrl, headers (access_token), credentials, and a custom fetch implementation (nodeFetch). ```TypeScript import * as api from "./api.ts"; // generated api.defaults.baseUrl = "https://example.com/api"; api.defaults.headers = { access_token: "secret" }; api.defaults.credentials = "include"; api.defaults.fetch = nodeFetch; // custom fetch implementation ``` -------------------------------- ### createResolver usage example Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/resolve.md Example showing how to reuse a resolver across many lookups. Imports createResolver from @oazapfts/resolve and creates a resolver bound to the spec. ```ts import { createResolver } from "@oazapfts/resolve"; const resolveInDoc = createResolver(spec); const tag = resolveInDoc({ $ref: "#/components/schemas/Tag" }); ``` -------------------------------- ### Selective optimistic handling with ok helper Source: https://github.com/oazapfts/oazapfts/blob/main/README.md Use ok from @oazapfts/runtime to apply optimistic response handling to individual API calls while keeping full ApiResponse for others. ```TypeScript import { ok } from "@oazapfts/runtime"; const pet = await ok(api.getPetById(1)); ``` -------------------------------- ### Use named imports for tree-shaking Source: https://github.com/oazapfts/oazapfts/blob/main/README.md For large APIs, use individual named imports to enable tree-shaking and exclude unused code. ```ts import { getPetById } from "./my-generated-api.ts"; ``` -------------------------------- ### Example usage of resolve Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/resolve.md Shows how to import and use resolve to resolve a $ref to a schema object from a parsed OpenAPI document. ```TypeScript import { resolve } from "@oazapfts/resolve"; const doc = await parseSpecSource(); // Document with components.schemas.Pet const pet = resolve({ $ref: "#/components/schemas/Pet" }, { spec: doc }); ``` -------------------------------- ### oazapfts CLI usage and options Source: https://github.com/oazapfts/oazapfts/blob/main/README.md Shows the CLI command syntax and all available options. The spec can be a URL or local path to an OpenAPI or Swagger spec (json or yml). If the filename is omitted, the generated code is written to stdout. ```bash oazapfts [filename] Options: --exclude, -e tag to exclude --include, -i tag to include --optimistic --useEnumType --useUnknown --mergeReadWriteOnly --argumentStyle= (default: positional) --allSchemas --futureStripLegacyMethods --numericBooleanQueryParameters ``` -------------------------------- ### Usage example for numericBooleanReserved Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime-query.md Shows how to use `numericBooleanReserved` with `explode` to serialize booleans as `1`/`0`. The example produces `admin=1&count=5`. ```TypeScript import { explode, numericBooleanReserved } from "@oazapfts/runtime/query"; explode({ admin: true, count: 5 }, numericBooleanReserved); // → "admin=1&count=5" ``` -------------------------------- ### Example: plugin reads default base URL and overrides banner Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/oazapfts-context.md Shows how to create a context, override the spec-derived baseUrl, prepend a company banner, and generate source code. Uses createContext, parseSpec, generateAst, and printAst. ```TypeScript import { createContext } from "oazapfts/context"; import { parseSpec, generateAst, printAst } from "oazapfts"; const ctx = createContext(await parseSpec("./spec.json"), { mergeReadWriteOnly: true, }); // Override the spec-derived baseUrl (first server entry or "/") ctx.defaults.baseUrl = "https://api.example.com/v1"; // Prepend a company banner ctx.banner = ctx.banner + "\nCopyright (c) Example Corp"; const src = printAst(await generateAst(ctx)); ``` -------------------------------- ### Use handle helper with status handlers Source: https://github.com/oazapfts/oazapfts/blob/main/README.md Simplify response handling with the handle helper from @oazapfts/runtime. It throws an HttpError for any unhandled status code unless a default handler is provided. ```ts import { handle } from "@oazapfts/runtime"; await handle(api.getPetById(1), { 200(pet) { // pet is properly typed as Pet }, 404(message) { // message is as string }, }); ``` -------------------------------- ### Application code example using mergeHeaders Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime-headers.md Demonstrates merging custom headers with null values ignored and boolean/number values coerced to strings. The resulting Headers object returns string values for all keys. ```TypeScript import { mergeHeaders } from "@oazapfts/runtime/headers"; const h = mergeHeaders( { "x-app": "my-app", "x-correlation-id": null }, { "x-correlation-id": "abc", trace: true, count: 3 }, ); h.get("x-app"); // "my-app" h.get("x-correlation-id"); // "abc" (null in base ignored) h.get("trace"); // "true" h.get("count"); // "3" ``` -------------------------------- ### delimited usage example Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime-util.md Shows how to use the delimited factory with a custom delimiter '|'. The output is 'color=red|blue&n=1', skipping the undefined 'tags' parameter. ```ts import { delimited } from "@oazapfts/runtime/util"; const d = delimited("|"); d({ color: ["red", "blue"], tags: undefined, n: 1 }); // → "color=red|blue&n=1" ``` -------------------------------- ### query usage example Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime-query.md Shows how to use the query function with explode and form serializers. Outputs '?status=sold&limit=10' for non-empty params, and empty string for no params. ```ts import { query, explode, form } from "@oazapfts/runtime/query"; query(explode({ status: "sold" }), form({ limit: 10 })); // → "?status=sold&limit=10" query(); // → "" query(explode({})); // → "" ``` -------------------------------- ### Example: print an AST with a custom banner modification Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/oazapfts.md Shows how to generate and print an AST after modifying the banner. The ctx.banner is set to a custom string before printing. ```TypeScript import { generateAst, printAst, parseSpec } from "oazapfts"; import { createContext } from "oazapfts/context"; const ctx = createContext(await parseSpec("./api.json")); ctx.banner = "Generated from internal spec"; const source = printAst(await generateAst(ctx)); ``` -------------------------------- ### Import generated API and call getPetById Source: https://github.com/oazapfts/oazapfts/blob/main/README.md Use the generated API by importing the module and calling the function matching the operationId. The function returns a Promise; here it is used without await. ```ts import * as api from "./my-generated-api.ts"; const res = api.getPetById(1); ``` -------------------------------- ### getRefBasename(ref: string): string Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/resolve.md Get the last path component of the given ref. ```APIDOC ## Function: getRefBasename ### Description Get the last path component of the given ref. ### Signature `(ref: string) => string` ### Parameters - **ref** (string) - Required - The reference string. ### Returns - **string** - The last `/-separated` component of the ref string. ### Example ```ts import { getRefBasename } from "@oazapfts/resolve"; getRefBasename("#/components/schemas/Pet"); // "Pet" ``` ``` -------------------------------- ### deep usage example with import Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime-query.md Shows how to import and use deep. The first call serializes a nested object to color[R]=100&color[G]=200&color[B]=150; the second serializes an array without an index to a[]=1&a[]=2. ```ts import { deep } from "@oazapfts/runtime/query"; deep({ color: { R: 100, G: 200, B: 150 } }); // → "color[R]=100&color[G]=200&color[B]=150" deep({ a: [1, 2] }); // → "a[]=1&a[]=2" ``` -------------------------------- ### encode usage example with encodeReserved Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime-util.md Shows how to create a query encoder using encode with encodeReserved and apply it to template strings. The comments show expected outputs: spaces become %20, arrays are joined with commas, objects are flattened and encoded, and undefined interpolations become empty strings. ```TypeScript import { encode, encodeReserved } from "@oazapfts/runtime/util"; const q = encode(encodeReserved); q`${'"a b"'}=${[1, 2, 3]}`; // "a%20b=1,2,3" q`${'"x"'}=${{ k: "v w" }}`; // "x=k,v%20w" q`${'"y"'}=${undefined}`; // "y=" ``` -------------------------------- ### Example: building an AST without printing Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/oazapfts.md Shows how to parse an OpenAPI spec and generate an AST using generateAst. Requires createContext from 'oazapfts/context' and parseSpec from 'oazapfts'. The ctx is created with allSchemas: true. ```TypeScript import { createContext } from "oazapfts/context"; import { generateAst, parseSpec } from "oazapfts"; const doc = await parseSpec("./api.json"); const ctx = createContext(doc, { allSchemas: true }); const ast = await generateAst(ctx); ``` -------------------------------- ### explode usage example Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime-query.md Demonstrates explode serialization: arrays expand to repeated keys, numericBooleanReserved converts booleans to 1/0, nested objects are flattened without key prefixing. ```ts import { explode, numericBooleanReserved } from "@oazapfts/runtime/query"; explode({ tags: ["a", "b"], flag: true }); // → "tags=a&tags=b&flag=true" explode({ flag: true }, numericBooleanReserved); // → "flag=1" explode({ nested: { a: 1 } }); // → "a=1" ``` -------------------------------- ### Usage example for form, pipe, space Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime-query.md Shows how to import and use the three delimited variants. Each function serializes an array parameter into a query string with the respective delimiter: `form` produces `color=1,2,3`, `pipe` produces `color=1|2|3`, `space` produces `color=1%202%203`. ```TypeScript import { form, pipe, space } from "@oazapfts/runtime/query"; form({ color: [1, 2, 3] }); // "color=1,2,3" pipe({ color: [1, 2, 3] }); // "color=1|2|3" space({ color: [1, 2, 3] }); // "color=1%202%203" ``` -------------------------------- ### Use handle helper with default handler Source: https://github.com/oazapfts/oazapfts/blob/main/README.md Add a default handler to catch any unhandled status codes, preventing the HttpError from being thrown. The default handler receives the status and data. ```ts await handle(api.getPetById(1), { 200(pet) { // ... }, default(status, data) { // handle error }, }); ``` -------------------------------- ### Generated servers export from demo/api.ts Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/configuration.md Example of the generated `servers` export produced by `createServersStatement`. It includes a plain URL string for servers without variables and an arrow function for servers with variables, destructuring each variable with its default value and type union. ```TypeScript export const servers = { server1: "https://petstore.swagger.io/v2", server2: ({ protocol = "https", stage = "staging", version = "v1", }: { protocol: "http" | "https"; stage: "test" | "staging" | "production"; version: "v1" | "v2"; }) => `${protocol}://${stage}.petstore.example.org/${version}`, }; ``` -------------------------------- ### Narrow response type with status check Source: https://github.com/oazapfts/oazapfts/blob/main/README.md Use a type guard by checking res.status to narrow the data type. In the 200 branch, data is Pet; in the 404 branch, data is a string; the else branch handles other errors. ```ts const res = await api.getPetById(1); if (res.status === 200) { const pet = res.data; // pet is properly typed as Pet } if (res.status === 404) { const message = res.data; // message is a string } else { // handle the error } ``` -------------------------------- ### Basic generateSource call with local spec Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/oazapfts.md Example of calling generateSource with a local spec file path and the optimistic option. The returned code is a string ready to be written to a .ts file. ```TypeScript import { generateSource } from "oazapfts"; const code = await generateSource( "/path/to/petstore.json", { optimistic: true }, ); // code is a string ready to be written to a .ts file ``` -------------------------------- ### Example: filter endpoints and add header parameter via UNSTABLE_plugins Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/oazapfts-plugin.md Shows how to create a plugin with UNSTABLE_createPlugin, tap filterEndpoint to skip internal endpoints, and tap generateMethod to augment the method body. Uses the UNSTABLE_plugins option in generateSource. ```TypeScript import { UNSTABLE_createPlugin } from "oazapfts/plugin"; import { generateSource } from "oazapfts"; const tracePlugin = UNSTABLE_createPlugin( (hooks) => { // Skip everything tagged "internal" hooks.filterEndpoint.tap("skipInternal", (generate, endpoint, ctx) => { if (endpoint.operation.tags?.includes("internal")) return false; return generate; }); // Augment the generated method body hooks.generateMethod.tapPromise("addTraceHeader", async (endpoint, ctx) => { // return undefined to delegate to the default generator; returning // methods here would replace it entirely (bail hook) return undefined; }); }, { name: "trace-plugin", precedence: "eager" }, ); const src = await generateSource("./api.json", { UNSTABLE_plugins: [tracePlugin], }); ``` -------------------------------- ### Override defaults at runtime Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/configuration.md Consumers can override the generated defaults at runtime by assigning new values to the exported defaults object. This example sets a custom baseUrl, headers, credentials, and a custom fetch implementation (node-fetch). ```TypeScript import * as api from "./api.ts"; import nodeFetch from "node-fetch"; api.defaults.baseUrl = "https://example.com/api"; api.defaults.headers = { access_token: "secret" }; api.defaults.credentials = "include"; api.defaults.fetch = nodeFetch; ``` -------------------------------- ### Optimistic mode: consume response as Pet type Source: https://github.com/oazapfts/oazapfts/blob/main/README.md Use with the --optimistic command line argument. Each function returns a Promise for the happy path (first 2xx response). Non-200 responses reject the promise with an HttpError. ```TypeScript const pet = await api.getPetById(1); // pet is now typed as Pet! ``` -------------------------------- ### Per-call opts override defaults Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/configuration.md Each generated function accepts a trailing Oazapfts.RequestOpts argument that overrides defaults for that call only. This example passes credentials, custom headers, and an abort signal to getPetById. ```TypeScript const res = api.getPetById(1, { credentials: "include", headers: { Authorization: `Bearer ${token}` }, signal: controller.signal, }); ``` -------------------------------- ### generateSource with URL spec, options, and error handling Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/oazapfts.md Example using the default export (which is generateSource) with a URL spec and various options like include, enumStyle, argumentStyle, and futureStripLegacyMethods. Includes error handling for non-OpenAPI v3 specs, checking for the 'Only OpenAPI v3' error message. ```TypeScript import generateSource from "oazapfts"; // default export is generateSource try { const ts = await generateSource("https://example.com/api/openapi.json", { include: ["store"], // only generate tagged endpoints enumStyle: "enum", argumentStyle: "object", futureStripLegacyMethods: true, }); await writeFile("api.ts", ts); } catch (err) { if (err instanceof Error && /Only OpenAPI v3/.test(err.message)) { console.error("Spec must be OpenAPI v3, convert it first"); } console.error(err); } ``` -------------------------------- ### Generated getPetById function in explicit mode Source: https://github.com/oazapfts/oazapfts/blob/main/README.md Example of a generated function in explicit mode. It returns a Promise for an ApiResponse union discriminated by status, with typed data for 200 and 400, and no data for 404. ```ts /** * Find pet by ID */ export function getPetById(petId: number, opts?: Oazapfts.RequestOpts) { return oazapfts.fetchJson< | { status: 200; data: Pet; } | { status: 400; data: string; } | { status: 404; } >(`/pet/${encodeURIComponent(petId)}`, { ...opts, }); } ``` -------------------------------- ### json(opts) Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Builds a RequestInit-like object for JSON requests. Sets body to JSON.stringify(body) and Content-Type to application/json (unless already provided). ```APIDOC ## json(opts) ### Description Builds a RequestInit-like object for JSON requests. Sets body to JSON.stringify(body) and Content-Type to application/json (unless already provided). ### Parameters - **opts** (JsonRequestOpts) - Required - Options with a `body` field (any type). ### Returns A RequestInit-like object with `body` and `Content-Type` header set. ``` -------------------------------- ### form(opts) Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Builds a RequestInit-like object for URL-encoded form requests. Serializes body with qs.form and sets Content-Type to application/x-www-form-urlencoded. ```APIDOC ## form(opts) ### Description Builds a RequestInit-like object for URL-encoded form requests. Serializes body with qs.form and sets Content-Type to application/x-www-form-urlencoded. ### Parameters - **opts** (FormRequestOpts) - Required - Options with a `body` field (Record). ### Returns A RequestInit-like object with `body` and `Content-Type` header set. ``` -------------------------------- ### Custom fetch, auth header, binary download, multipart upload with error handling Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Shows a runtime instance with a custom `fetch` that adds an Authorization header, a multipart upload via `fetchBlob` and `multipart`, a url-encoded form via `fetchText` and `form`, and `HttpError` handling. Multipart primitives are stringified, arrays append one entry each, and objects become JSON blobs. ```TypeScript import { runtime } from "@oazapfts/runtime"; import { HttpError } from "@oazapfts/runtime"; const client = runtime({ baseUrl: "https://api.example.com", fetch: (input, init) => fetch(input, { ...init, headers: { ...(init?.headers ?? {}), Authorization: `Bearer ${token}` }, }), }); try { // multipart upload: primitives are stringified, arrays append one entry each, // objects become JSON blobs const up = await client.fetchBlob<{ status: 200; data: Blob }>("/upload", { method: "POST", ...client.multipart({ body: { file: fileInput.files[0], tags: ["a", "b"], // two form entries named "tags" meta: { kind: "photo" }, // appended as a JSON Blob public: true, // appended as "true" }, }), }); // url-encoded form await client.fetchText("/login", client.form({ body: { user, pass } })); } catch (e) { if (e instanceof HttpError) { console.error(`HTTP ${e.status}`, e.data, e.headers); } } ``` -------------------------------- ### End-to-end programmatic usage of building blocks Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/oazapfts-generate.md Shows how to parse an OpenAPI document, create a context, create hooks, inspect a schema conversion, resolve method names, and generate an API file. Uses UNSTABLE_createHooks and requires allSchemas: true in the context. ```ts import { createContext } from "oazapfts/context"; import { UNSTABLE_createHooks } from "oazapfts/plugin"; import { generateApi, getOperationName, getTypeFromSchema, } from "oazapfts/generate"; import { parseSpec, printAst } from "oazapfts"; const doc = await parseSpec("./api.yaml"); const ctx = createContext(doc, { allSchemas: true }); const hooks = UNSTABLE_createHooks(); // Inspect a schema conversion directly: const pet = doc.components?.schemas?.Pet; if (pet) { const typeNode = getTypeFromSchema(ctx, pet, "Pet"); console.log(printAst(typeNode as any)); // e.g. { id?: number; name: string; ... } } // Resolve method names before generating: const names = getOperationNames("GET", "/pet/{petId}", undefined, new Map()); console.log(names.primaryName); // "getPetByPetId" const file = await generateApi(ctx, hooks); console.log(printAst(file)); ``` -------------------------------- ### multipart(opts) Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Builds a RequestInit-like object for multipart form data requests. Creates a FormData instance and appends fields according to their types. ```APIDOC ## multipart(opts) ### Description Builds a RequestInit-like object for multipart form data requests. Creates a FormData instance and appends fields according to their types. ### Parameters - **opts** (MultipartRequestOpts) - Required - Options with a `body` field (Record). ### Returns A RequestInit-like object with a `FormData` body. ### Behavior - Arrays append one entry per value. - Objects/unknown values append a JSON `Blob` of type `application/json`. - Numbers/booleans are stringified. ``` -------------------------------- ### getRefBasename implementation from src/getRefBasename.ts Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/resolve.md Gets the last path component of the given ref. ```ts /** * Get the last path component of the given ref. */ export function getRefBasename(ref: string) { return ref.replace(/.+\//, ""); } ``` -------------------------------- ### Basic usage with fetchJson and json Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Mirrors generated code: creates a runtime instance with a base URL, then calls `fetchJson` with a JSON body built by `api.json`. Logs the response data when the status is 200. ```TypeScript import * as Oazapfts from "@oazapfts/runtime"; const api = Oazapfts.runtime({ baseUrl: "https://petstore.swagger.io/v2" }); const res = await api.fetchJson<{ status: 200; data: Pet }>("/pet/1", { ...api.json({ method: "POST", body: { name: "Rex" } }), }); if (res.status === 200) console.log(res.data); ``` -------------------------------- ### runtime(defaults) Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Factory function that creates a runtime object with methods for making HTTP requests. It accepts default request options and returns an object with methods like fetchText, fetchJson, fetchBlob, and helpers for building request bodies. ```APIDOC ## runtime(defaults) ### Description Creates a runtime object with methods for making HTTP requests. Accepts default request options that are merged under per-request options. ### Parameters - **defaults** (RequestOpts) - Optional, default `{}` - Default options: `baseUrl`, custom `fetch`, `headers`, and any `RequestInit` options. ### Returns An object with the following members: - `ok` - Unwraps 2xx responses, throws `HttpError` otherwise. - `fetchText` - Fetches and returns response text. - `fetchJson` - Fetches and parses JSON response. - `fetchBlob` - Fetches and returns response as Blob. - `mergeHeaders` - Merges headers, later wins. - `json` - Builds a JSON request body. - `form` - Builds a URL-encoded form request body. - `multipart` - Builds a multipart form data request body. ### Example ```ts import * as Oazapfts from "@oazapfts/runtime"; const api = Oazapfts.runtime({ baseUrl: "https://petstore.swagger.io/v2" }); const res = await api.fetchJson<{ status: 200; data: Pet }>("/pet/1", { ...api.json({ method: "POST", body: { name: "Rex" } }), }); if (res.status === 200) console.log(res.data); ``` ``` -------------------------------- ### optimistic(api) Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Converts a whole namespace/object of API functions into optimistic mode at runtime. Every function in the object is wrapped with okify, while non-function values are kept as-is. ```APIDOC ## optimistic(api) ### Description Converts a whole namespace/object of API functions into optimistic mode at runtime. Every function in the object is wrapped with okify, while non-function values are kept as-is. ### Signature ```ts export function optimistic>( api: T, ): OptimisticApi ``` ### Parameters - **api** (`T extends Record`) - Required - A namespace/object of API functions (e.g. `import * as api`) ### Return Value `OptimisticApi` — an object with the same keys where every function is replaced by its `okify` wrapper; non-function values are kept as-is. (`OptimisticApi` itself is not exported.) ### Example ```ts import { optimistic } from "@oazapfts/runtime"; import * as api from "./generated-api"; const optimisticApi = optimistic(api); const pet = await optimisticApi.getPetById(1); // no ApiResponse unwrapping ``` ``` -------------------------------- ### Supporting types for okify Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Type definitions used by okify: Args extracts the argument list, ApiFunction is the expected function shape, AsyncReturnType gets the resolved type, OkResponse extracts the success response, and Okify is the wrapper type. ```ts export type Args = T extends (...args: infer U) => any ? U : any; export type ApiFunction = (...args: any[]) => Promise>; export type AsyncReturnType = T extends (...args: any[]) => Promise ? V : never; export type OkResponse = SuccessResponse< AsyncReturnType >; export type Okify = ( ...args: Args ) => Promise>; ``` -------------------------------- ### Reuse parsed document across multiple generateSource runs Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/oazapfts.md Example showing how to parse a remote OpenAPI spec once and reuse the resulting document for multiple generateSource calls with different argument styles. ```ts import { parseSpec, generateSource } from "oazapfts"; const doc = await parseSpec("https://petstore.swagger.io/v2/swagger.json"); const positional = await generateSource(doc, { argumentStyle: "positional" }); const objectStyle = await generateSource(doc, { argumentStyle: "object" }); ``` -------------------------------- ### getRefName implementation from src/getRefName.ts Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/resolve.md Returns a name for the given ref that can be used as basis for a type alias. Usually the baseName, unless the ref starts with a number, in which case the whole ref is returned with slashes turned into underscores. ```ts /** * Returns a name for the given ref that can be used as basis for a type * alias. This usually is the baseName, unless the ref starts with a number, * in which case the whole ref is returned, with slashes turned into * underscores. */ export function getRefName(ref: string) { const base = getRefBasename(ref); if (/^\d+/.test(base)) { return refPathToPropertyPath(ref).join("_"); } return base; } ``` -------------------------------- ### getPetById(petId: number, opts?: Oazapfts.RequestOpts) Source: https://github.com/oazapfts/oazapfts/blob/main/README.md Generated function to find a pet by ID. Returns a Promise for an ApiResponse object with status and data properties, typed as a union of possible responses discriminated by status. ```APIDOC ## getPetById(petId: number, opts?: Oazapfts.RequestOpts) ### Description Find pet by ID. Returns a Promise for an ApiResponse object with status and data properties, typed as a union of possible responses discriminated by status. ### Method GET ### Endpoint `/pet/${encodeURIComponent(petId)}` ### Parameters #### Path Parameters - **petId** (number) - Required - The ID of the pet to fetch. #### Optional Parameters - **opts** (Oazapfts.RequestOpts) - Optional - Fetch options, including headers, credentials, AbortSignal, baseUrl override, or custom fetch implementation. ### Response #### Success Response (200) - **data** (Pet) - The pet object. #### Error Response (400) - **data** (string) - Error message. #### Error Response (404) - No data property. ### Response Example ```json { "status": 200, "data": { "id": 1, "name": "Fido" } } ``` ``` -------------------------------- ### Type a custom spec transformer against the OpenAPI namespace Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/oazapfts.md Example showing how to use the OpenAPI namespace to type a function that adds a tag to all operations in an OpenAPI document. Uses parseSpec from oazapfts and casts to OpenAPI.OperationObject. ```ts import { parseSpec } from "oazapfts"; import type { OpenAPI } from "oazapfts"; async function addTag(spec: string): Promise { const doc = await parseSpec(spec); for (const pathItem of Object.values(doc.paths ?? {})) { for (const [, operation] of Object.entries(pathItem ?? {})) { if (operation && "tags" in operation) { (operation as OpenAPI.OperationObject).tags = ["all"]; } } } return doc; } ``` -------------------------------- ### joinUrl(...parts) Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime-util.md Joins URL segments into a single path, stripping leading slashes from all but the first segment and trailing slashes from all but the last. It drops falsy segments. ```APIDOC ## joinUrl(...parts) ### Description Joins URL segments into a single path, stripping leading slashes from all but the first segment and trailing slashes from all but the last. It drops falsy segments. ### Signature ```ts export function joinUrl(...parts: Array): string ``` ### Parameters - **parts** (`...Array`) - Required - URL segments (falsy segments dropped). ### Return `string` — segments joined with a single `/`: leading slashes are stripped from every segment after the first; trailing slashes are stripped from every segment except the last. ### Example ```ts import { joinUrl } from "@oazapfts/runtime/util"; joinUrl("https://api.example.com/", "/v2", "pets"); // "https://api.example.com/v2/pets" joinUrl("/", undefined, "a//", "b"); // "/a//b" ``` ``` -------------------------------- ### getRefName(ref: string): string Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/resolve.md Returns a name for the given ref that can be used as basis for a type alias. This usually is the baseName, unless the ref starts with a number, in which case the whole ref is returned, with slashes turned into underscores. ```APIDOC ## Function: getRefName ### Description Returns a name for the given ref that can be used as basis for a type alias. This usually is the baseName, unless the ref starts with a number, in which case the whole ref is returned, with slashes turned into underscores. ### Signature `(ref: string) => string` ### Parameters - **ref** (string) - Required - The reference string. ### Returns - **string** - The alias basis: last path segment, or (when it starts with a digit) the full property path joined with `_`. ### Example ```ts import { getRefName } from "@oazapfts/resolve"; getRefName("#/components/schemas/123Schema"); // "components_schemas_123Schema" ``` ``` -------------------------------- ### oazapfts CLI usage and options Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/configuration.md Usage text printed by the oazapfts CLI. Lists all supported flags, aliases, and defaults. Note that --useEnumType is deprecated in favor of --enumStyle=enum, and invalid values for --enumStyle or --argumentStyle exit with code 1. ```text oazapfts [filename] Options: --exclude, -e --include, -i --help, -h --version, -v --optimistic --useEnumType (deprecated, use --enumStyle=enum) --enumStyle= (default: union) --useUnknown --mergeReadWriteOnly --argumentStyle= (default: positional) --allSchemas --numericBooleanQueryParameters --futureStripLegacyMethods ``` -------------------------------- ### createContext(doc, options) Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/oazapfts-generate.md Creates an Oazapfts context from a parsed OpenAPI document and options. The context is used throughout the generation process. ```APIDOC ## createContext(doc, options) ### Description Creates an Oazapfts context from a parsed OpenAPI document and options. The context is used throughout the generation process. ### Signature ```ts export function createContext(doc: OpenAPIDocument, options?: Partial): OazapftsContext ``` ### Parameters - **doc** (`OpenAPIDocument`) - Required - The parsed OpenAPI document. - **options** (`Partial`) - Optional - Generation options (e.g., `allSchemas`). ### Return `OazapftsContext` - The context object. ``` -------------------------------- ### Create a resolver and resolve a $ref Source: https://github.com/oazapfts/oazapfts/blob/main/packages/resolve/README.md Import createResolver from @oazapfts/resolve, pass an OpenAPI spec object, and call the returned resolver with a $ref string to resolve the referenced schema. The example logs the resolved Test schema to the console. ```typescript import { createResolver } from "@oazapfts/resolve"; const spec = { openapi: "3.0.0", info: { title: "Test API", version: "1.0.0" }, paths: {}, components: { schemas: { Test: { type: "object", properties: { id: { type: "string" }, }, }, }, }, }; const resolve = createResolver(spec); console.log(resolve({ $ref: "#/components/schemas/Test" })); ``` -------------------------------- ### fetchJson(url, req?) Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Fetches a URL and parses the response as JSON when the content-type contains 'json'. Adds 'Accept: application/json' header. Returns a WithHeaders object. ```APIDOC ## fetchJson(url, req?) ### Description Fetches a URL and parses the response as JSON when the content-type contains 'json'. Adds 'Accept: application/json' header. Returns a WithHeaders object. ### Parameters - **url** (string) - Required - The URL to fetch. - **req** (FetchRequestOpts) - Optional, default `{}` - Request options. ### Returns A `WithHeaders` object containing the parsed data and headers. ### Example ```ts const res = await api.fetchJson<{ status: 200; data: Pet }>("/pet/1", { ...api.json({ method: "POST", body: { name: "Rex" } }), }); ``` ``` -------------------------------- ### Generated defaults export and runtime initialization Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/configuration.md Every generated file includes this defaults export and runtime initialization. The baseUrl defaults to the first spec server URL with variable defaults substituted, or "/" if none. The headers object is always emitted and sent with every request. ```TypeScript export const defaults: Oazapfts.Defaults = { headers: {}, baseUrl: "https://petstore.swagger.io/v2", // first spec server, else "/" }; const oazapfts = Oazapfts.runtime(defaults); ``` -------------------------------- ### Import path for oazapfts/generate Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/oazapfts-generate.md Import the generation building blocks from the 'oazapfts/generate' subpath. ```typescript import { generateApi, getTypeFromSchema } from "oazapfts/generate" ``` -------------------------------- ### generateApi(ctx, hooks) Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/oazapfts-generate.md Generates the API client code from the OpenAPI document and hooks. Returns an AST that can be printed. ```APIDOC ## generateApi(ctx, hooks) ### Description Generates the API client code from the OpenAPI document and hooks. Returns an AST that can be printed. ### Signature ```ts export function generateApi(ctx: OazapftsContext, hooks: Hooks): Promise ``` ### Parameters - **ctx** (`OazapftsContext`) - Required - The context containing the parsed OpenAPI document and options. - **hooks** (`Hooks`) - Required - Hooks for customizing generation. ### Return `Promise` - The generated AST representing the API client code. ``` -------------------------------- ### Request body types for runtime methods Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Type definitions for the request body options accepted by the runtime object's methods. `FetchRequestOpts` allows string, FormData, or Blob bodies; `JsonRequestOpts` accepts any body; `FormRequestOpts` and `MultipartRequestOpts` expect record-like bodies. ```TypeScript type FetchRequestOpts = RequestOpts & { body?: string | FormData | Blob; }; type JsonRequestOpts = RequestOpts & { body?: any; }; type FormRequestOpts = RequestOpts & { body?: Record; }; type MultipartRequestOpts = RequestOpts & { body?: Record; }; ``` -------------------------------- ### fetchBlob(url, req?) Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime.md Fetches a URL and returns the response body as a Blob. Returns a WithHeaders object. ```APIDOC ## fetchBlob(url, req?) ### Description Fetches a URL and returns the response body as a Blob. Returns a WithHeaders object. ### Parameters - **url** (string) - Required - The URL to fetch. - **req** (FetchRequestOpts) - Optional, default `{}` - Request options. ### Returns A `WithHeaders` object containing the Blob data and headers. ### Example ```ts const up = await client.fetchBlob<{ status: 200; data: Blob }>("/upload", { method: "POST", ...client.multipart({ body: { file: fileInput.files[0], tags: ["a", "b"], meta: { kind: "photo" }, public: true, }, }), }); ``` ``` -------------------------------- ### joinUrl function signature Source: https://github.com/oazapfts/oazapfts/blob/main/_autodocs/api-reference/runtime-util.md Joins URL segments with a single '/', stripping leading slashes from all but the first segment and trailing slashes from all but the last. Falsy segments are dropped. ```ts export function joinUrl(...parts: Array) { return parts .filter(Boolean) .map((s, i) => (i === 0 ? s : s!.replace(/^\/+/, ""))) .map((s, i, a) => (i === a.length - 1 ? s : s!.replace(/\/+$/, ""))) .join("/"); } ```