@proxyrequest/sdk 2.0.0 → 3.0.1

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/dist/index.js CHANGED
@@ -1,5 +1,883 @@
1
- import createClient from "openapi-fetch";
1
+ //#region node_modules/openapi-fetch/dist/index.mjs
2
+ const PATH_PARAM_RE = /\{[^{}]+\}/g;
3
+ const supportsRequestInitExt = () => {
4
+ return typeof process === "object" && Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 && process.versions.undici;
5
+ };
6
+ function randomID() {
7
+ return Math.random().toString(36).slice(2, 11);
8
+ }
9
+ function createClient(clientOptions) {
10
+ let { baseUrl = "", Request: CustomRequest = globalThis.Request, fetch: baseFetch = globalThis.fetch, querySerializer: globalQuerySerializer, bodySerializer: globalBodySerializer, pathSerializer: globalPathSerializer, headers: baseHeaders, requestInitExt = void 0, ...baseOptions } = { ...clientOptions };
11
+ requestInitExt = supportsRequestInitExt() ? requestInitExt : void 0;
12
+ baseUrl = removeTrailingSlash(baseUrl);
13
+ const globalMiddlewares = [];
14
+ async function coreFetch(schemaPath, fetchOptions) {
15
+ const { baseUrl: localBaseUrl, fetch = baseFetch, Request = CustomRequest, headers, params = {}, parseAs = "json", querySerializer: requestQuerySerializer, bodySerializer = globalBodySerializer ?? defaultBodySerializer, pathSerializer: requestPathSerializer, body, middleware: requestMiddlewares = [], ...init } = fetchOptions || {};
16
+ let finalBaseUrl = baseUrl;
17
+ if (localBaseUrl) finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;
18
+ let querySerializer = typeof globalQuerySerializer === "function" ? globalQuerySerializer : createQuerySerializer(globalQuerySerializer);
19
+ if (requestQuerySerializer) querySerializer = typeof requestQuerySerializer === "function" ? requestQuerySerializer : createQuerySerializer({
20
+ ...typeof globalQuerySerializer === "object" ? globalQuerySerializer : {},
21
+ ...requestQuerySerializer
22
+ });
23
+ const pathSerializer = requestPathSerializer || globalPathSerializer || defaultPathSerializer;
24
+ const serializedBody = body === void 0 ? void 0 : bodySerializer(body, mergeHeaders(baseHeaders, headers, params.header));
25
+ const finalHeaders = mergeHeaders(serializedBody === void 0 || serializedBody instanceof FormData ? {} : { "Content-Type": "application/json" }, baseHeaders, headers, params.header);
26
+ const finalMiddlewares = [...globalMiddlewares, ...requestMiddlewares];
27
+ const requestInit = {
28
+ redirect: "follow",
29
+ ...baseOptions,
30
+ ...init,
31
+ body: serializedBody,
32
+ headers: finalHeaders
33
+ };
34
+ let id;
35
+ let options;
36
+ let request = new Request(createFinalURL(schemaPath, {
37
+ baseUrl: finalBaseUrl,
38
+ params,
39
+ querySerializer,
40
+ pathSerializer
41
+ }), requestInit);
42
+ let response;
43
+ for (const key in init) if (!(key in request)) request[key] = init[key];
44
+ if (finalMiddlewares.length) {
45
+ id = randomID();
46
+ options = Object.freeze({
47
+ baseUrl: finalBaseUrl,
48
+ fetch,
49
+ parseAs,
50
+ querySerializer,
51
+ bodySerializer,
52
+ pathSerializer
53
+ });
54
+ for (const m of finalMiddlewares) if (m && typeof m === "object" && typeof m.onRequest === "function") {
55
+ const result = await m.onRequest({
56
+ request,
57
+ schemaPath,
58
+ params,
59
+ options,
60
+ id
61
+ });
62
+ if (result) {
63
+ if (result instanceof Request) request = result;
64
+ else if (result instanceof Response) {
65
+ response = result;
66
+ break;
67
+ } else throw new Error("onRequest: must return new Request() or Response() when modifying the request");
68
+ }
69
+ }
70
+ }
71
+ if (!response) {
72
+ try {
73
+ response = await fetch(request, requestInitExt);
74
+ } catch (error2) {
75
+ let errorAfterMiddleware = error2;
76
+ if (finalMiddlewares.length) for (let i = finalMiddlewares.length - 1; i >= 0; i--) {
77
+ const m = finalMiddlewares[i];
78
+ if (m && typeof m === "object" && typeof m.onError === "function") {
79
+ const result = await m.onError({
80
+ request,
81
+ error: errorAfterMiddleware,
82
+ schemaPath,
83
+ params,
84
+ options,
85
+ id
86
+ });
87
+ if (result) {
88
+ if (result instanceof Response) {
89
+ errorAfterMiddleware = void 0;
90
+ response = result;
91
+ break;
92
+ }
93
+ if (result instanceof Error) {
94
+ errorAfterMiddleware = result;
95
+ continue;
96
+ }
97
+ throw new Error("onError: must return new Response() or instance of Error");
98
+ }
99
+ }
100
+ }
101
+ if (errorAfterMiddleware) throw errorAfterMiddleware;
102
+ }
103
+ if (finalMiddlewares.length) for (let i = finalMiddlewares.length - 1; i >= 0; i--) {
104
+ const m = finalMiddlewares[i];
105
+ if (m && typeof m === "object" && typeof m.onResponse === "function") {
106
+ const result = await m.onResponse({
107
+ request,
108
+ response,
109
+ schemaPath,
110
+ params,
111
+ options,
112
+ id
113
+ });
114
+ if (result) {
115
+ if (!(result instanceof Response)) throw new Error("onResponse: must return new Response() when modifying the response");
116
+ response = result;
117
+ }
118
+ }
119
+ }
120
+ }
121
+ const contentLength = response.headers.get("Content-Length");
122
+ if (response.status === 204 || request.method === "HEAD" || contentLength === "0" && !response.headers.get("Transfer-Encoding")?.includes("chunked")) return response.ok ? {
123
+ data: void 0,
124
+ response
125
+ } : {
126
+ error: void 0,
127
+ response
128
+ };
129
+ if (response.ok) {
130
+ const getResponseData = async () => {
131
+ if (parseAs === "stream") return response.body;
132
+ if (parseAs === "json" && !contentLength) {
133
+ const raw = await response.text();
134
+ return raw ? JSON.parse(raw) : void 0;
135
+ }
136
+ return await response[parseAs]();
137
+ };
138
+ return {
139
+ data: await getResponseData(),
140
+ response
141
+ };
142
+ }
143
+ let error = await response.text();
144
+ try {
145
+ error = JSON.parse(error);
146
+ } catch {}
147
+ return {
148
+ error,
149
+ response
150
+ };
151
+ }
152
+ return {
153
+ request(method, url, init) {
154
+ return coreFetch(url, {
155
+ ...init,
156
+ method: method.toUpperCase()
157
+ });
158
+ },
159
+ /** Call a GET endpoint */
160
+ GET(url, init) {
161
+ return coreFetch(url, {
162
+ ...init,
163
+ method: "GET"
164
+ });
165
+ },
166
+ /** Call a PUT endpoint */
167
+ PUT(url, init) {
168
+ return coreFetch(url, {
169
+ ...init,
170
+ method: "PUT"
171
+ });
172
+ },
173
+ /** Call a POST endpoint */
174
+ POST(url, init) {
175
+ return coreFetch(url, {
176
+ ...init,
177
+ method: "POST"
178
+ });
179
+ },
180
+ /** Call a DELETE endpoint */
181
+ DELETE(url, init) {
182
+ return coreFetch(url, {
183
+ ...init,
184
+ method: "DELETE"
185
+ });
186
+ },
187
+ /** Call a OPTIONS endpoint */
188
+ OPTIONS(url, init) {
189
+ return coreFetch(url, {
190
+ ...init,
191
+ method: "OPTIONS"
192
+ });
193
+ },
194
+ /** Call a HEAD endpoint */
195
+ HEAD(url, init) {
196
+ return coreFetch(url, {
197
+ ...init,
198
+ method: "HEAD"
199
+ });
200
+ },
201
+ /** Call a PATCH endpoint */
202
+ PATCH(url, init) {
203
+ return coreFetch(url, {
204
+ ...init,
205
+ method: "PATCH"
206
+ });
207
+ },
208
+ /** Call a TRACE endpoint */
209
+ TRACE(url, init) {
210
+ return coreFetch(url, {
211
+ ...init,
212
+ method: "TRACE"
213
+ });
214
+ },
215
+ /** Register middleware */
216
+ use(...middleware) {
217
+ for (const m of middleware) {
218
+ if (!m) continue;
219
+ if (typeof m !== "object" || !("onRequest" in m || "onResponse" in m || "onError" in m)) throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
220
+ globalMiddlewares.push(m);
221
+ }
222
+ },
223
+ /** Unregister middleware */
224
+ eject(...middleware) {
225
+ for (const m of middleware) {
226
+ const i = globalMiddlewares.indexOf(m);
227
+ if (i !== -1) globalMiddlewares.splice(i, 1);
228
+ }
229
+ }
230
+ };
231
+ }
232
+ function serializePrimitiveParam(name, value, options) {
233
+ if (value === void 0 || value === null) return "";
234
+ if (typeof value === "object") throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
235
+ return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;
236
+ }
237
+ function serializeObjectParam(name, value, options) {
238
+ if (!value || typeof value !== "object") return "";
239
+ const values = [];
240
+ const joiner = {
241
+ simple: ",",
242
+ label: ".",
243
+ matrix: ";"
244
+ }[options.style] || "&";
245
+ if (options.style !== "deepObject" && options.explode === false) {
246
+ for (const k in value) values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));
247
+ const final2 = values.join(",");
248
+ switch (options.style) {
249
+ case "form": return `${name}=${final2}`;
250
+ case "label": return `.${final2}`;
251
+ case "matrix": return `;${name}=${final2}`;
252
+ default: return final2;
253
+ }
254
+ }
255
+ for (const k in value) {
256
+ const finalName = options.style === "deepObject" ? `${name}[${k}]` : k;
257
+ values.push(serializePrimitiveParam(finalName, value[k], options));
258
+ }
259
+ const final = values.join(joiner);
260
+ return options.style === "label" || options.style === "matrix" ? `${joiner}${final}` : final;
261
+ }
262
+ function serializeArrayParam(name, value, options) {
263
+ if (!Array.isArray(value)) return "";
264
+ if (options.explode === false) {
265
+ const joiner2 = {
266
+ form: ",",
267
+ spaceDelimited: "%20",
268
+ pipeDelimited: "|"
269
+ }[options.style] || ",";
270
+ const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner2);
271
+ switch (options.style) {
272
+ case "simple": return final;
273
+ case "label": return `.${final}`;
274
+ case "matrix": return `;${name}=${final}`;
275
+ default: return `${name}=${final}`;
276
+ }
277
+ }
278
+ const joiner = {
279
+ simple: ",",
280
+ label: ".",
281
+ matrix: ";"
282
+ }[options.style] || "&";
283
+ const values = [];
284
+ for (const v of value) if (options.style === "simple" || options.style === "label") values.push(options.allowReserved === true ? v : encodeURIComponent(v));
285
+ else values.push(serializePrimitiveParam(name, v, options));
286
+ return options.style === "label" || options.style === "matrix" ? `${joiner}${values.join(joiner)}` : values.join(joiner);
287
+ }
288
+ function createQuerySerializer(options) {
289
+ return function querySerializer(queryParams) {
290
+ const search = [];
291
+ if (queryParams && typeof queryParams === "object") for (const name in queryParams) {
292
+ const value = queryParams[name];
293
+ if (value === void 0 || value === null) continue;
294
+ if (Array.isArray(value)) {
295
+ if (value.length === 0) continue;
296
+ search.push(serializeArrayParam(name, value, {
297
+ style: "form",
298
+ explode: true,
299
+ ...options?.array,
300
+ allowReserved: options?.allowReserved || false
301
+ }));
302
+ continue;
303
+ }
304
+ if (typeof value === "object") {
305
+ search.push(serializeObjectParam(name, value, {
306
+ style: "deepObject",
307
+ explode: true,
308
+ ...options?.object,
309
+ allowReserved: options?.allowReserved || false
310
+ }));
311
+ continue;
312
+ }
313
+ search.push(serializePrimitiveParam(name, value, options));
314
+ }
315
+ return search.join("&");
316
+ };
317
+ }
318
+ function defaultPathSerializer(pathname, pathParams) {
319
+ let nextURL = pathname;
320
+ for (const match of pathname.match(PATH_PARAM_RE) ?? []) {
321
+ let name = match.substring(1, match.length - 1);
322
+ let explode = false;
323
+ let style = "simple";
324
+ if (name.endsWith("*")) {
325
+ explode = true;
326
+ name = name.substring(0, name.length - 1);
327
+ }
328
+ if (name.startsWith(".")) {
329
+ style = "label";
330
+ name = name.substring(1);
331
+ } else if (name.startsWith(";")) {
332
+ style = "matrix";
333
+ name = name.substring(1);
334
+ }
335
+ if (!pathParams || pathParams[name] === void 0 || pathParams[name] === null) continue;
336
+ const value = pathParams[name];
337
+ if (Array.isArray(value)) {
338
+ nextURL = nextURL.replace(match, serializeArrayParam(name, value, {
339
+ style,
340
+ explode
341
+ }));
342
+ continue;
343
+ }
344
+ if (typeof value === "object") {
345
+ nextURL = nextURL.replace(match, serializeObjectParam(name, value, {
346
+ style,
347
+ explode
348
+ }));
349
+ continue;
350
+ }
351
+ if (style === "matrix") {
352
+ nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);
353
+ continue;
354
+ }
355
+ nextURL = nextURL.replace(match, style === "label" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));
356
+ }
357
+ return nextURL;
358
+ }
359
+ function defaultBodySerializer(body, headers) {
360
+ if (body instanceof FormData) return body;
361
+ if (headers) {
362
+ if ((headers.get instanceof Function ? headers.get("Content-Type") ?? headers.get("content-type") : headers["Content-Type"] ?? headers["content-type"]) === "application/x-www-form-urlencoded") return new URLSearchParams(body).toString();
363
+ }
364
+ return JSON.stringify(body);
365
+ }
366
+ function createFinalURL(pathname, options) {
367
+ let finalURL = `${options.baseUrl}${pathname}`;
368
+ if (options.params?.path) finalURL = options.pathSerializer(finalURL, options.params.path);
369
+ let search = options.querySerializer(options.params.query ?? {});
370
+ if (search.startsWith("?")) search = search.substring(1);
371
+ if (search) finalURL += `?${search}`;
372
+ return finalURL;
373
+ }
374
+ function mergeHeaders(...allHeaders) {
375
+ const finalHeaders = new Headers();
376
+ for (const h of allHeaders) {
377
+ if (!h || typeof h !== "object") continue;
378
+ const iterator = h instanceof Headers ? h.entries() : Object.entries(h);
379
+ for (const [k, v] of iterator) if (v === null) finalHeaders.delete(k);
380
+ else if (Array.isArray(v)) for (const v2 of v) finalHeaders.append(k, v2);
381
+ else if (v !== void 0) finalHeaders.set(k, v);
382
+ }
383
+ return finalHeaders;
384
+ }
385
+ function removeTrailingSlash(url) {
386
+ if (url.endsWith("/")) return url.substring(0, url.length - 1);
387
+ return url;
388
+ }
389
+
390
+ //#endregion
391
+ //#region node_modules/lossless-json/lib/esm/utils.js
392
+ /**
393
+ * Test whether a string contains an integer number
394
+ */
395
+ function isInteger(value) {
396
+ return INTEGER_REGEX.test(value);
397
+ }
398
+ const INTEGER_REGEX = /^-?[0-9]+$/;
399
+ /**
400
+ * Test whether a string contains a number
401
+ * http://stackoverflow.com/questions/13340717/json-numbers-regular-expression
402
+ */
403
+ function isNumber(value) {
404
+ return NUMBER_REGEX.test(value);
405
+ }
406
+ const NUMBER_REGEX = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
407
+ /**
408
+ * Test whether a string can be safely represented with a number
409
+ * without information loss.
410
+ *
411
+ * When approx is true, floating point numbers that lose a few digits but
412
+ * are still approximately equal in value are considered safe too.
413
+ * Integer numbers must still be exactly equal.
414
+ */
415
+ function isSafeNumber(value, config) {
416
+ if (isInteger(value)) return Number.isSafeInteger(Number.parseInt(value, 10));
417
+ const parsed = String(Number.parseFloat(value));
418
+ if (value === parsed) return true;
419
+ const valueDigits = extractSignificantDigits(value);
420
+ const parsedDigits = extractSignificantDigits(parsed);
421
+ if (valueDigits === parsedDigits) return true;
422
+ if (config?.approx === true) {
423
+ const requiredDigits = 14;
424
+ if (!isInteger(value) && parsedDigits.length >= requiredDigits && valueDigits.startsWith(parsedDigits.substring(0, requiredDigits))) return true;
425
+ }
426
+ return false;
427
+ }
428
+ let UnsafeNumberReason = /*#__PURE__*/ function(UnsafeNumberReason) {
429
+ UnsafeNumberReason["underflow"] = "underflow";
430
+ UnsafeNumberReason["overflow"] = "overflow";
431
+ UnsafeNumberReason["truncate_integer"] = "truncate_integer";
432
+ UnsafeNumberReason["truncate_float"] = "truncate_float";
433
+ return UnsafeNumberReason;
434
+ }({});
435
+ /**
436
+ * When the provided value is an unsafe number, describe what the reason is:
437
+ * overflow, underflow, truncate_integer, or truncate_float.
438
+ * Returns undefined when the value is safe.
439
+ */
440
+ function getUnsafeNumberReason(value) {
441
+ if (isSafeNumber(value, { approx: false })) return;
442
+ if (isInteger(value)) return UnsafeNumberReason.truncate_integer;
443
+ const num = Number.parseFloat(value);
444
+ if (!Number.isFinite(num)) return UnsafeNumberReason.overflow;
445
+ if (num === 0) return UnsafeNumberReason.underflow;
446
+ return UnsafeNumberReason.truncate_float;
447
+ }
448
+ /**
449
+ * Get the significant digits of a number.
450
+ *
451
+ * For example:
452
+ * '2.34' returns '234'
453
+ * '-77' returns '77'
454
+ * '0.003400' returns '34'
455
+ * '120.5e+30' returns '1205'
456
+ **/
457
+ function extractSignificantDigits(value) {
458
+ const { start, end } = getSignificantDigitRange(value);
459
+ const digits = value.substring(start, end);
460
+ const dot = digits.indexOf(".");
461
+ if (dot === -1) return digits;
462
+ return digits.substring(0, dot) + digits.substring(dot + 1);
463
+ }
464
+ /**
465
+ * Returns the range (start to end) of the significant digits of a value.
466
+ * Note that this range _may_ contain the decimal dot.
467
+ *
468
+ * For example:
469
+ *
470
+ * getSignificantDigitRange('0.0325900') // { start: 3, end: 7 }
471
+ * getSignificantDigitRange('2.0300') // { start: 0, end: 3 }
472
+ * getSignificantDigitRange('0.0') // { start: 3, end: 3 }
473
+ *
474
+ */
475
+ function getSignificantDigitRange(value) {
476
+ let start = 0;
477
+ if (value[0] === "-") start++;
478
+ while (value[start] === "0" || value[start] === ".") start++;
479
+ let end = value.lastIndexOf("e");
480
+ if (end === -1) end = value.lastIndexOf("E");
481
+ if (end === -1) end = value.length;
482
+ while ((value[end - 1] === "0" || value[end - 1] === ".") && end > start) end--;
483
+ return {
484
+ start,
485
+ end
486
+ };
487
+ }
488
+
489
+ //#endregion
490
+ //#region node_modules/lossless-json/lib/esm/LosslessNumber.js
491
+ /**
492
+ * A lossless number. Stores its numeric value as string
493
+ */
494
+ var LosslessNumber = class {
495
+ isLosslessNumber = true;
496
+ constructor(value) {
497
+ if (!isNumber(value)) throw new Error(`Invalid number (value: "${value}")`);
498
+ this.value = value;
499
+ }
500
+ /**
501
+ * Get the value of the LosslessNumber as number or bigint.
502
+ *
503
+ * - a number is returned for safe numbers and decimal values that only lose some insignificant digits
504
+ * - a bigint is returned for big integer numbers
505
+ * - an Error is thrown for values that will overflow or underflow
506
+ *
507
+ * Note that you can implement your own strategy for conversion by just getting the value as string
508
+ * via .toString(), and using util functions like isInteger, isSafeNumber, getUnsafeNumberReason,
509
+ * and toSafeNumberOrThrow to convert it to a numeric value.
510
+ */
511
+ valueOf() {
512
+ const unsafeReason = getUnsafeNumberReason(this.value);
513
+ if (unsafeReason === void 0 || unsafeReason === UnsafeNumberReason.truncate_float) return Number.parseFloat(this.value);
514
+ if (isInteger(this.value)) return BigInt(this.value);
515
+ throw new Error(`Cannot safely convert to number: the value '${this.value}' would ${unsafeReason} and become ${Number.parseFloat(this.value)}`);
516
+ }
517
+ /**
518
+ * Get the value of the LosslessNumber as string.
519
+ */
520
+ toString() {
521
+ return this.value;
522
+ }
523
+ };
524
+ /**
525
+ * Test whether a value is a LosslessNumber
526
+ */
527
+ function isLosslessNumber(value) {
528
+ return value && typeof value === "object" && value.isLosslessNumber || false;
529
+ }
530
+
531
+ //#endregion
532
+ //#region node_modules/lossless-json/lib/esm/numberParsers.js
533
+ function parseLosslessNumber(value) {
534
+ return new LosslessNumber(value);
535
+ }
536
+
537
+ //#endregion
538
+ //#region node_modules/lossless-json/lib/esm/revive.js
539
+ /**
540
+ * Revive a json object.
541
+ * Applies the reviver function recursively on all values in the JSON object.
542
+ * @param json A JSON Object, Array, or value
543
+ * @param reviver
544
+ * A reviver function invoked with arguments `key` and `value`,
545
+ * which must return a replacement value. The function context
546
+ * (`this`) is the Object or Array that contains the currently
547
+ * handled value.
548
+ */
549
+ function revive(json, reviver) {
550
+ return reviveValue({ "": json }, "", json, reviver);
551
+ }
552
+ /**
553
+ * Revive a value
554
+ */
555
+ function reviveValue(context, key, value, reviver) {
556
+ if (Array.isArray(value)) return reviver.call(context, key, reviveArray(value, reviver));
557
+ if (value && typeof value === "object" && !isLosslessNumber(value)) return reviver.call(context, key, reviveObject(value, reviver));
558
+ return reviver.call(context, key, value);
559
+ }
560
+ /**
561
+ * Revive the properties of an object
562
+ */
563
+ function reviveObject(object, reviver) {
564
+ for (const key of Object.keys(object)) {
565
+ const value = reviveValue(object, key, object[key], reviver);
566
+ if (value !== void 0) object[key] = value;
567
+ else delete object[key];
568
+ }
569
+ return object;
570
+ }
571
+ /**
572
+ * Revive the properties of an Array
573
+ */
574
+ function reviveArray(array, reviver) {
575
+ for (let i = 0; i < array.length; i++) array[i] = reviveValue(array, String(i), array[i], reviver);
576
+ return array;
577
+ }
578
+
579
+ //#endregion
580
+ //#region node_modules/lossless-json/lib/esm/parse.js
581
+ /**
582
+ * The LosslessJSON.parse() method parses a string as JSON, optionally transforming
583
+ * the value produced by parsing.
584
+ *
585
+ * The parser is based on the parser of Tan Li Hou shared in
586
+ * https://lihautan.com/json-parser-with-javascript/
587
+ *
588
+ * @param text
589
+ * The string to parse as JSON. See the JSON object for a description of JSON syntax.
590
+ *
591
+ * @param [reviver]
592
+ * If a function, prescribes how the value originally produced by parsing is
593
+ * transformed, before being returned.
594
+ *
595
+ * @param [options=ParseOptions | NumberParserArgument]
596
+ * Pass a custom number parser. Input is a string, and the output can be unknown
597
+ * numeric value: number, bigint, LosslessNumber, or a custom BigNumber library.
598
+ *
599
+ * @returns Returns the Object corresponding to the given JSON text.
600
+ *
601
+ * @throws Throws a SyntaxError exception if the string to parse is not valid JSON.
602
+ */
603
+ function parse(text, reviver, options) {
604
+ const optionsObj = typeof options === "function" ? { parseNumber: options } : options;
605
+ const parseNumber = optionsObj?.parseNumber ?? parseLosslessNumber;
606
+ const onDuplicateKey = optionsObj?.onDuplicateKey ?? throwDuplicateKey;
607
+ let i = 0;
608
+ const value = parseValue();
609
+ expectValue(value);
610
+ expectEndOfInput();
611
+ return reviver ? revive(value, reviver) : value;
612
+ function parseObject() {
613
+ if (text.charCodeAt(i) === codeOpeningBrace) {
614
+ i++;
615
+ skipWhitespace();
616
+ const object = {};
617
+ let initial = true;
618
+ while (i < text.length && text.charCodeAt(i) !== codeClosingBrace) {
619
+ if (!initial) {
620
+ eatComma();
621
+ skipWhitespace();
622
+ } else initial = false;
623
+ const start = i;
624
+ const key = parseString();
625
+ if (key === void 0) {
626
+ throwObjectKeyExpected();
627
+ return;
628
+ }
629
+ skipWhitespace();
630
+ eatColon();
631
+ const value = parseValue();
632
+ if (value === void 0) {
633
+ throwObjectValueExpected();
634
+ return;
635
+ }
636
+ if (Object.prototype.hasOwnProperty.call(object, key) && !isDeepEqual(value, object[key])) {
637
+ const returnedValue = onDuplicateKey({
638
+ key,
639
+ position: start + 1,
640
+ oldValue: object[key],
641
+ newValue: value
642
+ });
643
+ if (returnedValue !== void 0) object[key] = returnedValue;
644
+ } else object[key] = value;
645
+ }
646
+ if (text.charCodeAt(i) !== codeClosingBrace) throwObjectKeyOrEndExpected();
647
+ i++;
648
+ return object;
649
+ }
650
+ }
651
+ function parseArray() {
652
+ if (text.charCodeAt(i) === codeOpeningBracket) {
653
+ i++;
654
+ skipWhitespace();
655
+ const array = [];
656
+ let initial = true;
657
+ while (i < text.length && text.charCodeAt(i) !== codeClosingBracket) {
658
+ if (!initial) eatComma();
659
+ else initial = false;
660
+ const value = parseValue();
661
+ expectArrayItem(value);
662
+ array.push(value);
663
+ }
664
+ if (text.charCodeAt(i) !== codeClosingBracket) throwArrayItemOrEndExpected();
665
+ i++;
666
+ return array;
667
+ }
668
+ }
669
+ function parseValue() {
670
+ skipWhitespace();
671
+ const value = parseString() ?? parseNumeric() ?? parseObject() ?? parseArray() ?? parseKeyword("true", true) ?? parseKeyword("false", false) ?? parseKeyword("null", null);
672
+ skipWhitespace();
673
+ return value;
674
+ }
675
+ function parseKeyword(name, value) {
676
+ if (text.slice(i, i + name.length) === name) {
677
+ i += name.length;
678
+ return value;
679
+ }
680
+ }
681
+ function skipWhitespace() {
682
+ while (isWhitespace(text.charCodeAt(i))) i++;
683
+ }
684
+ function parseString() {
685
+ if (text.charCodeAt(i) === codeDoubleQuote) {
686
+ i++;
687
+ let result = "";
688
+ while (i < text.length && text.charCodeAt(i) !== codeDoubleQuote) {
689
+ if (text.charCodeAt(i) === codeBackslash) {
690
+ const char = text[i + 1];
691
+ const escapeChar = escapeCharacters[char];
692
+ if (escapeChar !== void 0) {
693
+ result += escapeChar;
694
+ i++;
695
+ } else if (char === "u") {
696
+ if (isHex(text.charCodeAt(i + 2)) && isHex(text.charCodeAt(i + 3)) && isHex(text.charCodeAt(i + 4)) && isHex(text.charCodeAt(i + 5))) {
697
+ result += String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16));
698
+ i += 5;
699
+ } else throwInvalidUnicodeCharacter(i);
700
+ } else throwInvalidEscapeCharacter(i);
701
+ } else if (isValidStringCharacter(text.charCodeAt(i))) result += text[i];
702
+ else throwInvalidCharacter(text[i]);
703
+ i++;
704
+ }
705
+ expectEndOfString();
706
+ i++;
707
+ return result;
708
+ }
709
+ }
710
+ function parseNumeric() {
711
+ const start = i;
712
+ if (text.charCodeAt(i) === codeMinus) {
713
+ i++;
714
+ expectDigit(start);
715
+ }
716
+ if (text.charCodeAt(i) === codeZero) i++;
717
+ else if (isNonZeroDigit(text.charCodeAt(i))) {
718
+ i++;
719
+ while (isDigit(text.charCodeAt(i))) i++;
720
+ }
721
+ if (text.charCodeAt(i) === codeDot) {
722
+ i++;
723
+ expectDigit(start);
724
+ while (isDigit(text.charCodeAt(i))) i++;
725
+ }
726
+ if (text.charCodeAt(i) === 101 || text.charCodeAt(i) === 69) {
727
+ i++;
728
+ if (text.charCodeAt(i) === codeMinus || text.charCodeAt(i) === codePlus) i++;
729
+ expectDigit(start);
730
+ while (isDigit(text.charCodeAt(i))) i++;
731
+ }
732
+ if (i > start) return parseNumber(text.slice(start, i));
733
+ }
734
+ function eatComma() {
735
+ if (text.charCodeAt(i) !== codeComma) throw new SyntaxError(`Comma ',' expected after value ${gotAt()}`);
736
+ i++;
737
+ }
738
+ function eatColon() {
739
+ if (text.charCodeAt(i) !== codeColon) throw new SyntaxError(`Colon ':' expected after property name ${gotAt()}`);
740
+ i++;
741
+ }
742
+ function expectValue(value) {
743
+ if (value === void 0) throw new SyntaxError(`JSON value expected ${gotAt()}`);
744
+ }
745
+ function expectArrayItem(value) {
746
+ if (value === void 0) throw new SyntaxError(`Array item expected ${gotAt()}`);
747
+ }
748
+ function expectEndOfInput() {
749
+ if (i < text.length) throw new SyntaxError(`Expected end of input ${gotAt()}`);
750
+ }
751
+ function expectDigit(start) {
752
+ if (!isDigit(text.charCodeAt(i))) {
753
+ const numSoFar = text.slice(start, i);
754
+ throw new SyntaxError(`Invalid number '${numSoFar}', expecting a digit ${gotAt()}`);
755
+ }
756
+ }
757
+ function expectEndOfString() {
758
+ if (text.charCodeAt(i) !== codeDoubleQuote) throw new SyntaxError(`End of string '"' expected ${gotAt()}`);
759
+ }
760
+ function throwObjectKeyExpected() {
761
+ throw new SyntaxError(`Quoted object key expected ${gotAt()}`);
762
+ }
763
+ function throwDuplicateKey(_ref) {
764
+ let { key, position } = _ref;
765
+ throw new SyntaxError(`Duplicate key '${key}' encountered at position ${position}`);
766
+ }
767
+ function throwObjectKeyOrEndExpected() {
768
+ throw new SyntaxError(`Quoted object key or end of object '}' expected ${gotAt()}`);
769
+ }
770
+ function throwArrayItemOrEndExpected() {
771
+ throw new SyntaxError(`Array item or end of array ']' expected ${gotAt()}`);
772
+ }
773
+ function throwInvalidCharacter(char) {
774
+ throw new SyntaxError(`Invalid character '${char}' ${pos()}`);
775
+ }
776
+ function throwInvalidEscapeCharacter(start) {
777
+ const chars = text.slice(start, start + 2);
778
+ throw new SyntaxError(`Invalid escape character '${chars}' ${pos()}`);
779
+ }
780
+ function throwObjectValueExpected() {
781
+ throw new SyntaxError(`Object value expected after ':' ${pos()}`);
782
+ }
783
+ function throwInvalidUnicodeCharacter(start) {
784
+ const chars = text.slice(start, start + 6);
785
+ throw new SyntaxError(`Invalid unicode character '${chars}' ${pos()}`);
786
+ }
787
+ function pos() {
788
+ return `at position ${i}`;
789
+ }
790
+ function got() {
791
+ return i < text.length ? `but got '${text[i]}'` : "but reached end of input";
792
+ }
793
+ function gotAt() {
794
+ return `${got()} ${pos()}`;
795
+ }
796
+ }
797
+ function isWhitespace(code) {
798
+ return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn;
799
+ }
800
+ function isHex(code) {
801
+ return code >= codeZero && code <= codeNine || code >= 65 && code <= 70 || code >= 97 && code <= 102;
802
+ }
803
+ function isDigit(code) {
804
+ return code >= codeZero && code <= codeNine;
805
+ }
806
+ function isNonZeroDigit(code) {
807
+ return code >= codeOne && code <= codeNine;
808
+ }
809
+ function isValidStringCharacter(code) {
810
+ return code >= 32 && code <= 1114111;
811
+ }
812
+ function isDeepEqual(a, b) {
813
+ if (a === b) return true;
814
+ if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((item, index) => isDeepEqual(item, b[index]));
815
+ if (isObject$1(a) && isObject$1(b)) return [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].every((key) => isDeepEqual(a[key], b[key]));
816
+ return false;
817
+ }
818
+ function isObject$1(value) {
819
+ return typeof value === "object" && value !== null;
820
+ }
821
+ const escapeCharacters = {
822
+ "\"": "\"",
823
+ "\\": "\\",
824
+ "/": "/",
825
+ b: "\b",
826
+ f: "\f",
827
+ n: "\n",
828
+ r: "\r",
829
+ t: " "
830
+ };
831
+ const codeBackslash = 92;
832
+ const codeOpeningBrace = 123;
833
+ const codeClosingBrace = 125;
834
+ const codeOpeningBracket = 91;
835
+ const codeClosingBracket = 93;
836
+ const codeSpace = 32;
837
+ const codeNewline = 10;
838
+ const codeTab = 9;
839
+ const codeReturn = 13;
840
+ const codeDoubleQuote = 34;
841
+ const codePlus = 43;
842
+ const codeMinus = 45;
843
+ const codeZero = 48;
844
+ const codeOne = 49;
845
+ const codeNine = 57;
846
+ const codeComma = 44;
847
+ const codeDot = 46;
848
+ const codeColon = 58;
849
+ const codeUppercaseA = 65;
850
+ const codeLowercaseA = 97;
851
+ const codeUppercaseE = 69;
852
+ const codeLowercaseE = 101;
853
+ const codeUppercaseF = 70;
854
+ const codeLowercaseF = 102;
855
+
856
+ //#endregion
857
+ //#region src/analytics.ts
858
+ /** Decode feed IDs before a native JSON parser can round their UInt64 values. */
859
+ function parseFeedResponse(raw) {
860
+ const page = parse(raw, void 0, { onDuplicateKey: ({ newValue }) => newValue });
861
+ if (!isObject(page) || !Array.isArray(page.results)) throw new TypeError("Expected a feed response with a results array.");
862
+ for (const record of page.results) {
863
+ if (!isObject(record)) throw new TypeError("Expected a feed record.");
864
+ const id = isLosslessNumber(record.id) ? record.id.value : record.id;
865
+ if (typeof id !== "string" || !/^(0|[1-9]\d*)$/u.test(id) || id.length > 20 || id.length === 20 && id > "18446744073709551615") throw new TypeError("Expected a decimal UInt64 feed ID.");
866
+ record.id = id;
867
+ }
868
+ return nativeValues(page);
869
+ }
870
+ function isObject(value) {
871
+ return value !== null && typeof value === "object" && !Array.isArray(value);
872
+ }
873
+ function nativeValues(value) {
874
+ if (isLosslessNumber(value)) return Number(value.value);
875
+ if (Array.isArray(value)) return value.map(nativeValues);
876
+ if (isObject(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, nativeValues(item)]));
877
+ return value;
878
+ }
2
879
 
