@hirosystems/token-metadata-api-client 1.2.0 → 2.0.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/lib/index.js ADDED
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.createClient = createClient;
18
+ const openapi_fetch_1 = require("openapi-fetch");
19
+ function createClient(options) {
20
+ return (0, openapi_fetch_1.default)({ baseUrl: 'https://api.mainnet.hiro.so', ...options });
21
+ }
22
+ __exportStar(require("openapi-fetch"), exports);
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAGA,oCAEC;AALD,iDAA8E;AAG9E,SAAgB,YAAY,CAAC,OAAuB;IAClD,OAAO,IAAA,uBAAmB,EAAQ,EAAE,OAAO,EAAE,6BAA6B,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC;AAC5F,CAAC;AAED,gDAA8B"}
@@ -0,0 +1,613 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = global || self, factory(global.TokenMetadataApiClient = {}));
5
+ })(this, (function (exports) {
6
+ function _extends() {
7
+ return _extends = Object.assign ? Object.assign.bind() : function (n) {
8
+ for (var e = 1; e < arguments.length; e++) {
9
+ var t = arguments[e];
10
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
11
+ }
12
+ return n;
13
+ }, _extends.apply(null, arguments);
14
+ }
15
+
16
+ // settings & const
17
+ const PATH_PARAM_RE = /\{[^{}]+\}/g;
18
+
19
+ /**
20
+ * Returns a cheap, non-cryptographically-secure random ID
21
+ * Courtesy of @imranbarbhuiya (https://github.com/imranbarbhuiya)
22
+ */
23
+ function randomID() {
24
+ return Math.random().toString(36).slice(2, 11);
25
+ }
26
+
27
+ /**
28
+ * Create an openapi-fetch client.
29
+ * @type {import("./index.js").default}
30
+ */
31
+ function createClient$1(clientOptions) {
32
+ let {
33
+ baseUrl = "",
34
+ Request: CustomRequest = globalThis.Request,
35
+ fetch: baseFetch = globalThis.fetch,
36
+ querySerializer: globalQuerySerializer,
37
+ bodySerializer: globalBodySerializer,
38
+ headers: baseHeaders,
39
+ ...baseOptions
40
+ } = { ...clientOptions };
41
+ baseUrl = removeTrailingSlash(baseUrl);
42
+ const middlewares = [];
43
+
44
+ /**
45
+ * Per-request fetch (keeps settings created in createClient()
46
+ * @param {T} url
47
+ * @param {import('./index.js').FetchOptions<T>} fetchOptions
48
+ */
49
+ async function coreFetch(schemaPath, fetchOptions) {
50
+ const {
51
+ baseUrl: localBaseUrl,
52
+ fetch = baseFetch,
53
+ Request = CustomRequest,
54
+ headers,
55
+ params = {},
56
+ parseAs = "json",
57
+ querySerializer: requestQuerySerializer,
58
+ bodySerializer = globalBodySerializer ?? defaultBodySerializer,
59
+ body,
60
+ ...init
61
+ } = fetchOptions || {};
62
+ if (localBaseUrl) {
63
+ baseUrl = removeTrailingSlash(localBaseUrl);
64
+ }
65
+
66
+ let querySerializer =
67
+ typeof globalQuerySerializer === "function"
68
+ ? globalQuerySerializer
69
+ : createQuerySerializer(globalQuerySerializer);
70
+ if (requestQuerySerializer) {
71
+ querySerializer =
72
+ typeof requestQuerySerializer === "function"
73
+ ? requestQuerySerializer
74
+ : createQuerySerializer({
75
+ ...(typeof globalQuerySerializer === "object" ? globalQuerySerializer : {}),
76
+ ...requestQuerySerializer,
77
+ });
78
+ }
79
+
80
+ const serializedBody = body === undefined ? undefined : bodySerializer(body);
81
+
82
+ const defaultHeaders =
83
+ // with no body, we should not to set Content-Type
84
+ serializedBody === undefined ||
85
+ // if serialized body is FormData; browser will correctly set Content-Type & boundary expression
86
+ serializedBody instanceof FormData
87
+ ? {}
88
+ : {
89
+ "Content-Type": "application/json",
90
+ };
91
+
92
+ const requestInit = {
93
+ redirect: "follow",
94
+ ...baseOptions,
95
+ ...init,
96
+ body: serializedBody,
97
+ headers: mergeHeaders(defaultHeaders, baseHeaders, headers, params.header),
98
+ };
99
+
100
+ let id;
101
+ let options;
102
+ let request = new CustomRequest(createFinalURL(schemaPath, { baseUrl, params, querySerializer }), requestInit);
103
+
104
+ /** Add custom parameters to Request object */
105
+ for (const key in init) {
106
+ if (!(key in request)) {
107
+ request[key] = init[key];
108
+ }
109
+ }
110
+
111
+ if (middlewares.length) {
112
+ id = randomID();
113
+
114
+ // middleware (request)
115
+ options = Object.freeze({
116
+ baseUrl,
117
+ fetch,
118
+ parseAs,
119
+ querySerializer,
120
+ bodySerializer,
121
+ });
122
+ for (const m of middlewares) {
123
+ if (m && typeof m === "object" && typeof m.onRequest === "function") {
124
+ const result = await m.onRequest({
125
+ request,
126
+ schemaPath,
127
+ params,
128
+ options,
129
+ id,
130
+ });
131
+ if (result) {
132
+ if (!(result instanceof CustomRequest)) {
133
+ throw new Error("onRequest: must return new Request() when modifying the request");
134
+ }
135
+ request = result;
136
+ }
137
+ }
138
+ }
139
+ }
140
+
141
+ // fetch!
142
+ let response = await fetch(request);
143
+
144
+ // middleware (response)
145
+ // execute in reverse-array order (first priority gets last transform)
146
+ if (middlewares.length) {
147
+ for (let i = middlewares.length - 1; i >= 0; i--) {
148
+ const m = middlewares[i];
149
+ if (m && typeof m === "object" && typeof m.onResponse === "function") {
150
+ const result = await m.onResponse({
151
+ request,
152
+ response,
153
+ schemaPath,
154
+ params,
155
+ options,
156
+ id,
157
+ });
158
+ if (result) {
159
+ if (!(result instanceof Response)) {
160
+ throw new Error("onResponse: must return new Response() when modifying the response");
161
+ }
162
+ response = result;
163
+ }
164
+ }
165
+ }
166
+ }
167
+
168
+ // handle empty content
169
+ // note: we return `{}` because we want user truthy checks for `.data` or `.error` to succeed
170
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
171
+ return response.ok ? { data: {}, response } : { error: {}, response };
172
+ }
173
+
174
+ // parse response (falling back to .text() when necessary)
175
+ if (response.ok) {
176
+ // if "stream", skip parsing entirely
177
+ if (parseAs === "stream") {
178
+ return { data: response.body, response };
179
+ }
180
+ return { data: await response[parseAs](), response };
181
+ }
182
+
183
+ // handle errors
184
+ let error = await response.text();
185
+ try {
186
+ error = JSON.parse(error); // attempt to parse as JSON
187
+ } catch {
188
+ // noop
189
+ }
190
+ return { error, response };
191
+ }
192
+
193
+ return {
194
+ /** Call a GET endpoint */
195
+ GET(url, init) {
196
+ return coreFetch(url, { ...init, method: "GET" });
197
+ },
198
+ /** Call a PUT endpoint */
199
+ PUT(url, init) {
200
+ return coreFetch(url, { ...init, method: "PUT" });
201
+ },
202
+ /** Call a POST endpoint */
203
+ POST(url, init) {
204
+ return coreFetch(url, { ...init, method: "POST" });
205
+ },
206
+ /** Call a DELETE endpoint */
207
+ DELETE(url, init) {
208
+ return coreFetch(url, { ...init, method: "DELETE" });
209
+ },
210
+ /** Call a OPTIONS endpoint */
211
+ OPTIONS(url, init) {
212
+ return coreFetch(url, { ...init, method: "OPTIONS" });
213
+ },
214
+ /** Call a HEAD endpoint */
215
+ HEAD(url, init) {
216
+ return coreFetch(url, { ...init, method: "HEAD" });
217
+ },
218
+ /** Call a PATCH endpoint */
219
+ PATCH(url, init) {
220
+ return coreFetch(url, { ...init, method: "PATCH" });
221
+ },
222
+ /** Call a TRACE endpoint */
223
+ TRACE(url, init) {
224
+ return coreFetch(url, { ...init, method: "TRACE" });
225
+ },
226
+ /** Register middleware */
227
+ use(...middleware) {
228
+ for (const m of middleware) {
229
+ if (!m) {
230
+ continue;
231
+ }
232
+ if (typeof m !== "object" || !("onRequest" in m || "onResponse" in m)) {
233
+ throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");
234
+ }
235
+ middlewares.push(m);
236
+ }
237
+ },
238
+ /** Unregister middleware */
239
+ eject(...middleware) {
240
+ for (const m of middleware) {
241
+ const i = middlewares.indexOf(m);
242
+ if (i !== -1) {
243
+ middlewares.splice(i, 1);
244
+ }
245
+ }
246
+ },
247
+ };
248
+ }
249
+
250
+ class PathCallForwarder {
251
+ constructor(client, url) {
252
+ this.client = client;
253
+ this.url = url;
254
+ }
255
+
256
+ GET(init) {
257
+ return this.client.GET(this.url, init);
258
+ }
259
+ PUT(init) {
260
+ return this.client.PUT(this.url, init);
261
+ }
262
+ POST(init) {
263
+ return this.client.POST(this.url, init);
264
+ }
265
+ DELETE(init) {
266
+ return this.client.DELETE(this.url, init);
267
+ }
268
+ OPTIONS(init) {
269
+ return this.client.OPTIONS(this.url, init);
270
+ }
271
+ HEAD(init) {
272
+ return this.client.HEAD(this.url, init);
273
+ }
274
+ PATCH(init) {
275
+ return this.client.PATCH(this.url, init);
276
+ }
277
+ TRACE(init) {
278
+ return this.client.TRACE(this.url, init);
279
+ }
280
+ }
281
+
282
+ class PathClientProxyHandler {
283
+ constructor() {
284
+ this.client = null;
285
+ }
286
+
287
+ // Assume the property is an URL.
288
+ get(coreClient, url) {
289
+ const forwarder = new PathCallForwarder(coreClient, url);
290
+ this.client[url] = forwarder;
291
+ return forwarder;
292
+ }
293
+ }
294
+
295
+ /**
296
+ * Wrap openapi-fetch client to support a path based API.
297
+ * @type {import("./index.js").wrapAsPathBasedClient}
298
+ */
299
+ function wrapAsPathBasedClient(coreClient) {
300
+ const handler = new PathClientProxyHandler();
301
+ const proxy = new Proxy(coreClient, handler);
302
+
303
+ // Put the proxy on the prototype chain of the actual client.
304
+ // This means if we do not have a memoized PathCallForwarder,
305
+ // we fall back to the proxy to synthesize it.
306
+ // However, the proxy itself is not on the hot-path (if we fetch the same
307
+ // endpoint multiple times, only the first call will hit the proxy).
308
+ function Client() {}
309
+ Client.prototype = proxy;
310
+
311
+ const client = new Client();
312
+
313
+ // Feed the client back to the proxy handler so it can store the generated
314
+ // PathCallForwarder.
315
+ handler.client = client;
316
+
317
+ return client;
318
+ }
319
+
320
+ /**
321
+ * Convenience method to an openapi-fetch path based client.
322
+ * Strictly equivalent to `wrapAsPathBasedClient(createClient(...))`.
323
+ * @type {import("./index.js").createPathBasedClient}
324
+ */
325
+ function createPathBasedClient(clientOptions) {
326
+ return wrapAsPathBasedClient(createClient$1(clientOptions));
327
+ }
328
+
329
+ // utils
330
+
331
+ /**
332
+ * Serialize primitive param values
333
+ * @type {import("./index.js").serializePrimitiveParam}
334
+ */
335
+ function serializePrimitiveParam(name, value, options) {
336
+ if (value === undefined || value === null) {
337
+ return "";
338
+ }
339
+ if (typeof value === "object") {
340
+ throw new Error(
341
+ "Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.",
342
+ );
343
+ }
344
+ return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;
345
+ }
346
+
347
+ /**
348
+ * Serialize object param (shallow only)
349
+ * @type {import("./index.js").serializeObjectParam}
350
+ */
351
+ function serializeObjectParam(name, value, options) {
352
+ if (!value || typeof value !== "object") {
353
+ return "";
354
+ }
355
+ const values = [];
356
+ const joiner =
357
+ {
358
+ simple: ",",
359
+ label: ".",
360
+ matrix: ";",
361
+ }[options.style] || "&";
362
+
363
+ // explode: false
364
+ if (options.style !== "deepObject" && options.explode === false) {
365
+ for (const k in value) {
366
+ values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));
367
+ }
368
+ const final = values.join(","); // note: values are always joined by comma in explode: false (but joiner can prefix)
369
+ switch (options.style) {
370
+ case "form": {
371
+ return `${name}=${final}`;
372
+ }
373
+ case "label": {
374
+ return `.${final}`;
375
+ }
376
+ case "matrix": {
377
+ return `;${name}=${final}`;
378
+ }
379
+ default: {
380
+ return final;
381
+ }
382
+ }
383
+ }
384
+
385
+ // explode: true
386
+ for (const k in value) {
387
+ const finalName = options.style === "deepObject" ? `${name}[${k}]` : k;
388
+ values.push(serializePrimitiveParam(finalName, value[k], options));
389
+ }
390
+ const final = values.join(joiner);
391
+ return options.style === "label" || options.style === "matrix" ? `${joiner}${final}` : final;
392
+ }
393
+
394
+ /**
395
+ * Serialize array param (shallow only)
396
+ * @type {import("./index.js").serializeArrayParam}
397
+ */
398
+ function serializeArrayParam(name, value, options) {
399
+ if (!Array.isArray(value)) {
400
+ return "";
401
+ }
402
+
403
+ // explode: false
404
+ if (options.explode === false) {
405
+ const joiner = { form: ",", spaceDelimited: "%20", pipeDelimited: "|" }[options.style] || ","; // note: for arrays, joiners vary wildly based on style + explode behavior
406
+ const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner);
407
+ switch (options.style) {
408
+ case "simple": {
409
+ return final;
410
+ }
411
+ case "label": {
412
+ return `.${final}`;
413
+ }
414
+ case "matrix": {
415
+ return `;${name}=${final}`;
416
+ }
417
+ // case "spaceDelimited":
418
+ // case "pipeDelimited":
419
+ default: {
420
+ return `${name}=${final}`;
421
+ }
422
+ }
423
+ }
424
+
425
+ // explode: true
426
+ const joiner = { simple: ",", label: ".", matrix: ";" }[options.style] || "&";
427
+ const values = [];
428
+ for (const v of value) {
429
+ if (options.style === "simple" || options.style === "label") {
430
+ values.push(options.allowReserved === true ? v : encodeURIComponent(v));
431
+ } else {
432
+ values.push(serializePrimitiveParam(name, v, options));
433
+ }
434
+ }
435
+ return options.style === "label" || options.style === "matrix"
436
+ ? `${joiner}${values.join(joiner)}`
437
+ : values.join(joiner);
438
+ }
439
+
440
+ /**
441
+ * Serialize query params to string
442
+ * @type {import("./index.js").createQuerySerializer}
443
+ */
444
+ function createQuerySerializer(options) {
445
+ return function querySerializer(queryParams) {
446
+ const search = [];
447
+ if (queryParams && typeof queryParams === "object") {
448
+ for (const name in queryParams) {
449
+ const value = queryParams[name];
450
+ if (value === undefined || value === null) {
451
+ continue;
452
+ }
453
+ if (Array.isArray(value)) {
454
+ search.push(
455
+ serializeArrayParam(name, value, {
456
+ style: "form",
457
+ explode: true,
458
+ ...options?.array,
459
+ allowReserved: options?.allowReserved || false,
460
+ }),
461
+ );
462
+ continue;
463
+ }
464
+ if (typeof value === "object") {
465
+ search.push(
466
+ serializeObjectParam(name, value, {
467
+ style: "deepObject",
468
+ explode: true,
469
+ ...options?.object,
470
+ allowReserved: options?.allowReserved || false,
471
+ }),
472
+ );
473
+ continue;
474
+ }
475
+ search.push(serializePrimitiveParam(name, value, options));
476
+ }
477
+ }
478
+ return search.join("&");
479
+ };
480
+ }
481
+
482
+ /**
483
+ * Handle different OpenAPI 3.x serialization styles
484
+ * @type {import("./index.js").defaultPathSerializer}
485
+ * @see https://swagger.io/docs/specification/serialization/#path
486
+ */
487
+ function defaultPathSerializer(pathname, pathParams) {
488
+ let nextURL = pathname;
489
+ for (const match of pathname.match(PATH_PARAM_RE) ?? []) {
490
+ let name = match.substring(1, match.length - 1);
491
+ let explode = false;
492
+ let style = "simple";
493
+ if (name.endsWith("*")) {
494
+ explode = true;
495
+ name = name.substring(0, name.length - 1);
496
+ }
497
+ if (name.startsWith(".")) {
498
+ style = "label";
499
+ name = name.substring(1);
500
+ } else if (name.startsWith(";")) {
501
+ style = "matrix";
502
+ name = name.substring(1);
503
+ }
504
+ if (!pathParams || pathParams[name] === undefined || pathParams[name] === null) {
505
+ continue;
506
+ }
507
+ const value = pathParams[name];
508
+ if (Array.isArray(value)) {
509
+ nextURL = nextURL.replace(match, serializeArrayParam(name, value, { style, explode }));
510
+ continue;
511
+ }
512
+ if (typeof value === "object") {
513
+ nextURL = nextURL.replace(match, serializeObjectParam(name, value, { style, explode }));
514
+ continue;
515
+ }
516
+ if (style === "matrix") {
517
+ nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);
518
+ continue;
519
+ }
520
+ nextURL = nextURL.replace(match, style === "label" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));
521
+ }
522
+ return nextURL;
523
+ }
524
+
525
+ /**
526
+ * Serialize body object to string
527
+ * @type {import("./index.js").defaultBodySerializer}
528
+ */
529
+ function defaultBodySerializer(body) {
530
+ if (body instanceof FormData) {
531
+ return body;
532
+ }
533
+ return JSON.stringify(body);
534
+ }
535
+
536
+ /**
537
+ * Construct URL string from baseUrl and handle path and query params
538
+ * @type {import("./index.js").createFinalURL}
539
+ */
540
+ function createFinalURL(pathname, options) {
541
+ let finalURL = `${options.baseUrl}${pathname}`;
542
+ if (options.params?.path) {
543
+ finalURL = defaultPathSerializer(finalURL, options.params.path);
544
+ }
545
+ let search = options.querySerializer(options.params.query ?? {});
546
+ if (search.startsWith("?")) {
547
+ search = search.substring(1);
548
+ }
549
+ if (search) {
550
+ finalURL += `?${search}`;
551
+ }
552
+ return finalURL;
553
+ }
554
+
555
+ /**
556
+ * Merge headers a and b, with b taking priority
557
+ * @type {import("./index.js").mergeHeaders}
558
+ */
559
+ function mergeHeaders(...allHeaders) {
560
+ const finalHeaders = new Headers();
561
+ for (const h of allHeaders) {
562
+ if (!h || typeof h !== "object") {
563
+ continue;
564
+ }
565
+ const iterator = h instanceof Headers ? h.entries() : Object.entries(h);
566
+ for (const [k, v] of iterator) {
567
+ if (v === null) {
568
+ finalHeaders.delete(k);
569
+ } else if (Array.isArray(v)) {
570
+ for (const v2 of v) {
571
+ finalHeaders.append(k, v2);
572
+ }
573
+ } else if (v !== undefined) {
574
+ finalHeaders.set(k, v);
575
+ }
576
+ }
577
+ }
578
+ return finalHeaders;
579
+ }
580
+
581
+ /**
582
+ * Remove trailing slash from url
583
+ * @type {import("./index.js").removeTrailingSlash}
584
+ */
585
+ function removeTrailingSlash(url) {
586
+ if (url.endsWith("/")) {
587
+ return url.substring(0, url.length - 1);
588
+ }
589
+ return url;
590
+ }
591
+
592
+ function createClient(options) {
593
+ return createClient$1(_extends({
594
+ baseUrl: 'https://api.mainnet.hiro.so'
595
+ }, options));
596
+ }
597
+
598
+ exports.createClient = createClient;
599
+ exports.createFinalURL = createFinalURL;
600
+ exports.createPathBasedClient = createPathBasedClient;
601
+ exports.createQuerySerializer = createQuerySerializer;
602
+ exports.defaultBodySerializer = defaultBodySerializer;
603
+ exports.defaultPathSerializer = defaultPathSerializer;
604
+ exports.mergeHeaders = mergeHeaders;
605
+ exports.randomID = randomID;
606
+ exports.removeTrailingSlash = removeTrailingSlash;
607
+ exports.serializeArrayParam = serializeArrayParam;
608
+ exports.serializeObjectParam = serializeObjectParam;
609
+ exports.serializePrimitiveParam = serializePrimitiveParam;
610
+ exports.wrapAsPathBasedClient = wrapAsPathBasedClient;
611
+
612
+ }));
613
+ //# sourceMappingURL=index.umd.js.map