@withmarfa/client 0.0.83 → 0.0.86

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/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  The TypeScript SDK for a Marfa instance, generated from the repository's `openapi.json`. Paths, parameters, bodies and answers are typed from the document: a path the document does not name, or a required parameter left out, does not compile. Ranges and formats the document states only in prose are the server's to refuse.
4
4
 
5
+ The package loads through `import` and through `require`, so it works in an ES module project and in a CommonJS one, including a TypeScript project compiled with `module` set to `node16` or `nodenext`.
6
+
5
7
  ```ts
6
8
  import { createClient, pages } from "@withmarfa/client";
7
9
 
package/dist/index.cjs ADDED
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ CONTRACT_HEADER: () => CONTRACT_HEADER,
34
+ CONTRACT_VERSION: () => CONTRACT_VERSION,
35
+ ContractMismatchError: () => ContractMismatchError,
36
+ createClient: () => createClient,
37
+ pages: () => pages
38
+ });
39
+ module.exports = __toCommonJS(index_exports);
40
+ var import_openapi_fetch = __toESM(require("openapi-fetch"), 1);
41
+
42
+ // src/generated/byte-bodies.ts
43
+ var BYTE_BODIES = {
44
+ "POST /blobs": "application/octet-stream",
45
+ "PUT /profile/avatar": "application/octet-stream",
46
+ "POST /restore": "application/x-tar"
47
+ };
48
+
49
+ // src/generated/contract.ts
50
+ var CONTRACT_VERSION = 0;
51
+
52
+ // src/index.ts
53
+ var CONTRACT_HEADER = "X-Marfa-Contract";
54
+ var ContractMismatchError = class extends Error {
55
+ constructor(served, status, expected = CONTRACT_VERSION) {
56
+ super(
57
+ served === null ? `The server answered ${String(status)} with no contract version, so its body cannot be read by a client generated for contract ${String(expected)}.` : `The server answered with contract ${JSON.stringify(served)}; this client was generated for contract ${String(expected)}. Use a client generated for the server's contract.`
58
+ );
59
+ this.served = served;
60
+ this.status = status;
61
+ this.expected = expected;
62
+ this.name = "ContractMismatchError";
63
+ }
64
+ served;
65
+ status;
66
+ expected;
67
+ };
68
+ var BEARER = /^[A-Za-z0-9\-._~+/]+=*$/;
69
+ function checkCredential(credential) {
70
+ if (BEARER.test(credential)) return;
71
+ if (credential === "") {
72
+ throw new TypeError("credential is empty");
73
+ }
74
+ const at = credential.search(/[^A-Za-z0-9\-._~+/=]/);
75
+ throw new TypeError(
76
+ at === -1 ? "credential is not a bearer token: '=' may only end one, after at least one other character" : `credential is not a bearer token: the character at index ${String(at)} is not one a bearer token may hold`
77
+ );
78
+ }
79
+ function createClient(options) {
80
+ const fetcher = options.fetch ?? globalThis.fetch;
81
+ if (/[?#]/.test(options.baseUrl)) {
82
+ throw new TypeError(
83
+ "baseUrl names where the instance is served, with no query or fragment"
84
+ );
85
+ }
86
+ const base = new URL(options.baseUrl);
87
+ if (base.protocol !== "http:" && base.protocol !== "https:") {
88
+ throw new TypeError(`baseUrl must be http or https, not ${base.protocol}`);
89
+ }
90
+ const baseUrl = base.href.replace(/\/+$/, "");
91
+ const credential = options.credential;
92
+ checkCredential(credential);
93
+ const root = new URL(`${baseUrl}/`).href;
94
+ const expected = String(CONTRACT_VERSION);
95
+ const hold = async (response) => {
96
+ const served = response.headers.get(CONTRACT_HEADER);
97
+ if (served === expected) return response;
98
+ if (served === null && !response.ok) return response;
99
+ await response.body?.cancel();
100
+ throw new ContractMismatchError(served, response.status);
101
+ };
102
+ const describesServer = (request) => {
103
+ if (request.method !== "GET") return false;
104
+ const path = request.url.slice(root.length).split(/[?#]/, 1)[0];
105
+ return path === "" || path === "health";
106
+ };
107
+ const send = async (request) => {
108
+ if (!request.url.startsWith(root)) {
109
+ throw new Error(
110
+ `This client is for ${baseUrl}; it refuses to send ${request.url}.`
111
+ );
112
+ }
113
+ const headers = new Headers(request.headers);
114
+ headers.set("Authorization", `Bearer ${credential}`);
115
+ if (describesServer(request)) headers.delete(CONTRACT_HEADER);
116
+ else headers.set(CONTRACT_HEADER, expected);
117
+ return hold(
118
+ await fetcher(new Request(request, { headers, redirect: "error" }))
119
+ );
120
+ };
121
+ const gate = {
122
+ onRequest({ params }) {
123
+ for (const value of Object.values(params.path ?? {})) {
124
+ if (value === "." || value === "..") {
125
+ throw new Error(
126
+ `A path parameter of ${JSON.stringify(value)} names no resource.`
127
+ );
128
+ }
129
+ }
130
+ return void 0;
131
+ },
132
+ // A caller can hand one request a `fetch` of its own, which does not
133
+ // pass through `send`; its answer is still held here.
134
+ onResponse({ response }) {
135
+ return hold(response);
136
+ }
137
+ };
138
+ const serialize = import_openapi_fetch.defaultBodySerializer;
139
+ const client = (0, import_openapi_fetch.default)({
140
+ baseUrl,
141
+ fetch: send,
142
+ bodySerializer: (body, headers) => isBytes(body) ? body : serialize(body, headers)
143
+ });
144
+ client.use(gate);
145
+ labelBytes(client);
146
+ return client;
147
+ }
148
+ var isBytes = (body) => body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof ReadableStream;
149
+ function labelBytes(client) {
150
+ const label = (method, path, init) => {
151
+ const body = init?.body;
152
+ if (!init || !isBytes(body)) return init;
153
+ const own = body instanceof Blob ? body.type : "";
154
+ const type = own !== "" ? own : BYTE_BODIES[`${method} ${path}`] ?? "application/octet-stream";
155
+ return {
156
+ ...init,
157
+ headers: (0, import_openapi_fetch.mergeHeaders)({ "Content-Type": type }, init.headers),
158
+ // fetch refuses a streamed body unless told it is sent in one
159
+ // direction, before any answer is read.
160
+ ...body instanceof ReadableStream ? { duplex: "half" } : {}
161
+ };
162
+ };
163
+ const request = client.request;
164
+ const labeled = (method, path, init) => request(method, path, label(method.toUpperCase(), path, init));
165
+ const calls = client;
166
+ calls.request = labeled;
167
+ for (const method of [
168
+ "GET",
169
+ "PUT",
170
+ "POST",
171
+ "DELETE",
172
+ "OPTIONS",
173
+ "HEAD",
174
+ "PATCH",
175
+ "TRACE"
176
+ ]) {
177
+ calls[method] = (path, init) => labeled(method, path, init);
178
+ }
179
+ }
180
+ async function* pages(fetchPage) {
181
+ let cursor;
182
+ const followed = /* @__PURE__ */ new Set();
183
+ for (; ; ) {
184
+ const page = await fetchPage(cursor);
185
+ if (page.next_cursor !== null && typeof page.next_cursor !== "string") {
186
+ throw new Error(
187
+ "A page answered no next_cursor, so the walk cannot continue."
188
+ );
189
+ }
190
+ yield* page.data;
191
+ if (page.next_cursor === null) return;
192
+ if (followed.has(page.next_cursor)) {
193
+ throw new Error(
194
+ "The server answered a cursor this walk already followed, so it would not end."
195
+ );
196
+ }
197
+ followed.add(page.next_cursor);
198
+ cursor = page.next_cursor;
199
+ }
200
+ }
201
+ // Annotate the CommonJS export names for ESM import in node:
202
+ 0 && (module.exports = {
203
+ CONTRACT_HEADER,
204
+ CONTRACT_VERSION,
205
+ ContractMismatchError,
206
+ createClient,
207
+ pages
208
+ });