880
+ //#endregion
3
881
  //#region src/errors.ts
4
882
  const encoder$1 = new TextEncoder();
5
883
  var ProxyRequestError = class extends Error {
@@ -895,11 +1773,11 @@ var LocationsResource = class {
895
1773
  this.#client = client;
896
1774
  }
897
1775
  /** List available autonomous systems */
898
- async listAsns(options = {}) {
1776
+ async listAsns(options) {
899
1777
  return (await this.listAsnsWithResponse(options)).data;
900
1778
  }
901
1779
  /** List available autonomous systems; include response metadata. */
902
- async listAsnsWithResponse(options = {}) {
1780
+ async listAsnsWithResponse(options) {
903
1781
  return this.#client._callWithResponse({
904
1782
  operationId: "locations_asn_list",
905
1783
  method: "GET",
@@ -921,11 +1799,11 @@ var LocationsResource = class {
921
1799
  });
922
1800
  }
923
1801
  /** List available cities */
924
- async listCities(options = {}) {
1802
+ async listCities(options) {
925
1803
  return (await this.listCitiesWithResponse(options)).data;
926
1804
  }
927
1805
  /** List available cities; include response metadata. */
928
- async listCitiesWithResponse(options = {}) {
1806
+ async listCitiesWithResponse(options) {
929
1807
  return this.#client._callWithResponse({
930
1808
  operationId: "locations_cities_list",
931
1809
  method: "GET",
@@ -958,16 +1836,17 @@ var LocationsResource = class {
958
1836
  path: "/locations/cities/{id}"
959
1837
  }, {
960
1838
  path: { id: options.id },
1839
+ query: { package_id: options.packageId },
961
1840
  headers: { "Accept-Language": options.acceptLanguage },
962
1841
  ...options.request === void 0 ? {} : { request: options.request }
963
1842
  });
964
1843
  }
965
1844
  /** List available continents */
966
- async listContinents(options = {}) {
1845
+ async listContinents(options) {
967
1846
  return (await this.listContinentsWithResponse(options)).data;
968
1847
  }
969
1848
  /** List available continents; include response metadata. */
970
- async listContinentsWithResponse(options = {}) {
1849
+ async listContinentsWithResponse(options) {
971
1850
  return this.#client._callWithResponse({
972
1851
  operationId: "locations_continents_list",
973
1852
  method: "GET",
@@ -998,16 +1877,17 @@ var LocationsResource = class {
998
1877
  path: "/locations/continents/{id}"
999
1878
  }, {
1000
1879
  path: { id: options.id },
1880
+ query: { package_id: options.packageId },
1001
1881
  headers: { "Accept-Language": options.acceptLanguage },
1002
1882
  ...options.request === void 0 ? {} : { request: options.request }
1003
1883
  });
1004
1884
  }
1005
1885
  /** List available countries */
1006
- async listCountries(options = {}) {
1886
+ async listCountries(options) {
1007
1887
  return (await this.listCountriesWithResponse(options)).data;
1008
1888
  }
1009
1889
  /** List available countries; include response metadata. */
1010
- async listCountriesWithResponse(options = {}) {
1890
+ async listCountriesWithResponse(options) {
1011
1891
  return this.#client._callWithResponse({
1012
1892
  operationId: "locations_countries_list",
1013
1893
  method: "GET",
@@ -1038,16 +1918,17 @@ var LocationsResource = class {
1038
1918
  path: "/locations/countries/{id}"
1039
1919
  }, {
1040
1920
  path: { id: options.id },
1921
+ query: { package_id: options.packageId },
1041
1922
  headers: { "Accept-Language": options.acceptLanguage },
1042
1923
  ...options.request === void 0 ? {} : { request: options.request }
1043
1924
  });
1044
1925
  }
1045
1926
  /** List available internet service providers */
1046
- async listIsps(options = {}) {
1927
+ async listIsps(options) {
1047
1928
  return (await this.listIspsWithResponse(options)).data;
1048
1929
  }
1049
1930
  /** List available internet service providers; include response metadata. */
1050
- async listIspsWithResponse(options = {}) {
1931
+ async listIspsWithResponse(options) {
1051
1932
  return this.#client._callWithResponse({
1052
1933
  operationId: "locations_isps_list",
1053
1934
  method: "GET",
@@ -1068,11 +1949,11 @@ var LocationsResource = class {
1068
1949
  });
1069
1950
  }
1070
1951
  /** List available regions */
1071
- async listRegions(options = {}) {
1952
+ async listRegions(options) {
1072
1953
  return (await this.listRegionsWithResponse(options)).data;
1073
1954
  }
1074
1955
  /** List available regions; include response metadata. */
1075
- async listRegionsWithResponse(options = {}) {
1956
+ async listRegionsWithResponse(options) {
1076
1957
  return this.#client._callWithResponse({
1077
1958
  operationId: "locations_regions_list",
1078
1959
  method: "GET",
@@ -1104,6 +1985,7 @@ var LocationsResource = class {
1104
1985
  path: "/locations/regions/{id}"
1105
1986
  }, {
1106
1987
  path: { id: options.id },
1988
+ query: { package_id: options.packageId },
1107
1989
  headers: { "Accept-Language": options.acceptLanguage },
1108
1990
  ...options.request === void 0 ? {} : { request: options.request }
1109
1991
  });
@@ -1616,11 +2498,11 @@ var UsersResource = class {
1616
2498
  ...options.request === void 0 ? {} : { request: options.request }
1617
2499
  });
1618
2500
  }
1619
- /** Create a sub-user */
2501
+ /** Create a customer account */
1620
2502
  async create(options) {
1621
2503
  return (await this.createWithResponse(options)).data;
1622
2504
  }
1623
- /** Create a sub-user; include response metadata. */
2505
+ /** Create a customer account; include response metadata. */
1624
2506
  async createWithResponse(options) {
1625
2507
  return this.#client._callWithResponse({
1626
2508
  operationId: "users_create",
@@ -1735,6 +2617,27 @@ var UsersResource = class {
1735
2617
  ...options.request === void 0 ? {} : { request: options.request }
1736
2618
  });
1737
2619
  }
2620
+ /** Reset a user's remaining data */
2621
+ async resetData(options) {
2622
+ return (await this.resetDataWithResponse(options)).data;
2623
+ }
2624
+ /** Reset a user's remaining data; include response metadata. */
2625
+ async resetDataWithResponse(options) {
2626
+ return this.#client._callWithResponse({
2627
+ operationId: "users_data_reset_create",
2628
+ method: "POST",
2629
+ path: "/users/{id}/data/reset",
2630
+ idempotent: true
2631
+ }, {
2632
+ path: { id: options.id },
2633
+ headers: {
2634
+ "Idempotency-Key": options.idempotencyKey,
2635
+ "Accept-Language": options.acceptLanguage
2636
+ },
2637
+ body: options.body,
2638
+ ...options.request === void 0 ? {} : { request: options.request }
2639
+ });
2640
+ }
1738
2641
  /** List a sub-user's orders */
1739
2642
  async listOrders(options) {
1740
2643
  return (await this.listOrdersWithResponse(options)).data;
@@ -1772,7 +2675,7 @@ var UsersResource = class {
1772
2675
  }, {
1773
2676
  path: { id: options.id },
1774
2677
  headers: { "Accept-Language": options.acceptLanguage },
1775
- ...options.body === void 0 ? {} : { body: options.body },
2678
+ body: options.body,
1776
2679
  ...options.request === void 0 ? {} : { request: options.request }
1777
2680
  });
1778
2681
  }
@@ -1919,7 +2822,7 @@ function offsetFromUrl(url) {
1919
2822
  //#endregion
1920
2823
  //#region src/client.ts
1921
2824
  const DEFAULT_BASE_URL = "https://api.proxyrequest.com/api/v1";
1922
- const SDK_VERSION = "1.0.0";
2825
+ const SDK_VERSION = "3.0.1";
1923
2826
  var ProxyRequestClient = class ProxyRequestClient {
1924
2827
  apiKeys;
1925
2828
  affiliates;
@@ -2031,10 +2934,10 @@ var ProxyRequestClient = class ProxyRequestClient {
2031
2934
  ...data.body === void 0 ? {} : { body: data.body },
2032
2935
  ...[...controlHeaders].length === 0 ? {} : { headers: controlHeaders },
2033
2936
  signal: timeout.signal,
2034
- ...spec.binary ? { parseAs: "arrayBuffer" } : {}
2937
+ ...spec.binary ? { parseAs: "arrayBuffer" } : spec.operationId === "analytics_feed_retrieve" ? { parseAs: "text" } : {}
2035
2938
  });
2036
2939
  if (result.error !== void 0) throw ApiError.unexpected(`ProxyRequest returned an undocumented error for ${spec.operationId}.`, result.error);
2037
- const dataValue = spec.binary ? binaryResult(spec, result.data, result.response.headers) : result.data;
2940
+ const dataValue = spec.binary ? binaryResult(spec, result.data, result.response.headers) : spec.operationId === "analytics_feed_retrieve" ? parseFeedResponse(result.data) : result.data;
2038
2941
  const headers = headersToRecord(result.response.headers);
2039
2942
  const etag = headers.etag;
2040
2943
  return {