@counterfact/client 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +41 -0
- package/README.md +22 -1
- package/dist/fetch-auth.d.ts +23 -0
- package/dist/fetch-auth.js +138 -0
- package/dist/fetch.d.ts +167 -0
- package/dist/fetch.js +580 -0
- package/dist/media-type.d.ts +4 -0
- package/dist/media-type.js +50 -0
- package/dist/multipart-form.d.ts +2 -0
- package/dist/multipart-form.js +85 -0
- package/dist/route-builder.js +3 -1
- package/dist/route-catalog.js +2 -2
- package/dist/validation-helpers.d.ts +3 -0
- package/dist/validation-helpers.js +11 -0
- package/package.json +13 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,46 @@
|
|
|
1
1
|
# @counterfact/client
|
|
2
2
|
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 0bc24a0: Generate Fetch clients for Swagger 2.0 in normal and client-only generation.
|
|
8
|
+
The fluent client and named SDK use Swagger response schemas for validation
|
|
9
|
+
and support legacy array encodings, form fields, file bodies, and Basic
|
|
10
|
+
authentication.
|
|
11
|
+
- 6ea99b0: OpenAPI 3.x type generation now includes a Fetch client under `client/`. Use
|
|
12
|
+
`--generate-client` to generate only the client. Reuse route prefixes with
|
|
13
|
+
`segment()` and send requests once all required inputs are present. Validated
|
|
14
|
+
responses narrow by matched status. Responses outside the contract reject with
|
|
15
|
+
an error. Response validators are compiled during generation.
|
|
16
|
+
|
|
17
|
+
Generated clients apply OpenAPI security requirements and support per-request
|
|
18
|
+
authentication, credentials, redirect handling, and cancellation.
|
|
19
|
+
|
|
20
|
+
Completed fluent requests can call `stream()` to read declared byte responses
|
|
21
|
+
as they arrive.
|
|
22
|
+
|
|
23
|
+
Use `createSdk()` for named operations grouped by path segment or OpenAPI tag.
|
|
24
|
+
The named SDK shares request handling and validated response types with the fluent client.
|
|
25
|
+
|
|
26
|
+
- de2bd09: Accept typed OpenAPI 3.x multipart objects in the fluent client and named SDK.
|
|
27
|
+
File fields accept File, Blob, or Uint8Array.
|
|
28
|
+
- 31b46b0: Generate one Fetch client entry point per versioned API group. Fluent clients select the request and response types from the configured URL prefix in the route path, such as `route("/v2/greeting")`. Named SDKs select the contract with `version()`.
|
|
29
|
+
|
|
30
|
+
Import the root fluent client to call every configured API from one route function. Import a specific group or version to include only its contracts in your application.
|
|
31
|
+
|
|
32
|
+
### Patch Changes
|
|
33
|
+
|
|
34
|
+
- Updated dependencies [0bc24a0]
|
|
35
|
+
- Updated dependencies [6ea99b0]
|
|
36
|
+
- @counterfact/types@0.4.0
|
|
37
|
+
|
|
38
|
+
## 0.2.2
|
|
39
|
+
|
|
40
|
+
### Patch Changes
|
|
41
|
+
|
|
42
|
+
- 0d35a14: Handle prototype-named cookie/query inputs as ordinary own data properties, preserve unchanged context initializers containing an own `__proto__` key, and ignore inherited names when completing scenario groups.
|
|
43
|
+
|
|
3
44
|
## 0.2.1
|
|
4
45
|
|
|
5
46
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -4,7 +4,28 @@ Counterfact's raw HTTP client and immutable, OpenAPI-aware request builder.
|
|
|
4
4
|
Use it to construct, inspect, reuse, and send requests without starting the
|
|
5
5
|
Counterfact REPL or simulator.
|
|
6
6
|
|
|
7
|
-
##
|
|
7
|
+
## Generate a typed Fetch client
|
|
8
|
+
|
|
9
|
+
Run `npx counterfact@latest openapi.yaml ./generated --generate-client` and
|
|
10
|
+
import `createClient` from `./generated/index.js`. The generated entry point
|
|
11
|
+
uses the browser-compatible `@counterfact/client/fetch` export.
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { createClient } from "./generated/index.js";
|
|
15
|
+
|
|
16
|
+
const route = createClient({ baseUrl: "https://example.com" });
|
|
17
|
+
const tenant = route("/{tenantId}/v1").path({ tenantId: "acme" });
|
|
18
|
+
const order = tenant.segment("orders/{orderId}").method("get");
|
|
19
|
+
const result = await order.path({ orderId: "123" }).send();
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
A builder preserves path values as you append a segment. TypeScript offers
|
|
23
|
+
`send()` once the selected operation's required inputs are present. Check
|
|
24
|
+
`matchedStatus` to narrow a response body. A response outside the contract
|
|
25
|
+
rejects with `InvalidResponseError`. Response validators are compiled during
|
|
26
|
+
generation and run without dynamic code evaluation in the browser.
|
|
27
|
+
|
|
28
|
+
## Reusable requests in Node
|
|
8
29
|
|
|
9
30
|
```js
|
|
10
31
|
import {
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ClientSendOptions, ClientSecurityScheme } from "@counterfact/types/client-route";
|
|
2
|
+
export interface CookieCredential {
|
|
3
|
+
credentials: "include" | "same-origin";
|
|
4
|
+
}
|
|
5
|
+
export interface BasicCredential {
|
|
6
|
+
username: string;
|
|
7
|
+
password: string;
|
|
8
|
+
}
|
|
9
|
+
type Credential = string | CookieCredential | BasicCredential;
|
|
10
|
+
export type CredentialProvider<Value extends Credential = Credential> = (context: {
|
|
11
|
+
scopes: readonly string[];
|
|
12
|
+
signal: AbortSignal | undefined;
|
|
13
|
+
}) => Value | undefined | Promise<Value | undefined>;
|
|
14
|
+
export type SecurityRequirement = Readonly<Record<string, readonly string[]>>;
|
|
15
|
+
type SecuritySchemes = Readonly<Record<string, ClientSecurityScheme>>;
|
|
16
|
+
type Providers = Readonly<Record<string, CredentialProvider | undefined>>;
|
|
17
|
+
export declare class RequestAuthenticationError extends Error {
|
|
18
|
+
constructor(message: string);
|
|
19
|
+
}
|
|
20
|
+
export declare function applyAuthentication(url: URL, init: RequestInit & {
|
|
21
|
+
headers: Headers;
|
|
22
|
+
}, security: readonly SecurityRequirement[], schemes: SecuritySchemes, providers: Providers, options: ClientSendOptions | undefined, allowQueryCredentials: boolean): Promise<void>;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
export class RequestAuthenticationError extends Error {
|
|
2
|
+
constructor(message) {
|
|
3
|
+
super(message);
|
|
4
|
+
this.name = "RequestAuthenticationError";
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
function own(record, key) {
|
|
8
|
+
// eslint-disable-next-line security/detect-object-injection -- only own entries may name schemes and providers.
|
|
9
|
+
return Object.hasOwn(record, key) ? record[key] : undefined;
|
|
10
|
+
}
|
|
11
|
+
function applyQueryCredentials(url, remove, add = new URLSearchParams()) {
|
|
12
|
+
const current = url.search.slice(1).split("&").filter(Boolean);
|
|
13
|
+
const kept = current.filter((part) => [...new URLSearchParams(part).keys()].every((key) => !remove.has(key)));
|
|
14
|
+
if (kept.length !== current.length || add.size > 0) {
|
|
15
|
+
// Keep the encoding of unrelated OpenAPI parameters, including array separators.
|
|
16
|
+
url.search = [...kept, add.toString()].filter(Boolean).join("&");
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function clearCredentials(url, headers, schemes, allowQueryCredentials) {
|
|
20
|
+
headers.delete("authorization");
|
|
21
|
+
headers.delete("cookie");
|
|
22
|
+
const queryNames = new Set();
|
|
23
|
+
for (const scheme of Object.values(schemes)) {
|
|
24
|
+
if (scheme.type !== "apiKey")
|
|
25
|
+
continue;
|
|
26
|
+
if (scheme.location === "header")
|
|
27
|
+
headers.delete(scheme.name);
|
|
28
|
+
if (scheme.location === "query")
|
|
29
|
+
queryNames.add(scheme.name);
|
|
30
|
+
}
|
|
31
|
+
if (allowQueryCredentials && queryNames.size > 0)
|
|
32
|
+
applyQueryCredentials(url, queryNames);
|
|
33
|
+
}
|
|
34
|
+
// eslint-disable-next-line no-control-regex -- HTTP Basic forbids these control characters.
|
|
35
|
+
const basicControls = /[\x00-\x1F\x7F]/u;
|
|
36
|
+
function authorizationValue(scheme, value, name) {
|
|
37
|
+
if (scheme.type === "basic") {
|
|
38
|
+
if (typeof value !== "object" ||
|
|
39
|
+
value === null ||
|
|
40
|
+
!("username" in value) ||
|
|
41
|
+
typeof value.username !== "string" ||
|
|
42
|
+
typeof value.password !== "string" ||
|
|
43
|
+
value.username.includes(":") ||
|
|
44
|
+
basicControls.test(value.username) ||
|
|
45
|
+
basicControls.test(value.password)) {
|
|
46
|
+
throw new RequestAuthenticationError(`Invalid Basic credentials for security scheme "${name}"`);
|
|
47
|
+
}
|
|
48
|
+
const bytes = new TextEncoder().encode(`${value.username}:${value.password}`);
|
|
49
|
+
return `Basic ${btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""))}`;
|
|
50
|
+
}
|
|
51
|
+
if (typeof value !== "string") {
|
|
52
|
+
throw new RequestAuthenticationError(`Expected a credential string for security scheme "${name}"`);
|
|
53
|
+
}
|
|
54
|
+
return scheme.type === "bearer" ? `Bearer ${value}` : value;
|
|
55
|
+
}
|
|
56
|
+
async function resolveAlternative(requirement, schemes, providers, signal, credentials, allowQueryCredentials) {
|
|
57
|
+
const entries = [];
|
|
58
|
+
for (const [name, scopes] of Object.entries(requirement)) {
|
|
59
|
+
const scheme = own(schemes, name);
|
|
60
|
+
const provider = own(providers, name);
|
|
61
|
+
if (!scheme ||
|
|
62
|
+
!provider ||
|
|
63
|
+
(scheme.type === "apiKey" &&
|
|
64
|
+
((scheme.location === "cookie" && credentials === "omit") ||
|
|
65
|
+
(scheme.location === "query" && !allowQueryCredentials))))
|
|
66
|
+
return undefined;
|
|
67
|
+
entries.push({ name, scopes, scheme, provider });
|
|
68
|
+
}
|
|
69
|
+
const headers = new Map();
|
|
70
|
+
const query = new Map();
|
|
71
|
+
let cookieCredentials;
|
|
72
|
+
for (const { name, scopes, scheme, provider } of entries) {
|
|
73
|
+
signal?.throwIfAborted();
|
|
74
|
+
const value = await provider({ scopes, signal });
|
|
75
|
+
signal?.throwIfAborted();
|
|
76
|
+
if (value === undefined || value === "")
|
|
77
|
+
return undefined;
|
|
78
|
+
if (scheme.type === "apiKey" && scheme.location === "cookie") {
|
|
79
|
+
if (typeof value !== "object" ||
|
|
80
|
+
value === null ||
|
|
81
|
+
!("credentials" in value) ||
|
|
82
|
+
!["include", "same-origin"].includes(value.credentials)) {
|
|
83
|
+
throw new RequestAuthenticationError(`Invalid cookie credentials for security scheme "${name}"`);
|
|
84
|
+
}
|
|
85
|
+
if (cookieCredentials !== undefined &&
|
|
86
|
+
cookieCredentials !== value.credentials) {
|
|
87
|
+
throw new RequestAuthenticationError(`Conflicting cookie settings for security scheme "${name}"`);
|
|
88
|
+
}
|
|
89
|
+
cookieCredentials = value.credentials;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const target = scheme.type === "apiKey" && scheme.location === "query" ? query : headers;
|
|
93
|
+
const key = scheme.type !== "apiKey"
|
|
94
|
+
? "authorization"
|
|
95
|
+
: target === headers
|
|
96
|
+
? scheme.name.toLowerCase()
|
|
97
|
+
: scheme.name;
|
|
98
|
+
const credential = authorizationValue(scheme, value, name);
|
|
99
|
+
if (target.has(key) && target.get(key) !== credential) {
|
|
100
|
+
throw new RequestAuthenticationError(`Conflicting credentials for security scheme "${name}"`);
|
|
101
|
+
}
|
|
102
|
+
target.set(key, credential);
|
|
103
|
+
}
|
|
104
|
+
return { headers, query, cookieCredentials };
|
|
105
|
+
}
|
|
106
|
+
export async function applyAuthentication(url, init, security, schemes, providers, options, allowQueryCredentials) {
|
|
107
|
+
const anonymous = security.length === 0 ||
|
|
108
|
+
security.some((entry) => Object.keys(entry).length === 0);
|
|
109
|
+
if (options?.authenticate === false) {
|
|
110
|
+
if (!anonymous)
|
|
111
|
+
throw new RequestAuthenticationError("This operation requires authentication");
|
|
112
|
+
clearCredentials(url, init.headers, schemes, allowQueryCredentials);
|
|
113
|
+
init.credentials = "omit";
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
for (const requirement of security) {
|
|
117
|
+
if (Object.keys(requirement).length === 0)
|
|
118
|
+
continue;
|
|
119
|
+
const resolved = await resolveAlternative(requirement, schemes, providers, options?.signal ?? undefined, init.credentials, allowQueryCredentials);
|
|
120
|
+
if (!resolved)
|
|
121
|
+
continue;
|
|
122
|
+
for (const [key, value] of resolved.headers)
|
|
123
|
+
init.headers.set(key, value);
|
|
124
|
+
if (resolved.query.size > 0) {
|
|
125
|
+
applyQueryCredentials(url, new Set(resolved.query.keys()), new URLSearchParams([...resolved.query]));
|
|
126
|
+
}
|
|
127
|
+
init.credentials ??= resolved.cookieCredentials;
|
|
128
|
+
init.redirect ??= "error";
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (options?.authenticate === true || !anonymous) {
|
|
132
|
+
throw new RequestAuthenticationError("No credentials available for this operation");
|
|
133
|
+
}
|
|
134
|
+
if (security.length > 0) {
|
|
135
|
+
clearCredentials(url, init.headers, schemes, allowQueryCredentials);
|
|
136
|
+
init.credentials = "omit";
|
|
137
|
+
}
|
|
138
|
+
}
|
package/dist/fetch.d.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import type { ClientOperation, ClientOperations, ClientResult, ClientRouteFunction, ClientSecurityScheme, ClientSendOptions, ClientStreamResult, Streamable } from "@counterfact/types/client-route";
|
|
2
|
+
import { type CredentialProvider, type SecurityRequirement } from "./fetch-auth.js";
|
|
3
|
+
export { RequestAuthenticationError } from "./fetch-auth.js";
|
|
4
|
+
export type { BasicCredential, CookieCredential, CredentialProvider, } from "./fetch-auth.js";
|
|
5
|
+
export type { ClientOperations, ClientResult, ClientStreamResult, ClientRouteFunction, } from "@counterfact/types/client-route";
|
|
6
|
+
type ResponseValidators = Readonly<Record<string, (body: unknown) => boolean>>;
|
|
7
|
+
type Location = "path" | "query" | "headers" | "cookies";
|
|
8
|
+
type CollectionFormat = "csv" | "ssv" | "tsv" | "pipes" | "multi";
|
|
9
|
+
interface SwaggerFormField {
|
|
10
|
+
name: string;
|
|
11
|
+
required: boolean;
|
|
12
|
+
file: boolean;
|
|
13
|
+
collectionFormat?: CollectionFormat;
|
|
14
|
+
}
|
|
15
|
+
export interface FetchParameter {
|
|
16
|
+
name: string;
|
|
17
|
+
location: Location;
|
|
18
|
+
required: boolean;
|
|
19
|
+
style: string;
|
|
20
|
+
explode: boolean;
|
|
21
|
+
allowReserved?: boolean;
|
|
22
|
+
contentType?: string;
|
|
23
|
+
collectionFormat?: CollectionFormat;
|
|
24
|
+
}
|
|
25
|
+
type FormFieldEncoding = {
|
|
26
|
+
style?: string;
|
|
27
|
+
explode?: boolean;
|
|
28
|
+
allowReserved?: boolean;
|
|
29
|
+
contentType?: string;
|
|
30
|
+
};
|
|
31
|
+
interface WholeQuery {
|
|
32
|
+
required: boolean;
|
|
33
|
+
mediaType: string;
|
|
34
|
+
encoding?: Readonly<Record<string, FormFieldEncoding>>;
|
|
35
|
+
}
|
|
36
|
+
export interface FetchOperation {
|
|
37
|
+
parameters: readonly FetchParameter[];
|
|
38
|
+
querystring?: WholeQuery;
|
|
39
|
+
body?: {
|
|
40
|
+
required: boolean;
|
|
41
|
+
mediaType: string;
|
|
42
|
+
binary?: boolean;
|
|
43
|
+
formFields?: readonly SwaggerFormField[];
|
|
44
|
+
multipartContentTypes?: Readonly<Record<string, string>>;
|
|
45
|
+
};
|
|
46
|
+
responses: Readonly<Record<string, readonly string[]>>;
|
|
47
|
+
security?: readonly SecurityRequirement[];
|
|
48
|
+
responseSchemas?: Readonly<Record<string, Readonly<Record<string, string>>>>;
|
|
49
|
+
}
|
|
50
|
+
export type FetchOperations<Operations extends ClientOperations> = {
|
|
51
|
+
[Path in keyof Operations]: {
|
|
52
|
+
[Method in keyof Operations[Path]]: FetchOperation;
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
export interface FetchClientOptions<Auth extends Readonly<Record<string, CredentialProvider | undefined>> = Readonly<Record<string, CredentialProvider | undefined>>> {
|
|
56
|
+
auth?: Auth;
|
|
57
|
+
baseUrl: string | URL;
|
|
58
|
+
fetch?: typeof fetch;
|
|
59
|
+
headers?: ConstructorParameters<typeof Headers>[0];
|
|
60
|
+
credentials?: RequestInit["credentials"];
|
|
61
|
+
}
|
|
62
|
+
export type FetchClientOptionsWithDefault<Auth extends Readonly<Record<string, CredentialProvider | undefined>>> = Omit<FetchClientOptions<Auth>, "baseUrl"> & {
|
|
63
|
+
baseUrl?: FetchClientOptions["baseUrl"];
|
|
64
|
+
};
|
|
65
|
+
/** Select a generated version while retaining that version's client type. */
|
|
66
|
+
export declare function versionedFetchClient<Clients extends object>(factories: {
|
|
67
|
+
[Version in keyof Clients]: () => Clients[Version];
|
|
68
|
+
}): {
|
|
69
|
+
version<Version extends keyof Clients>(version: Version): Clients[Version];
|
|
70
|
+
};
|
|
71
|
+
/** Apply the configured version prefix unless the caller supplies a full URL. */
|
|
72
|
+
export declare function fetchOptionsForVersion<Auth extends Readonly<Record<string, CredentialProvider | undefined>>>(options: Omit<FetchClientOptions, "auth">, prefix: string, overrides?: Partial<FetchClientOptions<Auth>>): FetchClientOptions<Auth>;
|
|
73
|
+
export declare function serializeWholeQuery({ mediaType, encoding }: WholeQuery, value: unknown): string;
|
|
74
|
+
type InvalidResponseReason = "undocumented-status" | "unexpected-media-type" | "unexpected-body" | "missing-body" | "malformed-json" | "schema-mismatch";
|
|
75
|
+
/** A Fetch response whose status, media type, or body did not match the contract. */
|
|
76
|
+
export declare class InvalidResponseError extends Error {
|
|
77
|
+
readonly reason: InvalidResponseReason;
|
|
78
|
+
readonly response: Response;
|
|
79
|
+
readonly matchedStatus: string | undefined;
|
|
80
|
+
readonly body: unknown;
|
|
81
|
+
readonly status: number;
|
|
82
|
+
readonly mediaType: string | undefined;
|
|
83
|
+
constructor(reason: InvalidResponseReason, response: Response, matchedStatus: string | undefined, body?: unknown);
|
|
84
|
+
}
|
|
85
|
+
type FetchRouteDefinition<Operations extends ClientOperations> = {
|
|
86
|
+
operations: FetchOperations<Operations>;
|
|
87
|
+
validators: ResponseValidators;
|
|
88
|
+
securitySchemes: Readonly<Record<string, ClientSecurityScheme>>;
|
|
89
|
+
contracts?: Operations;
|
|
90
|
+
};
|
|
91
|
+
type FetchRouteSource = {
|
|
92
|
+
prefix: string;
|
|
93
|
+
definition: FetchRouteDefinition<ClientOperations>;
|
|
94
|
+
options: FetchClientOptions;
|
|
95
|
+
};
|
|
96
|
+
type WithoutTrailingSlash<Path extends string> = Path extends `${infer Rest}/` ? WithoutTrailingSlash<Rest> : Path;
|
|
97
|
+
type MountedPath<Prefix extends string, Path extends string> = Path extends "/" ? Prefix extends "" ? "/" : Prefix | `${Prefix}/` : `${Prefix}${Path}`;
|
|
98
|
+
type PrefixedOperations<Source extends FetchRouteSource> = {
|
|
99
|
+
[Path in keyof NonNullable<Source["definition"]["contracts"]> & string as MountedPath<WithoutTrailingSlash<Source["prefix"]>, Path>]: NonNullable<Source["definition"]["contracts"]>[Path];
|
|
100
|
+
};
|
|
101
|
+
type PrefixedPaths<Source extends FetchRouteSource> = Source extends unknown ? keyof PrefixedOperations<Source> : never;
|
|
102
|
+
type PrefixedMethods<Source extends FetchRouteSource, Path> = Path extends keyof PrefixedOperations<Source> ? PrefixedOperations<Source>[Path] : Record<never, never>;
|
|
103
|
+
type PrefixedMethodNames<Source extends FetchRouteSource, Path> = Source extends unknown ? keyof PrefixedMethods<Source, Path> : never;
|
|
104
|
+
type FirstPrefixedOperation<Sources extends readonly FetchRouteSource[], Path, Method> = Sources extends readonly [
|
|
105
|
+
infer First extends FetchRouteSource,
|
|
106
|
+
...infer Tail extends readonly FetchRouteSource[]
|
|
107
|
+
] ? Method extends keyof PrefixedMethods<First, Path> ? PrefixedMethods<First, Path>[Method] : FirstPrefixedOperation<Tail, Path, Method> : never;
|
|
108
|
+
type PrefixedContracts<Sources extends readonly FetchRouteSource[]> = {
|
|
109
|
+
[Path in PrefixedPaths<Sources[number]>]: {
|
|
110
|
+
[Method in PrefixedMethodNames<Sources[number], Path>]: FirstPrefixedOperation<Sources, Path, Method>;
|
|
111
|
+
};
|
|
112
|
+
};
|
|
113
|
+
/** Creates a browser-compatible route function from generated operation metadata. */
|
|
114
|
+
export declare function createFetchRoute<Operations extends ClientOperations>(operations: FetchOperations<Operations>, options: FetchClientOptions, validators?: ResponseValidators, securitySchemes?: Readonly<Record<string, ClientSecurityScheme>>): ClientRouteFunction<Operations>;
|
|
115
|
+
/** Creates a route function for specs mounted at their configured URL prefixes. */
|
|
116
|
+
export declare function createPrefixedFetchRoute<const Sources extends readonly FetchRouteSource[]>(sources: Sources): ClientRouteFunction<PrefixedContracts<Sources>>;
|
|
117
|
+
export interface NamedOperation {
|
|
118
|
+
readonly path: string;
|
|
119
|
+
readonly method: string;
|
|
120
|
+
readonly pathParameters: readonly string[];
|
|
121
|
+
}
|
|
122
|
+
export type NamedOperations = Readonly<Record<string, Readonly<Record<string, NamedOperation>>>>;
|
|
123
|
+
type EmptyFields = Record<never, never>;
|
|
124
|
+
type RequiredKeys<Fields> = {
|
|
125
|
+
[Key in keyof Fields]-?: EmptyFields extends Pick<Fields, Key> ? never : Key;
|
|
126
|
+
}[keyof Fields];
|
|
127
|
+
type NamedField<Name extends string, Value> = [keyof Value] extends [never] ? object : [RequiredKeys<Value>] extends [never] ? {
|
|
128
|
+
[Key in Name]?: Value;
|
|
129
|
+
} : {
|
|
130
|
+
[Key in Name]: Value;
|
|
131
|
+
};
|
|
132
|
+
type NamedRequest<Operation extends ClientOperation> = ClientSendOptions & (Operation["querystring"] extends {
|
|
133
|
+
value: infer Value;
|
|
134
|
+
required: infer Required;
|
|
135
|
+
} ? Required extends true ? {
|
|
136
|
+
query: Value;
|
|
137
|
+
} : {
|
|
138
|
+
query?: Value;
|
|
139
|
+
} : NamedField<"query", Operation["query"]>) & NamedField<"headers", Operation["headers"]> & NamedField<"cookies", Operation["cookies"]> & (Operation["bodyRequired"] extends true ? {
|
|
140
|
+
body: Operation["body"];
|
|
141
|
+
} : [Operation["body"]] extends [never] ? object : {
|
|
142
|
+
body?: Operation["body"];
|
|
143
|
+
});
|
|
144
|
+
type NamedArguments<Operation extends ClientOperation, Parameters extends readonly string[], Options = NamedRequest<Operation>> = [
|
|
145
|
+
...{
|
|
146
|
+
[Index in keyof Parameters]: Operation["path"][Parameters[Index] & keyof Operation["path"]];
|
|
147
|
+
},
|
|
148
|
+
...(EmptyFields extends Options ? [options?: Options] : [options: Options])
|
|
149
|
+
];
|
|
150
|
+
type NamedMethod<Operations extends ClientOperations, Entry extends NamedOperation> = Entry["path"] extends keyof Operations ? Entry["method"] extends keyof Operations[Entry["path"]] ? NamedCall<Operations[Entry["path"]][Entry["method"]], Entry["pathParameters"]> : never : never;
|
|
151
|
+
type NamedCall<Operation extends ClientOperation, Parameters extends readonly string[]> = ((...args: NamedArguments<Operation, Parameters>) => Promise<ClientResult<Operation>>) & ([Streamable<ClientResult<Operation>>] extends [never] ? object : {
|
|
152
|
+
stream(...args: NamedArguments<Operation, Parameters>): Promise<ClientStreamResult<Operation>>;
|
|
153
|
+
});
|
|
154
|
+
type NamedSdk<Operations extends ClientOperations, Names extends NamedOperations> = {
|
|
155
|
+
[Group in keyof Names]: {
|
|
156
|
+
[Name in keyof Names[Group]]: NamedMethod<Operations, Names[Group][Name]>;
|
|
157
|
+
};
|
|
158
|
+
};
|
|
159
|
+
/** Creates grouped, named methods that use the same contract as the fluent client. */
|
|
160
|
+
export declare function createFetchSdk<Operations extends ClientOperations, Names extends NamedOperations>(operations: FetchOperations<Operations>, names: Names, options: FetchClientOptions, validators?: ResponseValidators, securitySchemes?: Readonly<Record<string, ClientSecurityScheme>>): NamedSdk<Operations, Names>;
|
|
161
|
+
/** Binds the generated contract and naming metadata to its public SDK factory. */
|
|
162
|
+
export declare function defineFetchSdk<Operations extends ClientOperations, Names extends NamedOperations, Auth extends Readonly<Record<string, CredentialProvider | undefined>>, Default extends string | undefined = undefined>(definition: {
|
|
163
|
+
readonly operations: FetchOperations<Operations>;
|
|
164
|
+
readonly nativeBaseUrl?: Default;
|
|
165
|
+
}, names: Names, validators: ResponseValidators, securitySchemes?: Readonly<Record<string, ClientSecurityScheme>>): ((...[options]: Default extends string ? [options?: FetchClientOptionsWithDefault<Auth> | undefined] : [options: FetchClientOptions<Auth>]) => NamedSdk<Operations, Names>) & {
|
|
166
|
+
routeDefinition: FetchRouteDefinition<Operations>;
|
|
167
|
+
};
|
package/dist/fetch.js
ADDED
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
import { applyAuthentication, } from "./fetch-auth.js";
|
|
2
|
+
import { encodeMultipartBody } from "./multipart-form.js";
|
|
3
|
+
import { isJsonMediaType as isJson, matchMediaType, mediaTypeOf, } from "./media-type.js";
|
|
4
|
+
export { RequestAuthenticationError } from "./fetch-auth.js";
|
|
5
|
+
/** Select a generated version while retaining that version's client type. */
|
|
6
|
+
export function versionedFetchClient(factories) {
|
|
7
|
+
return {
|
|
8
|
+
version(version) {
|
|
9
|
+
if (!Object.hasOwn(factories, version)) {
|
|
10
|
+
throw new TypeError(`Unknown API version: ${String(version)}`);
|
|
11
|
+
}
|
|
12
|
+
// eslint-disable-next-line security/detect-object-injection -- the version was checked against the generated factory's own keys.
|
|
13
|
+
return factories[version]();
|
|
14
|
+
},
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function trimTrailingSlashes(path) {
|
|
18
|
+
let end = path.length;
|
|
19
|
+
while (path.charAt(end - 1) === "/")
|
|
20
|
+
end--;
|
|
21
|
+
return path.slice(0, end);
|
|
22
|
+
}
|
|
23
|
+
/** Apply the configured version prefix unless the caller supplies a full URL. */
|
|
24
|
+
export function fetchOptionsForVersion(options, prefix, overrides) {
|
|
25
|
+
const baseUrl = new URL(overrides?.baseUrl ?? options.baseUrl);
|
|
26
|
+
if (overrides?.baseUrl === undefined && prefix !== "") {
|
|
27
|
+
baseUrl.pathname =
|
|
28
|
+
trimTrailingSlashes(baseUrl.pathname) + trimTrailingSlashes(prefix);
|
|
29
|
+
}
|
|
30
|
+
return { ...options, ...overrides, baseUrl };
|
|
31
|
+
}
|
|
32
|
+
const empty = {
|
|
33
|
+
path: {},
|
|
34
|
+
query: {},
|
|
35
|
+
headers: {},
|
|
36
|
+
cookies: {},
|
|
37
|
+
body: undefined,
|
|
38
|
+
querystring: undefined,
|
|
39
|
+
};
|
|
40
|
+
function scalar(value) {
|
|
41
|
+
if (value === null)
|
|
42
|
+
return "";
|
|
43
|
+
if (typeof value === "string" ||
|
|
44
|
+
typeof value === "number" ||
|
|
45
|
+
typeof value === "boolean") {
|
|
46
|
+
return String(value);
|
|
47
|
+
}
|
|
48
|
+
throw new TypeError("Expected a primitive OpenAPI parameter value");
|
|
49
|
+
}
|
|
50
|
+
function encode(value) {
|
|
51
|
+
return encodeURIComponent(value).replace(/[!'()*]/gu, (character) => "%" + character.charCodeAt(0).toString(16).toUpperCase());
|
|
52
|
+
}
|
|
53
|
+
function encodeQueryValue(value, allowReserved) {
|
|
54
|
+
// Preserve reserved characters that cannot split the query or start a fragment.
|
|
55
|
+
return allowReserved
|
|
56
|
+
? encode(value).replace(/%(?:3A|2F|3F|5B|5D|40|21|24|27|28|29|2A|2C|3B)/gu, (token) => decodeURIComponent(token))
|
|
57
|
+
: encode(value);
|
|
58
|
+
}
|
|
59
|
+
function pairs(value) {
|
|
60
|
+
return value !== null && typeof value === "object" && !Array.isArray(value)
|
|
61
|
+
? Object.entries(value)
|
|
62
|
+
: undefined;
|
|
63
|
+
}
|
|
64
|
+
function formEncode(value) {
|
|
65
|
+
return new URLSearchParams([["", value]]).toString().slice(1);
|
|
66
|
+
}
|
|
67
|
+
const delimiters = { csv: ",", ssv: " ", tsv: "\t", pipes: "|" };
|
|
68
|
+
function collectionItems(values, format, stringify, encodeDelimiter = (delimiter) => delimiter) {
|
|
69
|
+
const items = values.map(stringify);
|
|
70
|
+
if (format === "multi")
|
|
71
|
+
return items;
|
|
72
|
+
// eslint-disable-next-line security/detect-object-injection -- the key is a declared Swagger collection format.
|
|
73
|
+
const delimiter = delimiters[format];
|
|
74
|
+
return [items.join(encodeDelimiter(delimiter))];
|
|
75
|
+
}
|
|
76
|
+
function serialize(parameter, value, encodeField = encode, encodeParameterValue) {
|
|
77
|
+
const { name, location, style, explode } = parameter;
|
|
78
|
+
const encodeValue = location === "headers"
|
|
79
|
+
? (text) => text
|
|
80
|
+
: (encodeParameterValue ??
|
|
81
|
+
((text) => encodeQueryValue(text, location === "query" && parameter.allowReserved)));
|
|
82
|
+
const key = location === "headers" ? name : encodeField(name);
|
|
83
|
+
const stringify = (item) => encodeValue(scalar(item));
|
|
84
|
+
if (parameter.contentType !== undefined) {
|
|
85
|
+
if (!isJson(parameter.contentType)) {
|
|
86
|
+
throw new TypeError(`Unsupported parameter content type: ${parameter.contentType}`);
|
|
87
|
+
}
|
|
88
|
+
return [[key, encodeValue(JSON.stringify(value))]];
|
|
89
|
+
}
|
|
90
|
+
if (parameter.collectionFormat && Array.isArray(value)) {
|
|
91
|
+
return collectionItems(value, parameter.collectionFormat, stringify, (delimiter) => /\s/u.test(delimiter) && location !== "headers"
|
|
92
|
+
? encodeValue(delimiter)
|
|
93
|
+
: delimiter).map((item) => [key, item]);
|
|
94
|
+
}
|
|
95
|
+
const fields = pairs(value);
|
|
96
|
+
const items = Array.isArray(value) ? value : undefined;
|
|
97
|
+
const positional = fields ? fields.flat() : items;
|
|
98
|
+
const joined = positional?.map(stringify).join(",") ?? stringify(value);
|
|
99
|
+
const named = fields?.map(([field, item]) => [
|
|
100
|
+
encodeValue(field),
|
|
101
|
+
stringify(item),
|
|
102
|
+
]);
|
|
103
|
+
const assignments = named?.map(([field, item]) => `${field}=${item}`);
|
|
104
|
+
const repeated = items?.map((item) => [key, stringify(item)]);
|
|
105
|
+
switch (style) {
|
|
106
|
+
case "simple":
|
|
107
|
+
return [[key, explode && assignments ? assignments.join(",") : joined]];
|
|
108
|
+
case "form":
|
|
109
|
+
return explode ? (named ?? repeated ?? [[key, joined]]) : [[key, joined]];
|
|
110
|
+
case "label":
|
|
111
|
+
return [
|
|
112
|
+
[
|
|
113
|
+
key,
|
|
114
|
+
"." +
|
|
115
|
+
(explode
|
|
116
|
+
? (assignments?.join(".") ??
|
|
117
|
+
items?.map(stringify).join(".") ??
|
|
118
|
+
joined)
|
|
119
|
+
: joined),
|
|
120
|
+
],
|
|
121
|
+
];
|
|
122
|
+
case "matrix": {
|
|
123
|
+
const expanded = assignments ?? items?.map((item) => `${key}=${stringify(item)}`);
|
|
124
|
+
return [
|
|
125
|
+
[
|
|
126
|
+
key,
|
|
127
|
+
";" + (explode && expanded ? expanded.join(";") : `${key}=${joined}`),
|
|
128
|
+
],
|
|
129
|
+
];
|
|
130
|
+
}
|
|
131
|
+
case "deepObject":
|
|
132
|
+
if (fields)
|
|
133
|
+
return fields.map(([field, item]) => [
|
|
134
|
+
`${key}[${encodeField(field)}]`,
|
|
135
|
+
stringify(item),
|
|
136
|
+
]);
|
|
137
|
+
break;
|
|
138
|
+
case "spaceDelimited":
|
|
139
|
+
case "pipeDelimited":
|
|
140
|
+
if (positional && !explode) {
|
|
141
|
+
return [
|
|
142
|
+
[
|
|
143
|
+
key,
|
|
144
|
+
positional
|
|
145
|
+
.map(stringify)
|
|
146
|
+
.join(style === "spaceDelimited" ? "%20" : "|"),
|
|
147
|
+
],
|
|
148
|
+
];
|
|
149
|
+
}
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
throw new TypeError(`Unsupported OpenAPI serialization for ${location} parameter "${name}": ${style}`);
|
|
153
|
+
}
|
|
154
|
+
const formMediaType = "application/x-www-form-urlencoded";
|
|
155
|
+
function queryJson(value) {
|
|
156
|
+
const json = JSON.stringify(value);
|
|
157
|
+
if (json === undefined)
|
|
158
|
+
throw new TypeError("Expected a JSON query value");
|
|
159
|
+
return json;
|
|
160
|
+
}
|
|
161
|
+
export function serializeWholeQuery({ mediaType, encoding }, value) {
|
|
162
|
+
if (isJson(mediaType))
|
|
163
|
+
return encode(queryJson(value));
|
|
164
|
+
const fields = pairs(value);
|
|
165
|
+
if (mediaType !== formMediaType || fields === undefined) {
|
|
166
|
+
throw new TypeError(`Unsupported whole-query value for ${mediaType}`);
|
|
167
|
+
}
|
|
168
|
+
const parts = [];
|
|
169
|
+
for (const [name, field] of fields) {
|
|
170
|
+
if (field === undefined)
|
|
171
|
+
continue;
|
|
172
|
+
const rules = encoding && inputValue(encoding, name);
|
|
173
|
+
if (rules?.style !== undefined ||
|
|
174
|
+
rules?.explode !== undefined ||
|
|
175
|
+
rules?.allowReserved !== undefined) {
|
|
176
|
+
const style = rules.style ?? "form";
|
|
177
|
+
parts.push(...serialize({
|
|
178
|
+
name,
|
|
179
|
+
location: "query",
|
|
180
|
+
required: false,
|
|
181
|
+
style,
|
|
182
|
+
explode: rules.explode ?? style === "form",
|
|
183
|
+
}, field, formEncode, rules.allowReserved
|
|
184
|
+
? (text) => encodeQueryValue(text, true).replaceAll("%20", "+")
|
|
185
|
+
: formEncode));
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
const key = formEncode(name);
|
|
189
|
+
const items = Array.isArray(field) ? field : [field];
|
|
190
|
+
const contentType = rules?.contentType?.toLowerCase();
|
|
191
|
+
for (const item of items) {
|
|
192
|
+
const json = contentType === undefined
|
|
193
|
+
? item !== null && typeof item === "object"
|
|
194
|
+
: isJson(contentType);
|
|
195
|
+
parts.push([key, formEncode(json ? queryJson(item) : scalar(item))]);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return parts.map(([key, field]) => `${key}=${field}`).join("&");
|
|
199
|
+
}
|
|
200
|
+
function isStreamable(mediaType) {
|
|
201
|
+
return !isJson(mediaType) && !mediaType.startsWith("text/");
|
|
202
|
+
}
|
|
203
|
+
function canStream(operation) {
|
|
204
|
+
return Object.values(operation.responses).some((media) => media.some(isStreamable));
|
|
205
|
+
}
|
|
206
|
+
function encodeSwaggerForm(mediaType, fields, value) {
|
|
207
|
+
const form = mediaType === formMediaType ? new URLSearchParams() : new FormData();
|
|
208
|
+
if ((form instanceof FormData && value instanceof FormData) ||
|
|
209
|
+
(form instanceof URLSearchParams && value instanceof URLSearchParams)) {
|
|
210
|
+
for (const field of fields) {
|
|
211
|
+
if (field.required && !value.has(field.name)) {
|
|
212
|
+
throw new TypeError(`Missing required Swagger form field "${field.name}"`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return value;
|
|
216
|
+
}
|
|
217
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
218
|
+
throw new TypeError("Expected a Swagger form body");
|
|
219
|
+
}
|
|
220
|
+
for (const { name, required, file, collectionFormat } of fields) {
|
|
221
|
+
const input = inputValue(value, name);
|
|
222
|
+
if (input === undefined) {
|
|
223
|
+
if (required)
|
|
224
|
+
throw new TypeError(`Missing required Swagger form field "${name}"`);
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
if (file) {
|
|
228
|
+
if (!(form instanceof FormData) || !(input instanceof Blob)) {
|
|
229
|
+
throw new TypeError(`Expected a file for Swagger form field "${name}"`);
|
|
230
|
+
}
|
|
231
|
+
form.append(name, input);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
const items = collectionFormat && Array.isArray(input)
|
|
235
|
+
? collectionItems(input, collectionFormat, scalar)
|
|
236
|
+
: [scalar(input)];
|
|
237
|
+
for (const item of items)
|
|
238
|
+
form.append(name, item);
|
|
239
|
+
}
|
|
240
|
+
return form;
|
|
241
|
+
}
|
|
242
|
+
function encodeBody(mediaType, value, multipartContentTypes, binary) {
|
|
243
|
+
if (isJson(mediaType)) {
|
|
244
|
+
const json = JSON.stringify(value);
|
|
245
|
+
if (json !== undefined)
|
|
246
|
+
return json;
|
|
247
|
+
}
|
|
248
|
+
if (mediaType.startsWith("text/") && typeof value === "string")
|
|
249
|
+
return value;
|
|
250
|
+
if ((binary || mediaTypeOf(mediaType) === "application/octet-stream") &&
|
|
251
|
+
(value instanceof Blob || value instanceof ArrayBuffer)) {
|
|
252
|
+
return value;
|
|
253
|
+
}
|
|
254
|
+
if (mediaType === "multipart/form-data") {
|
|
255
|
+
if (value instanceof FormData)
|
|
256
|
+
return value;
|
|
257
|
+
const fields = pairs(value);
|
|
258
|
+
if (fields)
|
|
259
|
+
return encodeMultipartBody(fields, multipartContentTypes);
|
|
260
|
+
}
|
|
261
|
+
if (mediaType === "application/x-www-form-urlencoded" &&
|
|
262
|
+
value instanceof URLSearchParams)
|
|
263
|
+
return value;
|
|
264
|
+
throw new TypeError(`Unsupported request body for ${mediaType}`);
|
|
265
|
+
}
|
|
266
|
+
/** A Fetch response whose status, media type, or body did not match the contract. */
|
|
267
|
+
export class InvalidResponseError extends Error {
|
|
268
|
+
reason;
|
|
269
|
+
response;
|
|
270
|
+
matchedStatus;
|
|
271
|
+
body;
|
|
272
|
+
status;
|
|
273
|
+
mediaType;
|
|
274
|
+
constructor(reason, response, matchedStatus, body = undefined) {
|
|
275
|
+
super(`Invalid HTTP response ${response.status}: ${reason.replaceAll("-", " ")}`);
|
|
276
|
+
this.reason = reason;
|
|
277
|
+
this.response = response;
|
|
278
|
+
this.matchedStatus = matchedStatus;
|
|
279
|
+
this.body = body;
|
|
280
|
+
this.name = "InvalidResponseError";
|
|
281
|
+
this.status = response.status;
|
|
282
|
+
this.mediaType = mediaTypeOf(response.headers.get("content-type"));
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
async function readResponse(response, method, operation, validators, stream) {
|
|
286
|
+
const { status } = response;
|
|
287
|
+
const match = [
|
|
288
|
+
String(status),
|
|
289
|
+
`${Math.floor(status / 100)}XX`,
|
|
290
|
+
"default",
|
|
291
|
+
].find((candidate) => Object.hasOwn(operation.responses, candidate));
|
|
292
|
+
if (match === undefined) {
|
|
293
|
+
throw new InvalidResponseError("undocumented-status", response, undefined);
|
|
294
|
+
}
|
|
295
|
+
// eslint-disable-next-line security/detect-object-injection -- match is an own response key selected above.
|
|
296
|
+
const declared = operation.responses[match];
|
|
297
|
+
const responseBody = response.body;
|
|
298
|
+
const emptyBody = method === "head" ||
|
|
299
|
+
[204, 205, 304].includes(status) ||
|
|
300
|
+
responseBody === null;
|
|
301
|
+
if (declared.length === 0) {
|
|
302
|
+
const bytes = emptyBody ? undefined : await response.clone().arrayBuffer();
|
|
303
|
+
if (bytes?.byteLength) {
|
|
304
|
+
throw new InvalidResponseError("unexpected-body", response, match, bytes);
|
|
305
|
+
}
|
|
306
|
+
return {
|
|
307
|
+
matchedStatus: match,
|
|
308
|
+
status,
|
|
309
|
+
mediaType: undefined,
|
|
310
|
+
body: undefined,
|
|
311
|
+
response,
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
if (emptyBody) {
|
|
315
|
+
throw new InvalidResponseError("missing-body", response, match);
|
|
316
|
+
}
|
|
317
|
+
const mediaType = matchMediaType(declared, response.headers.get("content-type"));
|
|
318
|
+
if (mediaType === undefined) {
|
|
319
|
+
throw new InvalidResponseError("unexpected-media-type", response, match);
|
|
320
|
+
}
|
|
321
|
+
if (stream && isStreamable(mediaType)) {
|
|
322
|
+
return {
|
|
323
|
+
matchedStatus: match,
|
|
324
|
+
status,
|
|
325
|
+
mediaType,
|
|
326
|
+
body: responseBody,
|
|
327
|
+
response,
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
const content = response.clone();
|
|
331
|
+
let body;
|
|
332
|
+
if (isJson(mediaType)) {
|
|
333
|
+
const text = await content.text();
|
|
334
|
+
try {
|
|
335
|
+
body = JSON.parse(text);
|
|
336
|
+
}
|
|
337
|
+
catch {
|
|
338
|
+
throw new InvalidResponseError("malformed-json", response, match, text);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
else if (mediaType.startsWith("text/")) {
|
|
342
|
+
body = await content.text();
|
|
343
|
+
}
|
|
344
|
+
else {
|
|
345
|
+
body = await content.arrayBuffer();
|
|
346
|
+
}
|
|
347
|
+
// eslint-disable-next-line security/detect-object-injection -- the status and media type were matched against declared values above.
|
|
348
|
+
const schema = operation.responseSchemas?.[match]?.[mediaType];
|
|
349
|
+
if (schema !== undefined) {
|
|
350
|
+
const validate = Object.hasOwn(validators, schema)
|
|
351
|
+
? // eslint-disable-next-line security/detect-object-injection -- validator names come from the generated operation metadata.
|
|
352
|
+
validators[schema]
|
|
353
|
+
: undefined;
|
|
354
|
+
if (validate?.(body) !== true) {
|
|
355
|
+
throw new InvalidResponseError("schema-mismatch", response, match, body);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return { matchedStatus: match, status, mediaType, body, response };
|
|
359
|
+
}
|
|
360
|
+
function inputValue(values, name) {
|
|
361
|
+
// eslint-disable-next-line security/detect-object-injection -- names come from OpenAPI and only own properties count as supplied inputs.
|
|
362
|
+
return Object.hasOwn(values, name) ? values[name] : undefined;
|
|
363
|
+
}
|
|
364
|
+
function isReady(operation, inputs) {
|
|
365
|
+
return ((!operation.body?.required || inputs.body !== undefined) &&
|
|
366
|
+
(!operation.querystring?.required || inputs.querystring !== undefined) &&
|
|
367
|
+
operation.parameters.every(({ location, name, required }) =>
|
|
368
|
+
// eslint-disable-next-line security/detect-object-injection -- location is a typed parameter location and only selects a request input map.
|
|
369
|
+
!required || inputValue(inputs[location], name) !== undefined));
|
|
370
|
+
}
|
|
371
|
+
function buildRequest(options, routePath, method, operation, inputs, sendOptions) {
|
|
372
|
+
const headers = new Headers(options.headers);
|
|
373
|
+
const query = [];
|
|
374
|
+
const cookies = [];
|
|
375
|
+
let path = routePath;
|
|
376
|
+
for (const parameter of operation.parameters) {
|
|
377
|
+
const value = inputValue(inputs[parameter.location], parameter.name);
|
|
378
|
+
if (value === undefined)
|
|
379
|
+
continue;
|
|
380
|
+
for (const [key, serialized] of serialize(parameter, value)) {
|
|
381
|
+
switch (parameter.location) {
|
|
382
|
+
case "path":
|
|
383
|
+
path = path.replaceAll(`{${parameter.name}}`, () => serialized);
|
|
384
|
+
break;
|
|
385
|
+
case "query":
|
|
386
|
+
query.push(`${key}=${serialized}`);
|
|
387
|
+
break;
|
|
388
|
+
case "headers":
|
|
389
|
+
headers.set(key, serialized);
|
|
390
|
+
break;
|
|
391
|
+
case "cookies":
|
|
392
|
+
cookies.push(`${key}=${serialized}`);
|
|
393
|
+
break;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
if (cookies.length > 0) {
|
|
398
|
+
headers.set("cookie", [headers.get("cookie"), ...cookies].filter(Boolean).join("; "));
|
|
399
|
+
}
|
|
400
|
+
if (/[{}]/u.test(path) ||
|
|
401
|
+
path.split("/").some((part) => /^(?:\.|%2e){1,2}$/iu.test(part))) {
|
|
402
|
+
throw new TypeError(`Cannot send an unresolved or dot-segment path: ${path}`);
|
|
403
|
+
}
|
|
404
|
+
const url = new URL(options.baseUrl);
|
|
405
|
+
url.pathname = url.pathname.replace(/\/$/u, "") + path;
|
|
406
|
+
if (operation.querystring) {
|
|
407
|
+
url.search =
|
|
408
|
+
inputs.querystring === undefined
|
|
409
|
+
? ""
|
|
410
|
+
: serializeWholeQuery(operation.querystring, inputs.querystring);
|
|
411
|
+
}
|
|
412
|
+
else if (query.length > 0) {
|
|
413
|
+
url.search = [url.search.slice(1), ...query].filter(Boolean).join("&");
|
|
414
|
+
}
|
|
415
|
+
let body;
|
|
416
|
+
if (inputs.body !== undefined && operation.body) {
|
|
417
|
+
const { mediaType, formFields, multipartContentTypes, binary } = operation.body;
|
|
418
|
+
body = formFields
|
|
419
|
+
? encodeSwaggerForm(mediaType, formFields, inputs.body)
|
|
420
|
+
: encodeBody(mediaType, inputs.body, multipartContentTypes, binary);
|
|
421
|
+
if (mediaType === "multipart/form-data")
|
|
422
|
+
headers.delete("content-type");
|
|
423
|
+
else
|
|
424
|
+
headers.set("content-type", mediaType);
|
|
425
|
+
}
|
|
426
|
+
return [
|
|
427
|
+
url,
|
|
428
|
+
{
|
|
429
|
+
method: method.toUpperCase(),
|
|
430
|
+
headers,
|
|
431
|
+
body,
|
|
432
|
+
signal: sendOptions?.signal,
|
|
433
|
+
credentials: sendOptions?.credentials ?? options.credentials,
|
|
434
|
+
redirect: sendOptions?.redirect,
|
|
435
|
+
},
|
|
436
|
+
];
|
|
437
|
+
}
|
|
438
|
+
function createSendRequest(options, validators, securitySchemes) {
|
|
439
|
+
const fetchRequest = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
440
|
+
return async function sendRequest(path, method, operation, inputs, sendOptions, stream = false) {
|
|
441
|
+
const [url, init] = buildRequest(options, path, method, operation, inputs, sendOptions);
|
|
442
|
+
if (operation.security || sendOptions?.authenticate !== undefined) {
|
|
443
|
+
await applyAuthentication(url, init, operation.security ?? [], securitySchemes, options.auth ?? {}, sendOptions, !operation.querystring ||
|
|
444
|
+
operation.querystring.mediaType === formMediaType);
|
|
445
|
+
}
|
|
446
|
+
return readResponse(await fetchRequest(url, init), method, operation, validators, stream);
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
function createRouteFromSources(sources) {
|
|
450
|
+
const routes = new Map();
|
|
451
|
+
for (const { prefix, options, definition } of sources) {
|
|
452
|
+
const mount = trimTrailingSlashes(prefix);
|
|
453
|
+
const sendRequest = createSendRequest(options, definition.validators, definition.securitySchemes);
|
|
454
|
+
for (const [path, methods] of Object.entries(definition.operations)) {
|
|
455
|
+
const mounted = mount + path;
|
|
456
|
+
const paths = mount && path === "/" ? [mount, mounted] : [mounted];
|
|
457
|
+
for (const fullPath of paths) {
|
|
458
|
+
const existing = routes.get(fullPath) ?? new Map();
|
|
459
|
+
// A shared URL uses the first spec that defines its method.
|
|
460
|
+
for (const [method, operation] of Object.entries(methods)) {
|
|
461
|
+
if (!existing.has(method))
|
|
462
|
+
existing.set(method, { operation, sendRequest });
|
|
463
|
+
}
|
|
464
|
+
routes.set(fullPath, existing);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
const prefixes = new Set(["/"]);
|
|
469
|
+
for (const path of routes.keys()) {
|
|
470
|
+
const segments = path.split("/");
|
|
471
|
+
for (let i = 2; i <= segments.length; i++)
|
|
472
|
+
prefixes.add(segments.slice(0, i).join("/"));
|
|
473
|
+
}
|
|
474
|
+
function request(path, method, bound, inputs) {
|
|
475
|
+
const { operation, sendRequest } = bound;
|
|
476
|
+
const next = (location, values) => request(path, method, bound, {
|
|
477
|
+
...inputs,
|
|
478
|
+
// eslint-disable-next-line security/detect-object-injection -- location comes from the fixed setters below.
|
|
479
|
+
[location]: { ...inputs[location], ...values },
|
|
480
|
+
});
|
|
481
|
+
return {
|
|
482
|
+
path: (values) => next("path", values),
|
|
483
|
+
query: operation.querystring
|
|
484
|
+
? (querystring) => request(path, method, bound, { ...inputs, querystring })
|
|
485
|
+
: (values) => next("query", values),
|
|
486
|
+
headers: (values) => next("headers", values),
|
|
487
|
+
cookies: (values) => next("cookies", values),
|
|
488
|
+
body: (body) => request(path, method, bound, { ...inputs, body }),
|
|
489
|
+
...(isReady(operation, inputs) && {
|
|
490
|
+
send: (sendOptions) => sendRequest(path, method, operation, inputs, sendOptions),
|
|
491
|
+
...(canStream(operation) && {
|
|
492
|
+
stream: (sendOptions) => sendRequest(path, method, operation, inputs, sendOptions, true),
|
|
493
|
+
}),
|
|
494
|
+
}),
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
function branch(path, bound) {
|
|
498
|
+
if (!prefixes.has(path))
|
|
499
|
+
throw new TypeError(`Unknown OpenAPI path: ${path}`);
|
|
500
|
+
return {
|
|
501
|
+
path: (values) => branch(path, { ...bound, ...values }),
|
|
502
|
+
segment: (fragment) => branch(`${path === "/" ? "" : path}/${fragment}`, bound),
|
|
503
|
+
method(method) {
|
|
504
|
+
const operation = routes.get(path)?.get(method);
|
|
505
|
+
if (!operation)
|
|
506
|
+
throw new TypeError(`Unknown OpenAPI operation: ${method} ${path}`);
|
|
507
|
+
return request(path, method, operation, { ...empty, path: bound });
|
|
508
|
+
},
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
return ((path) => branch(path, {}));
|
|
512
|
+
}
|
|
513
|
+
/** Creates a browser-compatible route function from generated operation metadata. */
|
|
514
|
+
export function createFetchRoute(operations, options, validators = {}, securitySchemes = {}) {
|
|
515
|
+
return createRouteFromSources([
|
|
516
|
+
{
|
|
517
|
+
prefix: "",
|
|
518
|
+
definition: { operations, validators, securitySchemes },
|
|
519
|
+
options,
|
|
520
|
+
},
|
|
521
|
+
]);
|
|
522
|
+
}
|
|
523
|
+
/** Creates a route function for specs mounted at their configured URL prefixes. */
|
|
524
|
+
export function createPrefixedFetchRoute(sources) {
|
|
525
|
+
return createRouteFromSources(sources);
|
|
526
|
+
}
|
|
527
|
+
/** Creates grouped, named methods that use the same contract as the fluent client. */
|
|
528
|
+
export function createFetchSdk(operations, names, options, validators = {}, securitySchemes = {}) {
|
|
529
|
+
const sendRequest = createSendRequest(options, validators, securitySchemes);
|
|
530
|
+
const metadata = operations;
|
|
531
|
+
return Object.fromEntries(Object.entries(names).map(([group, methods]) => [
|
|
532
|
+
group,
|
|
533
|
+
Object.fromEntries(Object.entries(methods).map(([name, { path, method, pathParameters }]) => {
|
|
534
|
+
const operation = inputValue(inputValue(metadata, path) ?? {}, method);
|
|
535
|
+
if (!operation)
|
|
536
|
+
throw new TypeError(`Unknown OpenAPI operation: ${method} ${path}`);
|
|
537
|
+
const invoke = (stream) => async (...args) => {
|
|
538
|
+
const request = args.at(pathParameters.length);
|
|
539
|
+
const inputs = {
|
|
540
|
+
...empty,
|
|
541
|
+
path: Object.fromEntries(pathParameters.map((key, index) => [key, args.at(index)])),
|
|
542
|
+
headers: request?.headers ?? empty.headers,
|
|
543
|
+
cookies: request?.cookies ?? empty.cookies,
|
|
544
|
+
query: operation.querystring
|
|
545
|
+
? empty.query
|
|
546
|
+
: (request?.query ?? empty.query),
|
|
547
|
+
querystring: operation.querystring
|
|
548
|
+
? request?.query
|
|
549
|
+
: undefined,
|
|
550
|
+
body: request?.body,
|
|
551
|
+
};
|
|
552
|
+
if (!isReady(operation, inputs)) {
|
|
553
|
+
throw new TypeError(`Missing required inputs for OpenAPI operation: ${method} ${path}`);
|
|
554
|
+
}
|
|
555
|
+
return sendRequest(path, method, operation, inputs, request, stream);
|
|
556
|
+
};
|
|
557
|
+
const send = invoke(false);
|
|
558
|
+
return [
|
|
559
|
+
name,
|
|
560
|
+
canStream(operation)
|
|
561
|
+
? Object.assign(send, { stream: invoke(true) })
|
|
562
|
+
: send,
|
|
563
|
+
];
|
|
564
|
+
})),
|
|
565
|
+
]));
|
|
566
|
+
}
|
|
567
|
+
/** Binds the generated contract and naming metadata to its public SDK factory. */
|
|
568
|
+
export function defineFetchSdk(definition, names, validators, securitySchemes = {}) {
|
|
569
|
+
const routeDefinition = {
|
|
570
|
+
operations: definition.operations,
|
|
571
|
+
validators,
|
|
572
|
+
securitySchemes,
|
|
573
|
+
};
|
|
574
|
+
return Object.assign((...[options]) => {
|
|
575
|
+
const baseUrl = options?.baseUrl ?? definition.nativeBaseUrl;
|
|
576
|
+
if (baseUrl === undefined)
|
|
577
|
+
throw new TypeError("Missing API baseUrl");
|
|
578
|
+
return createFetchSdk(definition.operations, names, { ...options, baseUrl }, validators, securitySchemes);
|
|
579
|
+
}, { routeDefinition });
|
|
580
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare function mediaTypeOf(value: string | null): string | undefined;
|
|
2
|
+
export declare function isJsonMediaType(value: string): boolean;
|
|
3
|
+
/** Return the original declaration for the most specific matching media type. */
|
|
4
|
+
export declare function matchMediaType(declared: readonly string[], contentType: string | null): string | undefined;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export function mediaTypeOf(value) {
|
|
2
|
+
return value?.split(";", 1)[0]?.trim().toLowerCase();
|
|
3
|
+
}
|
|
4
|
+
export function isJsonMediaType(value) {
|
|
5
|
+
const mediaType = mediaTypeOf(value);
|
|
6
|
+
return (mediaType === "application/json" || mediaType?.endsWith("+json") === true);
|
|
7
|
+
}
|
|
8
|
+
function parameters(value) {
|
|
9
|
+
return Array.from(value.matchAll(/;\s*([^=\s;]+)\s*=\s*("(?:[^"\\]|\\.)*"|[^;]*)/gu), ([, name, raw]) => {
|
|
10
|
+
const key = name.toLowerCase();
|
|
11
|
+
const trimmed = raw.trim();
|
|
12
|
+
const parameter = trimmed.startsWith('"')
|
|
13
|
+
? trimmed.slice(1, -1).replaceAll(/\\(.)/gu, "$1")
|
|
14
|
+
: trimmed;
|
|
15
|
+
return [key, key === "charset" ? parameter.toLowerCase() : parameter];
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
/** Return the original declaration for the most specific matching media type. */
|
|
19
|
+
export function matchMediaType(declared, contentType) {
|
|
20
|
+
if (contentType === null)
|
|
21
|
+
return undefined;
|
|
22
|
+
const essence = mediaTypeOf(contentType);
|
|
23
|
+
const [type, subtype] = essence?.split("/") ?? [];
|
|
24
|
+
if (!type || !subtype || type === "*" || subtype === "*")
|
|
25
|
+
return undefined;
|
|
26
|
+
const received = new Map(parameters(contentType));
|
|
27
|
+
let match;
|
|
28
|
+
let bestRank = -1;
|
|
29
|
+
let bestParameterCount = -1;
|
|
30
|
+
for (const candidate of declared) {
|
|
31
|
+
const range = mediaTypeOf(candidate);
|
|
32
|
+
const rank = range === essence
|
|
33
|
+
? 2
|
|
34
|
+
: range === `${type}/*`
|
|
35
|
+
? 1
|
|
36
|
+
: range === "*/*"
|
|
37
|
+
? 0
|
|
38
|
+
: -1;
|
|
39
|
+
if (rank < 0 || rank < bestRank)
|
|
40
|
+
continue;
|
|
41
|
+
const required = parameters(candidate);
|
|
42
|
+
if ((rank > bestRank || required.length > bestParameterCount) &&
|
|
43
|
+
required.every(([key, value]) => received.get(key) === value)) {
|
|
44
|
+
match = candidate;
|
|
45
|
+
bestRank = rank;
|
|
46
|
+
bestParameterCount = required.length;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return match;
|
|
50
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
function isBinary(value) {
|
|
2
|
+
return value instanceof Blob || value instanceof Uint8Array;
|
|
3
|
+
}
|
|
4
|
+
function escapeParameter(value) {
|
|
5
|
+
return value
|
|
6
|
+
.replaceAll("\r", "%0D")
|
|
7
|
+
.replaceAll("\n", "%0A")
|
|
8
|
+
.replaceAll('"', "%22");
|
|
9
|
+
}
|
|
10
|
+
function partContentType(name, declared, blobType, fallback) {
|
|
11
|
+
if (!declared)
|
|
12
|
+
return blobType || fallback;
|
|
13
|
+
// OpenAPI permits a list of alternatives and media ranges. Emit a concrete
|
|
14
|
+
// type, preferring the type we can infer from the value.
|
|
15
|
+
const choices = declared.split(",").map((choice) => choice.trim());
|
|
16
|
+
const inferred = blobType || fallback || "text/plain";
|
|
17
|
+
const essence = inferred.split(";", 1)[0]?.trim().toLowerCase() ?? "";
|
|
18
|
+
const matched = /^[\w!#$%&'+.^`|~-]+\/[\w!#$%&'+.^`|~-]+$/u.test(essence)
|
|
19
|
+
? choices.find((choice) => {
|
|
20
|
+
const range = choice.split(";")[0]?.trim().toLowerCase();
|
|
21
|
+
return (range === essence ||
|
|
22
|
+
range === "*/*" ||
|
|
23
|
+
(range?.endsWith("/*") && essence.startsWith(range.slice(0, -1))));
|
|
24
|
+
})
|
|
25
|
+
: undefined;
|
|
26
|
+
if (matched)
|
|
27
|
+
return matched.split(";")[0]?.includes("*") ? inferred : matched;
|
|
28
|
+
if (fallback === "application/json") {
|
|
29
|
+
const json = choices.find(isJsonContentType);
|
|
30
|
+
if (json)
|
|
31
|
+
return json;
|
|
32
|
+
}
|
|
33
|
+
const concrete = choices.find((choice) => choice && !choice.split(";")[0]?.includes("*"));
|
|
34
|
+
if (concrete)
|
|
35
|
+
return concrete;
|
|
36
|
+
throw new TypeError(`Multipart field "${name}" requires a content type matching ${declared} but received ${inferred}`);
|
|
37
|
+
}
|
|
38
|
+
function isJsonContentType(value) {
|
|
39
|
+
const essence = value?.split(";")[0]?.trim().toLowerCase();
|
|
40
|
+
return essence === "application/json" || essence?.endsWith("+json") === true;
|
|
41
|
+
}
|
|
42
|
+
/** Encode native multipart fields with their per-part types and file names. */
|
|
43
|
+
export function encodeMultipartBody(fields, contentTypes) {
|
|
44
|
+
const boundary = `counterfact-${Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
45
|
+
const chunks = [];
|
|
46
|
+
const declaredTypes = new Map(Object.entries(contentTypes ?? {}));
|
|
47
|
+
for (const [name, value] of fields) {
|
|
48
|
+
for (const part of Array.isArray(value) ? value : [value]) {
|
|
49
|
+
if (part === undefined)
|
|
50
|
+
continue;
|
|
51
|
+
const blob = part instanceof Blob ? part : undefined;
|
|
52
|
+
const filename = isBinary(part)
|
|
53
|
+
? part instanceof File
|
|
54
|
+
? part.name
|
|
55
|
+
: "blob"
|
|
56
|
+
: undefined;
|
|
57
|
+
const object = typeof part === "object" && part !== null && filename === undefined;
|
|
58
|
+
const contentType = partContentType(name, declaredTypes.get(name), blob?.type ?? "", filename === undefined
|
|
59
|
+
? object
|
|
60
|
+
? "application/json"
|
|
61
|
+
: undefined
|
|
62
|
+
: "application/octet-stream");
|
|
63
|
+
const json = isJsonContentType(contentType);
|
|
64
|
+
if (object && !json)
|
|
65
|
+
throw new TypeError(`Multipart field "${name}" requires a pre-encoded part for ${contentType}`);
|
|
66
|
+
const header = contentType
|
|
67
|
+
? `Content-Type: ${new Headers({ "content-type": contentType }).get("content-type")}\r\n`
|
|
68
|
+
: "";
|
|
69
|
+
const disposition = `form-data; name="${escapeParameter(name)}"` +
|
|
70
|
+
(filename === undefined
|
|
71
|
+
? ""
|
|
72
|
+
: `; filename="${escapeParameter(filename)}"`);
|
|
73
|
+
chunks.push(`--${boundary}\r\nContent-Disposition: ${disposition}\r\n${header}\r\n`, part instanceof Uint8Array
|
|
74
|
+
? new Uint8Array(part)
|
|
75
|
+
: (blob ??
|
|
76
|
+
(json
|
|
77
|
+
? JSON.stringify(part)
|
|
78
|
+
: String(part).replaceAll(/\r\n|\r|\n/gu, "\r\n"))), "\r\n");
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
chunks.push(`--${boundary}--\r\n`);
|
|
82
|
+
return new Blob(chunks, {
|
|
83
|
+
type: `multipart/form-data; boundary=${boundary}`,
|
|
84
|
+
});
|
|
85
|
+
}
|
package/dist/route-builder.js
CHANGED
|
@@ -190,6 +190,7 @@ export class RouteBuilder {
|
|
|
190
190
|
}
|
|
191
191
|
getHeaderValue(name) {
|
|
192
192
|
const key = findHeaderKey(this._headerParams, name);
|
|
193
|
+
// eslint-disable-next-line security/detect-object-injection -- key comes from own header enumeration; arbitrary header names are supported.
|
|
193
194
|
return key === undefined ? undefined : this._headerParams[key];
|
|
194
195
|
}
|
|
195
196
|
getHeaderCookies() {
|
|
@@ -208,7 +209,8 @@ export class RouteBuilder {
|
|
|
208
209
|
return cookies;
|
|
209
210
|
}
|
|
210
211
|
getCookieValue(name) {
|
|
211
|
-
if (
|
|
212
|
+
if (Object.hasOwn(this._cookieParams, name))
|
|
213
|
+
// eslint-disable-next-line security/detect-object-injection -- The own-property check above limits this read to explicitly supplied cookie parameters.
|
|
212
214
|
return this._cookieParams[name];
|
|
213
215
|
return this.getHeaderCookies().get(name);
|
|
214
216
|
}
|
package/dist/route-catalog.js
CHANGED
|
@@ -23,11 +23,11 @@ export function createOpenApiRouteCatalog(document) {
|
|
|
23
23
|
return {
|
|
24
24
|
getOperation(routePath, method) {
|
|
25
25
|
const normalizedPath = routePath.toLowerCase();
|
|
26
|
-
const matchingPath = Object.
|
|
26
|
+
const matchingPath = Object.entries(document.paths).find(([path]) => path.toLowerCase() === normalizedPath);
|
|
27
27
|
if (matchingPath === undefined) {
|
|
28
28
|
return undefined;
|
|
29
29
|
}
|
|
30
|
-
const pathItem =
|
|
30
|
+
const pathItem = matchingPath[1];
|
|
31
31
|
const operation = pathItem?.[method.toLowerCase()];
|
|
32
32
|
if (!operation) {
|
|
33
33
|
return undefined;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// These standalone helpers contain no validator compiler. Ajv publishes them
|
|
2
|
+
// as CommonJS modules, so native ESM exposes the exports object as the default.
|
|
3
|
+
import equalModule from "ajv/dist/runtime/equal.js";
|
|
4
|
+
import lengthModule from "ajv/dist/runtime/ucs2length.js";
|
|
5
|
+
function asFunction(module) {
|
|
6
|
+
return typeof module === "object" && module !== null && "default" in module
|
|
7
|
+
? module.default
|
|
8
|
+
: module;
|
|
9
|
+
}
|
|
10
|
+
export const equal = asFunction(equalModule);
|
|
11
|
+
export const ucs2length = asFunction(lengthModule);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@counterfact/client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Build and send reusable OpenAPI-aware HTTP requests without starting Counterfact.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -9,6 +9,14 @@
|
|
|
9
9
|
".": {
|
|
10
10
|
"types": "./dist/index.d.ts",
|
|
11
11
|
"import": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./fetch": {
|
|
14
|
+
"types": "./dist/fetch.d.ts",
|
|
15
|
+
"import": "./dist/fetch.js"
|
|
16
|
+
},
|
|
17
|
+
"./validation-helpers": {
|
|
18
|
+
"types": "./dist/validation-helpers.d.ts",
|
|
19
|
+
"import": "./dist/validation-helpers.js"
|
|
12
20
|
}
|
|
13
21
|
},
|
|
14
22
|
"files": [
|
|
@@ -50,5 +58,9 @@
|
|
|
50
58
|
"prepack": "yarn build",
|
|
51
59
|
"test": "node --experimental-vm-modules ../../node_modules/jest-cli/bin/jest.js --config ../../jest.config.js packages/client/test",
|
|
52
60
|
"test:packed-consumer": "node test/package/client-consumer-smoke.mjs"
|
|
61
|
+
},
|
|
62
|
+
"dependencies": {
|
|
63
|
+
"@counterfact/types": "0.4.0",
|
|
64
|
+
"ajv": "8.20.0"
|
|
53
65
|
}
|
|
54
66
|
}
|