unplugin-dingtalk 0.2.0 → 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.
@@ -0,0 +1,1499 @@
1
+ import {
2
+ FormData,
3
+ __forAwait,
4
+ __spreadProps,
5
+ __spreadValues,
6
+ fetch_blob_default,
7
+ formDataToBlob
8
+ } from "./chunk-PMOTCIQR.js";
9
+
10
+ // src/index.ts
11
+ import { exec } from "child_process";
12
+ import process2 from "process";
13
+
14
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js
15
+ import http2 from "http";
16
+ import https from "https";
17
+ import zlib from "zlib";
18
+ import Stream2, { PassThrough as PassThrough2, pipeline as pump } from "stream";
19
+ import { Buffer as Buffer3 } from "buffer";
20
+
21
+ // node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/dist/index.js
22
+ function dataUriToBuffer(uri) {
23
+ if (!/^data:/i.test(uri)) {
24
+ throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
25
+ }
26
+ uri = uri.replace(/\r?\n/g, "");
27
+ const firstComma = uri.indexOf(",");
28
+ if (firstComma === -1 || firstComma <= 4) {
29
+ throw new TypeError("malformed data: URI");
30
+ }
31
+ const meta = uri.substring(5, firstComma).split(";");
32
+ let charset = "";
33
+ let base64 = false;
34
+ const type = meta[0] || "text/plain";
35
+ let typeFull = type;
36
+ for (let i = 1; i < meta.length; i++) {
37
+ if (meta[i] === "base64") {
38
+ base64 = true;
39
+ } else if (meta[i]) {
40
+ typeFull += `;${meta[i]}`;
41
+ if (meta[i].indexOf("charset=") === 0) {
42
+ charset = meta[i].substring(8);
43
+ }
44
+ }
45
+ }
46
+ if (!meta[0] && !charset.length) {
47
+ typeFull += ";charset=US-ASCII";
48
+ charset = "US-ASCII";
49
+ }
50
+ const encoding = base64 ? "base64" : "ascii";
51
+ const data = unescape(uri.substring(firstComma + 1));
52
+ const buffer = Buffer.from(data, encoding);
53
+ buffer.type = type;
54
+ buffer.typeFull = typeFull;
55
+ buffer.charset = charset;
56
+ return buffer;
57
+ }
58
+ var dist_default = dataUriToBuffer;
59
+
60
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js
61
+ import Stream, { PassThrough } from "stream";
62
+ import { types, deprecate, promisify } from "util";
63
+ import { Buffer as Buffer2 } from "buffer";
64
+
65
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js
66
+ var FetchBaseError = class extends Error {
67
+ constructor(message, type) {
68
+ super(message);
69
+ Error.captureStackTrace(this, this.constructor);
70
+ this.type = type;
71
+ }
72
+ get name() {
73
+ return this.constructor.name;
74
+ }
75
+ get [Symbol.toStringTag]() {
76
+ return this.constructor.name;
77
+ }
78
+ };
79
+
80
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js
81
+ var FetchError = class extends FetchBaseError {
82
+ /**
83
+ * @param {string} message - Error message for human
84
+ * @param {string} [type] - Error type for machine
85
+ * @param {SystemError} [systemError] - For Node.js system error
86
+ */
87
+ constructor(message, type, systemError) {
88
+ super(message, type);
89
+ if (systemError) {
90
+ this.code = this.errno = systemError.code;
91
+ this.erroredSysCall = systemError.syscall;
92
+ }
93
+ }
94
+ };
95
+
96
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js
97
+ var NAME = Symbol.toStringTag;
98
+ var isURLSearchParameters = (object) => {
99
+ return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams";
100
+ };
101
+ var isBlob = (object) => {
102
+ return object && typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]);
103
+ };
104
+ var isAbortSignal = (object) => {
105
+ return typeof object === "object" && (object[NAME] === "AbortSignal" || object[NAME] === "EventTarget");
106
+ };
107
+ var isDomainOrSubdomain = (destination, original) => {
108
+ const orig = new URL(original).hostname;
109
+ const dest = new URL(destination).hostname;
110
+ return orig === dest || orig.endsWith(`.${dest}`);
111
+ };
112
+ var isSameProtocol = (destination, original) => {
113
+ const orig = new URL(original).protocol;
114
+ const dest = new URL(destination).protocol;
115
+ return orig === dest;
116
+ };
117
+
118
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js
119
+ var pipeline = promisify(Stream.pipeline);
120
+ var INTERNALS = Symbol("Body internals");
121
+ var Body = class {
122
+ constructor(body, {
123
+ size = 0
124
+ } = {}) {
125
+ let boundary = null;
126
+ if (body === null) {
127
+ body = null;
128
+ } else if (isURLSearchParameters(body)) {
129
+ body = Buffer2.from(body.toString());
130
+ } else if (isBlob(body)) {
131
+ } else if (Buffer2.isBuffer(body)) {
132
+ } else if (types.isAnyArrayBuffer(body)) {
133
+ body = Buffer2.from(body);
134
+ } else if (ArrayBuffer.isView(body)) {
135
+ body = Buffer2.from(body.buffer, body.byteOffset, body.byteLength);
136
+ } else if (body instanceof Stream) {
137
+ } else if (body instanceof FormData) {
138
+ body = formDataToBlob(body);
139
+ boundary = body.type.split("=")[1];
140
+ } else {
141
+ body = Buffer2.from(String(body));
142
+ }
143
+ let stream = body;
144
+ if (Buffer2.isBuffer(body)) {
145
+ stream = Stream.Readable.from(body);
146
+ } else if (isBlob(body)) {
147
+ stream = Stream.Readable.from(body.stream());
148
+ }
149
+ this[INTERNALS] = {
150
+ body,
151
+ stream,
152
+ boundary,
153
+ disturbed: false,
154
+ error: null
155
+ };
156
+ this.size = size;
157
+ if (body instanceof Stream) {
158
+ body.on("error", (error_) => {
159
+ const error = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_);
160
+ this[INTERNALS].error = error;
161
+ });
162
+ }
163
+ }
164
+ get body() {
165
+ return this[INTERNALS].stream;
166
+ }
167
+ get bodyUsed() {
168
+ return this[INTERNALS].disturbed;
169
+ }
170
+ /**
171
+ * Decode response as ArrayBuffer
172
+ *
173
+ * @return Promise
174
+ */
175
+ async arrayBuffer() {
176
+ const { buffer, byteOffset, byteLength } = await consumeBody(this);
177
+ return buffer.slice(byteOffset, byteOffset + byteLength);
178
+ }
179
+ async formData() {
180
+ const ct = this.headers.get("content-type");
181
+ if (ct.startsWith("application/x-www-form-urlencoded")) {
182
+ const formData = new FormData();
183
+ const parameters = new URLSearchParams(await this.text());
184
+ for (const [name, value] of parameters) {
185
+ formData.append(name, value);
186
+ }
187
+ return formData;
188
+ }
189
+ const { toFormData } = await import("./multipart-parser-HI4LNJC5.js");
190
+ return toFormData(this.body, ct);
191
+ }
192
+ /**
193
+ * Return raw response as Blob
194
+ *
195
+ * @return Promise
196
+ */
197
+ async blob() {
198
+ const ct = this.headers && this.headers.get("content-type") || this[INTERNALS].body && this[INTERNALS].body.type || "";
199
+ const buf = await this.arrayBuffer();
200
+ return new fetch_blob_default([buf], {
201
+ type: ct
202
+ });
203
+ }
204
+ /**
205
+ * Decode response as json
206
+ *
207
+ * @return Promise
208
+ */
209
+ async json() {
210
+ const text = await this.text();
211
+ return JSON.parse(text);
212
+ }
213
+ /**
214
+ * Decode response as text
215
+ *
216
+ * @return Promise
217
+ */
218
+ async text() {
219
+ const buffer = await consumeBody(this);
220
+ return new TextDecoder().decode(buffer);
221
+ }
222
+ /**
223
+ * Decode response as buffer (non-spec api)
224
+ *
225
+ * @return Promise
226
+ */
227
+ buffer() {
228
+ return consumeBody(this);
229
+ }
230
+ };
231
+ Body.prototype.buffer = deprecate(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer");
232
+ Object.defineProperties(Body.prototype, {
233
+ body: { enumerable: true },
234
+ bodyUsed: { enumerable: true },
235
+ arrayBuffer: { enumerable: true },
236
+ blob: { enumerable: true },
237
+ json: { enumerable: true },
238
+ text: { enumerable: true },
239
+ data: { get: deprecate(
240
+ () => {
241
+ },
242
+ "data doesn't exist, use json(), text(), arrayBuffer(), or body instead",
243
+ "https://github.com/node-fetch/node-fetch/issues/1000 (response)"
244
+ ) }
245
+ });
246
+ async function consumeBody(data) {
247
+ if (data[INTERNALS].disturbed) {
248
+ throw new TypeError(`body used already for: ${data.url}`);
249
+ }
250
+ data[INTERNALS].disturbed = true;
251
+ if (data[INTERNALS].error) {
252
+ throw data[INTERNALS].error;
253
+ }
254
+ const { body } = data;
255
+ if (body === null) {
256
+ return Buffer2.alloc(0);
257
+ }
258
+ if (!(body instanceof Stream)) {
259
+ return Buffer2.alloc(0);
260
+ }
261
+ const accum = [];
262
+ let accumBytes = 0;
263
+ try {
264
+ try {
265
+ for (var iter = __forAwait(body), more, temp, error; more = !(temp = await iter.next()).done; more = false) {
266
+ const chunk = temp.value;
267
+ if (data.size > 0 && accumBytes + chunk.length > data.size) {
268
+ const error2 = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size");
269
+ body.destroy(error2);
270
+ throw error2;
271
+ }
272
+ accumBytes += chunk.length;
273
+ accum.push(chunk);
274
+ }
275
+ } catch (temp) {
276
+ error = [temp];
277
+ } finally {
278
+ try {
279
+ more && (temp = iter.return) && await temp.call(iter);
280
+ } finally {
281
+ if (error)
282
+ throw error[0];
283
+ }
284
+ }
285
+ } catch (error2) {
286
+ const error_ = error2 instanceof FetchBaseError ? error2 : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error2.message}`, "system", error2);
287
+ throw error_;
288
+ }
289
+ if (body.readableEnded === true || body._readableState.ended === true) {
290
+ try {
291
+ if (accum.every((c2) => typeof c2 === "string")) {
292
+ return Buffer2.from(accum.join(""));
293
+ }
294
+ return Buffer2.concat(accum, accumBytes);
295
+ } catch (error2) {
296
+ throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error2.message}`, "system", error2);
297
+ }
298
+ } else {
299
+ throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`);
300
+ }
301
+ }
302
+ var clone = (instance, highWaterMark) => {
303
+ let p1;
304
+ let p2;
305
+ let { body } = instance[INTERNALS];
306
+ if (instance.bodyUsed) {
307
+ throw new Error("cannot clone body after it is used");
308
+ }
309
+ if (body instanceof Stream && typeof body.getBoundary !== "function") {
310
+ p1 = new PassThrough({ highWaterMark });
311
+ p2 = new PassThrough({ highWaterMark });
312
+ body.pipe(p1);
313
+ body.pipe(p2);
314
+ instance[INTERNALS].stream = p1;
315
+ body = p2;
316
+ }
317
+ return body;
318
+ };
319
+ var getNonSpecFormDataBoundary = deprecate(
320
+ (body) => body.getBoundary(),
321
+ "form-data doesn't follow the spec and requires special treatment. Use alternative package",
322
+ "https://github.com/node-fetch/node-fetch/issues/1167"
323
+ );
324
+ var extractContentType = (body, request) => {
325
+ if (body === null) {
326
+ return null;
327
+ }
328
+ if (typeof body === "string") {
329
+ return "text/plain;charset=UTF-8";
330
+ }
331
+ if (isURLSearchParameters(body)) {
332
+ return "application/x-www-form-urlencoded;charset=UTF-8";
333
+ }
334
+ if (isBlob(body)) {
335
+ return body.type || null;
336
+ }
337
+ if (Buffer2.isBuffer(body) || types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {
338
+ return null;
339
+ }
340
+ if (body instanceof FormData) {
341
+ return `multipart/form-data; boundary=${request[INTERNALS].boundary}`;
342
+ }
343
+ if (body && typeof body.getBoundary === "function") {
344
+ return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`;
345
+ }
346
+ if (body instanceof Stream) {
347
+ return null;
348
+ }
349
+ return "text/plain;charset=UTF-8";
350
+ };
351
+ var getTotalBytes = (request) => {
352
+ const { body } = request[INTERNALS];
353
+ if (body === null) {
354
+ return 0;
355
+ }
356
+ if (isBlob(body)) {
357
+ return body.size;
358
+ }
359
+ if (Buffer2.isBuffer(body)) {
360
+ return body.length;
361
+ }
362
+ if (body && typeof body.getLengthSync === "function") {
363
+ return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;
364
+ }
365
+ return null;
366
+ };
367
+ var writeToStream = async (dest, { body }) => {
368
+ if (body === null) {
369
+ dest.end();
370
+ } else {
371
+ await pipeline(body, dest);
372
+ }
373
+ };
374
+
375
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js
376
+ import { types as types2 } from "util";
377
+ import http from "http";
378
+ var validateHeaderName = typeof http.validateHeaderName === "function" ? http.validateHeaderName : (name) => {
379
+ if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) {
380
+ const error = new TypeError(`Header name must be a valid HTTP token [${name}]`);
381
+ Object.defineProperty(error, "code", { value: "ERR_INVALID_HTTP_TOKEN" });
382
+ throw error;
383
+ }
384
+ };
385
+ var validateHeaderValue = typeof http.validateHeaderValue === "function" ? http.validateHeaderValue : (name, value) => {
386
+ if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) {
387
+ const error = new TypeError(`Invalid character in header content ["${name}"]`);
388
+ Object.defineProperty(error, "code", { value: "ERR_INVALID_CHAR" });
389
+ throw error;
390
+ }
391
+ };
392
+ var Headers = class _Headers extends URLSearchParams {
393
+ /**
394
+ * Headers class
395
+ *
396
+ * @constructor
397
+ * @param {HeadersInit} [init] - Response headers
398
+ */
399
+ constructor(init) {
400
+ let result = [];
401
+ if (init instanceof _Headers) {
402
+ const raw = init.raw();
403
+ for (const [name, values] of Object.entries(raw)) {
404
+ result.push(...values.map((value) => [name, value]));
405
+ }
406
+ } else if (init == null) {
407
+ } else if (typeof init === "object" && !types2.isBoxedPrimitive(init)) {
408
+ const method = init[Symbol.iterator];
409
+ if (method == null) {
410
+ result.push(...Object.entries(init));
411
+ } else {
412
+ if (typeof method !== "function") {
413
+ throw new TypeError("Header pairs must be iterable");
414
+ }
415
+ result = [...init].map((pair) => {
416
+ if (typeof pair !== "object" || types2.isBoxedPrimitive(pair)) {
417
+ throw new TypeError("Each header pair must be an iterable object");
418
+ }
419
+ return [...pair];
420
+ }).map((pair) => {
421
+ if (pair.length !== 2) {
422
+ throw new TypeError("Each header pair must be a name/value tuple");
423
+ }
424
+ return [...pair];
425
+ });
426
+ }
427
+ } else {
428
+ throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");
429
+ }
430
+ result = result.length > 0 ? result.map(([name, value]) => {
431
+ validateHeaderName(name);
432
+ validateHeaderValue(name, String(value));
433
+ return [String(name).toLowerCase(), String(value)];
434
+ }) : void 0;
435
+ super(result);
436
+ return new Proxy(this, {
437
+ get(target, p, receiver) {
438
+ switch (p) {
439
+ case "append":
440
+ case "set":
441
+ return (name, value) => {
442
+ validateHeaderName(name);
443
+ validateHeaderValue(name, String(value));
444
+ return URLSearchParams.prototype[p].call(
445
+ target,
446
+ String(name).toLowerCase(),
447
+ String(value)
448
+ );
449
+ };
450
+ case "delete":
451
+ case "has":
452
+ case "getAll":
453
+ return (name) => {
454
+ validateHeaderName(name);
455
+ return URLSearchParams.prototype[p].call(
456
+ target,
457
+ String(name).toLowerCase()
458
+ );
459
+ };
460
+ case "keys":
461
+ return () => {
462
+ target.sort();
463
+ return new Set(URLSearchParams.prototype.keys.call(target)).keys();
464
+ };
465
+ default:
466
+ return Reflect.get(target, p, receiver);
467
+ }
468
+ }
469
+ });
470
+ }
471
+ get [Symbol.toStringTag]() {
472
+ return this.constructor.name;
473
+ }
474
+ toString() {
475
+ return Object.prototype.toString.call(this);
476
+ }
477
+ get(name) {
478
+ const values = this.getAll(name);
479
+ if (values.length === 0) {
480
+ return null;
481
+ }
482
+ let value = values.join(", ");
483
+ if (/^content-encoding$/i.test(name)) {
484
+ value = value.toLowerCase();
485
+ }
486
+ return value;
487
+ }
488
+ forEach(callback, thisArg = void 0) {
489
+ for (const name of this.keys()) {
490
+ Reflect.apply(callback, thisArg, [this.get(name), name, this]);
491
+ }
492
+ }
493
+ *values() {
494
+ for (const name of this.keys()) {
495
+ yield this.get(name);
496
+ }
497
+ }
498
+ /**
499
+ * @type {() => IterableIterator<[string, string]>}
500
+ */
501
+ *entries() {
502
+ for (const name of this.keys()) {
503
+ yield [name, this.get(name)];
504
+ }
505
+ }
506
+ [Symbol.iterator]() {
507
+ return this.entries();
508
+ }
509
+ /**
510
+ * Node-fetch non-spec method
511
+ * returning all headers and their values as array
512
+ * @returns {Record<string, string[]>}
513
+ */
514
+ raw() {
515
+ return [...this.keys()].reduce((result, key) => {
516
+ result[key] = this.getAll(key);
517
+ return result;
518
+ }, {});
519
+ }
520
+ /**
521
+ * For better console.log(headers) and also to convert Headers into Node.js Request compatible format
522
+ */
523
+ [Symbol.for("nodejs.util.inspect.custom")]() {
524
+ return [...this.keys()].reduce((result, key) => {
525
+ const values = this.getAll(key);
526
+ if (key === "host") {
527
+ result[key] = values[0];
528
+ } else {
529
+ result[key] = values.length > 1 ? values : values[0];
530
+ }
531
+ return result;
532
+ }, {});
533
+ }
534
+ };
535
+ Object.defineProperties(
536
+ Headers.prototype,
537
+ ["get", "entries", "forEach", "values"].reduce((result, property) => {
538
+ result[property] = { enumerable: true };
539
+ return result;
540
+ }, {})
541
+ );
542
+ function fromRawHeaders(headers = []) {
543
+ return new Headers(
544
+ headers.reduce((result, value, index, array) => {
545
+ if (index % 2 === 0) {
546
+ result.push(array.slice(index, index + 2));
547
+ }
548
+ return result;
549
+ }, []).filter(([name, value]) => {
550
+ try {
551
+ validateHeaderName(name);
552
+ validateHeaderValue(name, String(value));
553
+ return true;
554
+ } catch (e) {
555
+ return false;
556
+ }
557
+ })
558
+ );
559
+ }
560
+
561
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js
562
+ var redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
563
+ var isRedirect = (code) => {
564
+ return redirectStatus.has(code);
565
+ };
566
+
567
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js
568
+ var INTERNALS2 = Symbol("Response internals");
569
+ var Response = class _Response extends Body {
570
+ constructor(body = null, options = {}) {
571
+ super(body, options);
572
+ const status = options.status != null ? options.status : 200;
573
+ const headers = new Headers(options.headers);
574
+ if (body !== null && !headers.has("Content-Type")) {
575
+ const contentType = extractContentType(body, this);
576
+ if (contentType) {
577
+ headers.append("Content-Type", contentType);
578
+ }
579
+ }
580
+ this[INTERNALS2] = {
581
+ type: "default",
582
+ url: options.url,
583
+ status,
584
+ statusText: options.statusText || "",
585
+ headers,
586
+ counter: options.counter,
587
+ highWaterMark: options.highWaterMark
588
+ };
589
+ }
590
+ get type() {
591
+ return this[INTERNALS2].type;
592
+ }
593
+ get url() {
594
+ return this[INTERNALS2].url || "";
595
+ }
596
+ get status() {
597
+ return this[INTERNALS2].status;
598
+ }
599
+ /**
600
+ * Convenience property representing if the request ended normally
601
+ */
602
+ get ok() {
603
+ return this[INTERNALS2].status >= 200 && this[INTERNALS2].status < 300;
604
+ }
605
+ get redirected() {
606
+ return this[INTERNALS2].counter > 0;
607
+ }
608
+ get statusText() {
609
+ return this[INTERNALS2].statusText;
610
+ }
611
+ get headers() {
612
+ return this[INTERNALS2].headers;
613
+ }
614
+ get highWaterMark() {
615
+ return this[INTERNALS2].highWaterMark;
616
+ }
617
+ /**
618
+ * Clone this response
619
+ *
620
+ * @return Response
621
+ */
622
+ clone() {
623
+ return new _Response(clone(this, this.highWaterMark), {
624
+ type: this.type,
625
+ url: this.url,
626
+ status: this.status,
627
+ statusText: this.statusText,
628
+ headers: this.headers,
629
+ ok: this.ok,
630
+ redirected: this.redirected,
631
+ size: this.size,
632
+ highWaterMark: this.highWaterMark
633
+ });
634
+ }
635
+ /**
636
+ * @param {string} url The URL that the new response is to originate from.
637
+ * @param {number} status An optional status code for the response (e.g., 302.)
638
+ * @returns {Response} A Response object.
639
+ */
640
+ static redirect(url, status = 302) {
641
+ if (!isRedirect(status)) {
642
+ throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');
643
+ }
644
+ return new _Response(null, {
645
+ headers: {
646
+ location: new URL(url).toString()
647
+ },
648
+ status
649
+ });
650
+ }
651
+ static error() {
652
+ const response = new _Response(null, { status: 0, statusText: "" });
653
+ response[INTERNALS2].type = "error";
654
+ return response;
655
+ }
656
+ static json(data = void 0, init = {}) {
657
+ const body = JSON.stringify(data);
658
+ if (body === void 0) {
659
+ throw new TypeError("data is not JSON serializable");
660
+ }
661
+ const headers = new Headers(init && init.headers);
662
+ if (!headers.has("content-type")) {
663
+ headers.set("content-type", "application/json");
664
+ }
665
+ return new _Response(body, __spreadProps(__spreadValues({}, init), {
666
+ headers
667
+ }));
668
+ }
669
+ get [Symbol.toStringTag]() {
670
+ return "Response";
671
+ }
672
+ };
673
+ Object.defineProperties(Response.prototype, {
674
+ type: { enumerable: true },
675
+ url: { enumerable: true },
676
+ status: { enumerable: true },
677
+ ok: { enumerable: true },
678
+ redirected: { enumerable: true },
679
+ statusText: { enumerable: true },
680
+ headers: { enumerable: true },
681
+ clone: { enumerable: true }
682
+ });
683
+
684
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js
685
+ import { format as formatUrl } from "url";
686
+ import { deprecate as deprecate2 } from "util";
687
+
688
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js
689
+ var getSearch = (parsedURL) => {
690
+ if (parsedURL.search) {
691
+ return parsedURL.search;
692
+ }
693
+ const lastOffset = parsedURL.href.length - 1;
694
+ const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : "");
695
+ return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : "";
696
+ };
697
+
698
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js
699
+ import { isIP } from "net";
700
+ function stripURLForUseAsAReferrer(url, originOnly = false) {
701
+ if (url == null) {
702
+ return "no-referrer";
703
+ }
704
+ url = new URL(url);
705
+ if (/^(about|blob|data):$/.test(url.protocol)) {
706
+ return "no-referrer";
707
+ }
708
+ url.username = "";
709
+ url.password = "";
710
+ url.hash = "";
711
+ if (originOnly) {
712
+ url.pathname = "";
713
+ url.search = "";
714
+ }
715
+ return url;
716
+ }
717
+ var ReferrerPolicy = /* @__PURE__ */ new Set([
718
+ "",
719
+ "no-referrer",
720
+ "no-referrer-when-downgrade",
721
+ "same-origin",
722
+ "origin",
723
+ "strict-origin",
724
+ "origin-when-cross-origin",
725
+ "strict-origin-when-cross-origin",
726
+ "unsafe-url"
727
+ ]);
728
+ var DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin";
729
+ function validateReferrerPolicy(referrerPolicy) {
730
+ if (!ReferrerPolicy.has(referrerPolicy)) {
731
+ throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
732
+ }
733
+ return referrerPolicy;
734
+ }
735
+ function isOriginPotentiallyTrustworthy(url) {
736
+ if (/^(http|ws)s:$/.test(url.protocol)) {
737
+ return true;
738
+ }
739
+ const hostIp = url.host.replace(/(^\[)|(]$)/g, "");
740
+ const hostIPVersion = isIP(hostIp);
741
+ if (hostIPVersion === 4 && /^127\./.test(hostIp)) {
742
+ return true;
743
+ }
744
+ if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {
745
+ return true;
746
+ }
747
+ if (url.host === "localhost" || url.host.endsWith(".localhost")) {
748
+ return false;
749
+ }
750
+ if (url.protocol === "file:") {
751
+ return true;
752
+ }
753
+ return false;
754
+ }
755
+ function isUrlPotentiallyTrustworthy(url) {
756
+ if (/^about:(blank|srcdoc)$/.test(url)) {
757
+ return true;
758
+ }
759
+ if (url.protocol === "data:") {
760
+ return true;
761
+ }
762
+ if (/^(blob|filesystem):$/.test(url.protocol)) {
763
+ return true;
764
+ }
765
+ return isOriginPotentiallyTrustworthy(url);
766
+ }
767
+ function determineRequestsReferrer(request, { referrerURLCallback, referrerOriginCallback } = {}) {
768
+ if (request.referrer === "no-referrer" || request.referrerPolicy === "") {
769
+ return null;
770
+ }
771
+ const policy = request.referrerPolicy;
772
+ if (request.referrer === "about:client") {
773
+ return "no-referrer";
774
+ }
775
+ const referrerSource = request.referrer;
776
+ let referrerURL = stripURLForUseAsAReferrer(referrerSource);
777
+ let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true);
778
+ if (referrerURL.toString().length > 4096) {
779
+ referrerURL = referrerOrigin;
780
+ }
781
+ if (referrerURLCallback) {
782
+ referrerURL = referrerURLCallback(referrerURL);
783
+ }
784
+ if (referrerOriginCallback) {
785
+ referrerOrigin = referrerOriginCallback(referrerOrigin);
786
+ }
787
+ const currentURL = new URL(request.url);
788
+ switch (policy) {
789
+ case "no-referrer":
790
+ return "no-referrer";
791
+ case "origin":
792
+ return referrerOrigin;
793
+ case "unsafe-url":
794
+ return referrerURL;
795
+ case "strict-origin":
796
+ if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
797
+ return "no-referrer";
798
+ }
799
+ return referrerOrigin.toString();
800
+ case "strict-origin-when-cross-origin":
801
+ if (referrerURL.origin === currentURL.origin) {
802
+ return referrerURL;
803
+ }
804
+ if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
805
+ return "no-referrer";
806
+ }
807
+ return referrerOrigin;
808
+ case "same-origin":
809
+ if (referrerURL.origin === currentURL.origin) {
810
+ return referrerURL;
811
+ }
812
+ return "no-referrer";
813
+ case "origin-when-cross-origin":
814
+ if (referrerURL.origin === currentURL.origin) {
815
+ return referrerURL;
816
+ }
817
+ return referrerOrigin;
818
+ case "no-referrer-when-downgrade":
819
+ if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
820
+ return "no-referrer";
821
+ }
822
+ return referrerURL;
823
+ default:
824
+ throw new TypeError(`Invalid referrerPolicy: ${policy}`);
825
+ }
826
+ }
827
+ function parseReferrerPolicyFromHeader(headers) {
828
+ const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/);
829
+ let policy = "";
830
+ for (const token of policyTokens) {
831
+ if (token && ReferrerPolicy.has(token)) {
832
+ policy = token;
833
+ }
834
+ }
835
+ return policy;
836
+ }
837
+
838
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js
839
+ var INTERNALS3 = Symbol("Request internals");
840
+ var isRequest = (object) => {
841
+ return typeof object === "object" && typeof object[INTERNALS3] === "object";
842
+ };
843
+ var doBadDataWarn = deprecate2(
844
+ () => {
845
+ },
846
+ ".data is not a valid RequestInit property, use .body instead",
847
+ "https://github.com/node-fetch/node-fetch/issues/1000 (request)"
848
+ );
849
+ var Request = class _Request extends Body {
850
+ constructor(input, init = {}) {
851
+ let parsedURL;
852
+ if (isRequest(input)) {
853
+ parsedURL = new URL(input.url);
854
+ } else {
855
+ parsedURL = new URL(input);
856
+ input = {};
857
+ }
858
+ if (parsedURL.username !== "" || parsedURL.password !== "") {
859
+ throw new TypeError(`${parsedURL} is an url with embedded credentials.`);
860
+ }
861
+ let method = init.method || input.method || "GET";
862
+ if (/^(delete|get|head|options|post|put)$/i.test(method)) {
863
+ method = method.toUpperCase();
864
+ }
865
+ if (!isRequest(init) && "data" in init) {
866
+ doBadDataWarn();
867
+ }
868
+ if ((init.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) {
869
+ throw new TypeError("Request with GET/HEAD method cannot have body");
870
+ }
871
+ const inputBody = init.body ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
872
+ super(inputBody, {
873
+ size: init.size || input.size || 0
874
+ });
875
+ const headers = new Headers(init.headers || input.headers || {});
876
+ if (inputBody !== null && !headers.has("Content-Type")) {
877
+ const contentType = extractContentType(inputBody, this);
878
+ if (contentType) {
879
+ headers.set("Content-Type", contentType);
880
+ }
881
+ }
882
+ let signal = isRequest(input) ? input.signal : null;
883
+ if ("signal" in init) {
884
+ signal = init.signal;
885
+ }
886
+ if (signal != null && !isAbortSignal(signal)) {
887
+ throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");
888
+ }
889
+ let referrer = init.referrer == null ? input.referrer : init.referrer;
890
+ if (referrer === "") {
891
+ referrer = "no-referrer";
892
+ } else if (referrer) {
893
+ const parsedReferrer = new URL(referrer);
894
+ referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer;
895
+ } else {
896
+ referrer = void 0;
897
+ }
898
+ this[INTERNALS3] = {
899
+ method,
900
+ redirect: init.redirect || input.redirect || "follow",
901
+ headers,
902
+ parsedURL,
903
+ signal,
904
+ referrer
905
+ };
906
+ this.follow = init.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init.follow;
907
+ this.compress = init.compress === void 0 ? input.compress === void 0 ? true : input.compress : init.compress;
908
+ this.counter = init.counter || input.counter || 0;
909
+ this.agent = init.agent || input.agent;
910
+ this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384;
911
+ this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false;
912
+ this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || "";
913
+ }
914
+ /** @returns {string} */
915
+ get method() {
916
+ return this[INTERNALS3].method;
917
+ }
918
+ /** @returns {string} */
919
+ get url() {
920
+ return formatUrl(this[INTERNALS3].parsedURL);
921
+ }
922
+ /** @returns {Headers} */
923
+ get headers() {
924
+ return this[INTERNALS3].headers;
925
+ }
926
+ get redirect() {
927
+ return this[INTERNALS3].redirect;
928
+ }
929
+ /** @returns {AbortSignal} */
930
+ get signal() {
931
+ return this[INTERNALS3].signal;
932
+ }
933
+ // https://fetch.spec.whatwg.org/#dom-request-referrer
934
+ get referrer() {
935
+ if (this[INTERNALS3].referrer === "no-referrer") {
936
+ return "";
937
+ }
938
+ if (this[INTERNALS3].referrer === "client") {
939
+ return "about:client";
940
+ }
941
+ if (this[INTERNALS3].referrer) {
942
+ return this[INTERNALS3].referrer.toString();
943
+ }
944
+ return void 0;
945
+ }
946
+ get referrerPolicy() {
947
+ return this[INTERNALS3].referrerPolicy;
948
+ }
949
+ set referrerPolicy(referrerPolicy) {
950
+ this[INTERNALS3].referrerPolicy = validateReferrerPolicy(referrerPolicy);
951
+ }
952
+ /**
953
+ * Clone this request
954
+ *
955
+ * @return Request
956
+ */
957
+ clone() {
958
+ return new _Request(this);
959
+ }
960
+ get [Symbol.toStringTag]() {
961
+ return "Request";
962
+ }
963
+ };
964
+ Object.defineProperties(Request.prototype, {
965
+ method: { enumerable: true },
966
+ url: { enumerable: true },
967
+ headers: { enumerable: true },
968
+ redirect: { enumerable: true },
969
+ clone: { enumerable: true },
970
+ signal: { enumerable: true },
971
+ referrer: { enumerable: true },
972
+ referrerPolicy: { enumerable: true }
973
+ });
974
+ var getNodeRequestOptions = (request) => {
975
+ const { parsedURL } = request[INTERNALS3];
976
+ const headers = new Headers(request[INTERNALS3].headers);
977
+ if (!headers.has("Accept")) {
978
+ headers.set("Accept", "*/*");
979
+ }
980
+ let contentLengthValue = null;
981
+ if (request.body === null && /^(post|put)$/i.test(request.method)) {
982
+ contentLengthValue = "0";
983
+ }
984
+ if (request.body !== null) {
985
+ const totalBytes = getTotalBytes(request);
986
+ if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) {
987
+ contentLengthValue = String(totalBytes);
988
+ }
989
+ }
990
+ if (contentLengthValue) {
991
+ headers.set("Content-Length", contentLengthValue);
992
+ }
993
+ if (request.referrerPolicy === "") {
994
+ request.referrerPolicy = DEFAULT_REFERRER_POLICY;
995
+ }
996
+ if (request.referrer && request.referrer !== "no-referrer") {
997
+ request[INTERNALS3].referrer = determineRequestsReferrer(request);
998
+ } else {
999
+ request[INTERNALS3].referrer = "no-referrer";
1000
+ }
1001
+ if (request[INTERNALS3].referrer instanceof URL) {
1002
+ headers.set("Referer", request.referrer);
1003
+ }
1004
+ if (!headers.has("User-Agent")) {
1005
+ headers.set("User-Agent", "node-fetch");
1006
+ }
1007
+ if (request.compress && !headers.has("Accept-Encoding")) {
1008
+ headers.set("Accept-Encoding", "gzip, deflate, br");
1009
+ }
1010
+ let { agent } = request;
1011
+ if (typeof agent === "function") {
1012
+ agent = agent(parsedURL);
1013
+ }
1014
+ const search = getSearch(parsedURL);
1015
+ const options = {
1016
+ // Overwrite search to retain trailing ? (issue #776)
1017
+ path: parsedURL.pathname + search,
1018
+ // The following options are not expressed in the URL
1019
+ method: request.method,
1020
+ headers: headers[Symbol.for("nodejs.util.inspect.custom")](),
1021
+ insecureHTTPParser: request.insecureHTTPParser,
1022
+ agent
1023
+ };
1024
+ return {
1025
+ /** @type {URL} */
1026
+ parsedURL,
1027
+ options
1028
+ };
1029
+ };
1030
+
1031
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/abort-error.js
1032
+ var AbortError = class extends FetchBaseError {
1033
+ constructor(message, type = "aborted") {
1034
+ super(message, type);
1035
+ }
1036
+ };
1037
+
1038
+ // node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js
1039
+ var supportedSchemas = /* @__PURE__ */ new Set(["data:", "http:", "https:"]);
1040
+ async function fetch(url, options_) {
1041
+ return new Promise((resolve, reject) => {
1042
+ const request = new Request(url, options_);
1043
+ const { parsedURL, options } = getNodeRequestOptions(request);
1044
+ if (!supportedSchemas.has(parsedURL.protocol)) {
1045
+ throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`);
1046
+ }
1047
+ if (parsedURL.protocol === "data:") {
1048
+ const data = dist_default(request.url);
1049
+ const response2 = new Response(data, { headers: { "Content-Type": data.typeFull } });
1050
+ resolve(response2);
1051
+ return;
1052
+ }
1053
+ const send = (parsedURL.protocol === "https:" ? https : http2).request;
1054
+ const { signal } = request;
1055
+ let response = null;
1056
+ const abort = () => {
1057
+ const error = new AbortError("The operation was aborted.");
1058
+ reject(error);
1059
+ if (request.body && request.body instanceof Stream2.Readable) {
1060
+ request.body.destroy(error);
1061
+ }
1062
+ if (!response || !response.body) {
1063
+ return;
1064
+ }
1065
+ response.body.emit("error", error);
1066
+ };
1067
+ if (signal && signal.aborted) {
1068
+ abort();
1069
+ return;
1070
+ }
1071
+ const abortAndFinalize = () => {
1072
+ abort();
1073
+ finalize();
1074
+ };
1075
+ const request_ = send(parsedURL.toString(), options);
1076
+ if (signal) {
1077
+ signal.addEventListener("abort", abortAndFinalize);
1078
+ }
1079
+ const finalize = () => {
1080
+ request_.abort();
1081
+ if (signal) {
1082
+ signal.removeEventListener("abort", abortAndFinalize);
1083
+ }
1084
+ };
1085
+ request_.on("error", (error) => {
1086
+ reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, "system", error));
1087
+ finalize();
1088
+ });
1089
+ fixResponseChunkedTransferBadEnding(request_, (error) => {
1090
+ if (response && response.body) {
1091
+ response.body.destroy(error);
1092
+ }
1093
+ });
1094
+ if (process.version < "v14") {
1095
+ request_.on("socket", (s) => {
1096
+ let endedWithEventsCount;
1097
+ s.prependListener("end", () => {
1098
+ endedWithEventsCount = s._eventsCount;
1099
+ });
1100
+ s.prependListener("close", (hadError) => {
1101
+ if (response && endedWithEventsCount < s._eventsCount && !hadError) {
1102
+ const error = new Error("Premature close");
1103
+ error.code = "ERR_STREAM_PREMATURE_CLOSE";
1104
+ response.body.emit("error", error);
1105
+ }
1106
+ });
1107
+ });
1108
+ }
1109
+ request_.on("response", (response_) => {
1110
+ request_.setTimeout(0);
1111
+ const headers = fromRawHeaders(response_.rawHeaders);
1112
+ if (isRedirect(response_.statusCode)) {
1113
+ const location = headers.get("Location");
1114
+ let locationURL = null;
1115
+ try {
1116
+ locationURL = location === null ? null : new URL(location, request.url);
1117
+ } catch (e) {
1118
+ if (request.redirect !== "manual") {
1119
+ reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect"));
1120
+ finalize();
1121
+ return;
1122
+ }
1123
+ }
1124
+ switch (request.redirect) {
1125
+ case "error":
1126
+ reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, "no-redirect"));
1127
+ finalize();
1128
+ return;
1129
+ case "manual":
1130
+ break;
1131
+ case "follow": {
1132
+ if (locationURL === null) {
1133
+ break;
1134
+ }
1135
+ if (request.counter >= request.follow) {
1136
+ reject(new FetchError(`maximum redirect reached at: ${request.url}`, "max-redirect"));
1137
+ finalize();
1138
+ return;
1139
+ }
1140
+ const requestOptions = {
1141
+ headers: new Headers(request.headers),
1142
+ follow: request.follow,
1143
+ counter: request.counter + 1,
1144
+ agent: request.agent,
1145
+ compress: request.compress,
1146
+ method: request.method,
1147
+ body: clone(request),
1148
+ signal: request.signal,
1149
+ size: request.size,
1150
+ referrer: request.referrer,
1151
+ referrerPolicy: request.referrerPolicy
1152
+ };
1153
+ if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
1154
+ for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
1155
+ requestOptions.headers.delete(name);
1156
+ }
1157
+ }
1158
+ if (response_.statusCode !== 303 && request.body && options_.body instanceof Stream2.Readable) {
1159
+ reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect"));
1160
+ finalize();
1161
+ return;
1162
+ }
1163
+ if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request.method === "POST") {
1164
+ requestOptions.method = "GET";
1165
+ requestOptions.body = void 0;
1166
+ requestOptions.headers.delete("content-length");
1167
+ }
1168
+ const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers);
1169
+ if (responseReferrerPolicy) {
1170
+ requestOptions.referrerPolicy = responseReferrerPolicy;
1171
+ }
1172
+ resolve(fetch(new Request(locationURL, requestOptions)));
1173
+ finalize();
1174
+ return;
1175
+ }
1176
+ default:
1177
+ return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`));
1178
+ }
1179
+ }
1180
+ if (signal) {
1181
+ response_.once("end", () => {
1182
+ signal.removeEventListener("abort", abortAndFinalize);
1183
+ });
1184
+ }
1185
+ let body = pump(response_, new PassThrough2(), (error) => {
1186
+ if (error) {
1187
+ reject(error);
1188
+ }
1189
+ });
1190
+ if (process.version < "v12.10") {
1191
+ response_.on("aborted", abortAndFinalize);
1192
+ }
1193
+ const responseOptions = {
1194
+ url: request.url,
1195
+ status: response_.statusCode,
1196
+ statusText: response_.statusMessage,
1197
+ headers,
1198
+ size: request.size,
1199
+ counter: request.counter,
1200
+ highWaterMark: request.highWaterMark
1201
+ };
1202
+ const codings = headers.get("Content-Encoding");
1203
+ if (!request.compress || request.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {
1204
+ response = new Response(body, responseOptions);
1205
+ resolve(response);
1206
+ return;
1207
+ }
1208
+ const zlibOptions = {
1209
+ flush: zlib.Z_SYNC_FLUSH,
1210
+ finishFlush: zlib.Z_SYNC_FLUSH
1211
+ };
1212
+ if (codings === "gzip" || codings === "x-gzip") {
1213
+ body = pump(body, zlib.createGunzip(zlibOptions), (error) => {
1214
+ if (error) {
1215
+ reject(error);
1216
+ }
1217
+ });
1218
+ response = new Response(body, responseOptions);
1219
+ resolve(response);
1220
+ return;
1221
+ }
1222
+ if (codings === "deflate" || codings === "x-deflate") {
1223
+ const raw = pump(response_, new PassThrough2(), (error) => {
1224
+ if (error) {
1225
+ reject(error);
1226
+ }
1227
+ });
1228
+ raw.once("data", (chunk) => {
1229
+ if ((chunk[0] & 15) === 8) {
1230
+ body = pump(body, zlib.createInflate(), (error) => {
1231
+ if (error) {
1232
+ reject(error);
1233
+ }
1234
+ });
1235
+ } else {
1236
+ body = pump(body, zlib.createInflateRaw(), (error) => {
1237
+ if (error) {
1238
+ reject(error);
1239
+ }
1240
+ });
1241
+ }
1242
+ response = new Response(body, responseOptions);
1243
+ resolve(response);
1244
+ });
1245
+ raw.once("end", () => {
1246
+ if (!response) {
1247
+ response = new Response(body, responseOptions);
1248
+ resolve(response);
1249
+ }
1250
+ });
1251
+ return;
1252
+ }
1253
+ if (codings === "br") {
1254
+ body = pump(body, zlib.createBrotliDecompress(), (error) => {
1255
+ if (error) {
1256
+ reject(error);
1257
+ }
1258
+ });
1259
+ response = new Response(body, responseOptions);
1260
+ resolve(response);
1261
+ return;
1262
+ }
1263
+ response = new Response(body, responseOptions);
1264
+ resolve(response);
1265
+ });
1266
+ writeToStream(request_, request).catch(reject);
1267
+ });
1268
+ }
1269
+ function fixResponseChunkedTransferBadEnding(request, errorCallback) {
1270
+ const LAST_CHUNK = Buffer3.from("0\r\n\r\n");
1271
+ let isChunkedTransfer = false;
1272
+ let properLastChunkReceived = false;
1273
+ let previousChunk;
1274
+ request.on("response", (response) => {
1275
+ const { headers } = response;
1276
+ isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"];
1277
+ });
1278
+ request.on("socket", (socket) => {
1279
+ const onSocketClose = () => {
1280
+ if (isChunkedTransfer && !properLastChunkReceived) {
1281
+ const error = new Error("Premature close");
1282
+ error.code = "ERR_STREAM_PREMATURE_CLOSE";
1283
+ errorCallback(error);
1284
+ }
1285
+ };
1286
+ const onData = (buf) => {
1287
+ properLastChunkReceived = Buffer3.compare(buf.slice(-5), LAST_CHUNK) === 0;
1288
+ if (!properLastChunkReceived && previousChunk) {
1289
+ properLastChunkReceived = Buffer3.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && Buffer3.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0;
1290
+ }
1291
+ previousChunk = buf;
1292
+ };
1293
+ socket.prependListener("close", onSocketClose);
1294
+ socket.on("data", onData);
1295
+ request.on("close", () => {
1296
+ socket.removeListener("close", onSocketClose);
1297
+ socket.removeListener("data", onData);
1298
+ });
1299
+ });
1300
+ }
1301
+
1302
+ // src/index.ts
1303
+ import { createUnplugin } from "unplugin";
1304
+ import c from "picocolors";
1305
+ import { viteVConsole } from "vite-plugin-vconsole";
1306
+ import cookie from "cookie";
1307
+ import { start } from "chii";
1308
+ import { getRandomPort } from "get-port-please";
1309
+ var config;
1310
+ var colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
1311
+ var resovedInfo = {
1312
+ devtoolsInstance: void 0,
1313
+ availablePort: void 0,
1314
+ targetURL: void 0
1315
+ };
1316
+ var unpluginFactory = (options) => {
1317
+ const {
1318
+ chii: enableChii = true
1319
+ } = options || {};
1320
+ function debug(...args) {
1321
+ if (options == null ? void 0 : options.debug) {
1322
+ console.log(` ${c.yellow("DEBUG")} `, ...args);
1323
+ }
1324
+ }
1325
+ const plugins = [];
1326
+ const unpluginDing = {
1327
+ name: "unplugin-dingtalk",
1328
+ enforce: "pre",
1329
+ transformInclude(id) {
1330
+ return (id.endsWith("main.ts") || id.endsWith("main.js")) && !id.includes("node_modules");
1331
+ },
1332
+ async transform(_source) {
1333
+ var _a, _b, _c;
1334
+ if ((options == null ? void 0 : options.enable) && enableChii && !resovedInfo.availablePort) {
1335
+ resovedInfo.availablePort = await getRandomPort();
1336
+ debug(`chii server port: ${JSON.stringify({ availablePort: resovedInfo.availablePort })}`);
1337
+ start({
1338
+ port: resovedInfo.availablePort
1339
+ });
1340
+ }
1341
+ if ((options == null ? void 0 : options.enable) && ((_a = options == null ? void 0 : options.vueDevtools) == null ? void 0 : _a.enable)) {
1342
+ const codes = [
1343
+ `/* eslint-disable */;
1344
+ import { devtools } from '@vue/devtools'
1345
+ devtools.connect(${(_b = options == null ? void 0 : options.vueDevtools) == null ? void 0 : _b.host}, ${(_c = options == null ? void 0 : options.vueDevtools) == null ? void 0 : _c.port});`,
1346
+ (options == null ? void 0 : options.enable) && enableChii ? `(() => {
1347
+ const script = document.createElement('script');
1348
+ script.src="http://localhost:${resovedInfo.availablePort}/target.js";
1349
+ document.body.appendChild(script);
1350
+ })()` : "",
1351
+ `/* eslint-enable */${_source};`
1352
+ ];
1353
+ return {
1354
+ code: codes.join("\n"),
1355
+ map: null
1356
+ // support source map
1357
+ };
1358
+ }
1359
+ return {
1360
+ code: _source,
1361
+ map: null
1362
+ // support source map
1363
+ };
1364
+ },
1365
+ vite: {
1366
+ configResolved(_config) {
1367
+ config = _config;
1368
+ },
1369
+ async configureServer(server) {
1370
+ var _a, _b, _c;
1371
+ if (!(options == null ? void 0 : options.enable)) {
1372
+ return;
1373
+ }
1374
+ const availablePort = resovedInfo.availablePort;
1375
+ if ((options == null ? void 0 : options.enable) && ((_a = options == null ? void 0 : options.vconsole) == null ? void 0 : _a.enabled)) {
1376
+ plugins.push(viteVConsole(options == null ? void 0 : options.vconsole));
1377
+ }
1378
+ const _printUrls = server.printUrls.bind(server);
1379
+ let source = `localhost:${config.server.port || 5173}`;
1380
+ const url = (_b = server.resolvedUrls) == null ? void 0 : _b.local[0];
1381
+ if (url) {
1382
+ const u = new URL(url);
1383
+ source = u.host;
1384
+ }
1385
+ const base = server.config.base || "/";
1386
+ const _targetUrl = (_c = options == null ? void 0 : options.targetUrl) != null ? _c : `http://${source}${base}`;
1387
+ server.printUrls = () => {
1388
+ var _a2;
1389
+ _printUrls();
1390
+ console.log(` ${c.green("\u279C")} ${c.bold(
1391
+ `Open in dingtalk${((_a2 = options == null ? void 0 : options.vueDevtools) == null ? void 0 : _a2.enable) ? " (with vue-devtools)" : ""}`
1392
+ )}: ${colorUrl(`http://${source}${base}open-dingtalk`)}`);
1393
+ if (enableChii) {
1394
+ console.log(` ${c.green("\u279C")} ${c.bold(
1395
+ "Click to open chrome devtools"
1396
+ )}: ${colorUrl(`http://${source}${base}__chrome_devtools`)}`);
1397
+ }
1398
+ };
1399
+ const targetURL = new URL(_targetUrl);
1400
+ targetURL.searchParams.append("ddtab", "true");
1401
+ if (options == null ? void 0 : options.corpId) {
1402
+ targetURL.searchParams.append("corpId", options.corpId);
1403
+ }
1404
+ if (options.debugCookies && options.debugCookies.length > 0) {
1405
+ server.middlewares.use((req, res, next) => {
1406
+ const cookies = cookie.parse(req.headers.cookie || "");
1407
+ for (const [name, value] of Object.entries(cookies)) {
1408
+ if (options.debugCookies && options.debugCookies.length > 0 && options.debugCookies.includes(name)) {
1409
+ const serializedCookie = cookie.serialize(name, value, {
1410
+ httpOnly: false
1411
+ });
1412
+ res.setHeader("Set-Cookie", serializedCookie);
1413
+ }
1414
+ }
1415
+ next();
1416
+ });
1417
+ }
1418
+ if (enableChii) {
1419
+ server.middlewares.use("/__chrome_devtools", async (_req, res) => {
1420
+ try {
1421
+ const raw = await fetch(`http://localhost:${availablePort}/targets`);
1422
+ const data = await raw.json();
1423
+ if ((data == null ? void 0 : data.targets.length) > 0) {
1424
+ const devToolsUrl = `http://localhost:${availablePort}/front_end/chii_app.html?ws=localhost:${availablePort}/client/${Math.random().toString(20).substring(2, 8)}?target=${data.targets[0].id}&rtc=false`;
1425
+ res.writeHead(302, { Location: devToolsUrl });
1426
+ res.end();
1427
+ }
1428
+ } catch (error) {
1429
+ debug(`${error}`);
1430
+ res.writeHead(502);
1431
+ res.end();
1432
+ }
1433
+ });
1434
+ }
1435
+ server.middlewares.use("/open-dingtalk", (req, res) => {
1436
+ var _a2;
1437
+ debug(targetURL.toString());
1438
+ res.writeHead(302, {
1439
+ Location: `dingtalk://dingtalkclient/page/link?url=${encodeURIComponent(targetURL.toString())}`
1440
+ });
1441
+ if (((_a2 = options == null ? void 0 : options.vueDevtools) == null ? void 0 : _a2.enable) && !resovedInfo.devtoolsInstance) {
1442
+ resovedInfo.devtoolsInstance = exec("npx vue-devtools");
1443
+ console.log(` ${c.green("\u279C")} vue-devtools is running. If the devtools has no data, please refresh the page in dingtalk.`);
1444
+ resovedInfo.devtoolsInstance.on("exit", () => {
1445
+ resovedInfo.devtoolsInstance = void 0;
1446
+ });
1447
+ process2.on("exit", () => {
1448
+ if (resovedInfo.devtoolsInstance) {
1449
+ resovedInfo.devtoolsInstance.kill();
1450
+ }
1451
+ });
1452
+ }
1453
+ res.end();
1454
+ });
1455
+ }
1456
+ },
1457
+ webpack(compiler) {
1458
+ var _a, _b;
1459
+ if (!(options == null ? void 0 : options.enable)) {
1460
+ return;
1461
+ }
1462
+ const devServerOptions = __spreadValues(__spreadValues({
1463
+ host: "localhost",
1464
+ port: 8080
1465
+ }, compiler.options.devServer), (_a = process2.VUE_CLI_SERVICE) == null ? void 0 : _a.projectOptions.devServer);
1466
+ const source = `${devServerOptions.host === "0.0.0.0" ? "127.0.0.1" : devServerOptions.host}:${devServerOptions.port}`;
1467
+ const base = compiler.options.output.publicPath || "/";
1468
+ const _targetUrl = (_b = options == null ? void 0 : options.targetUrl) != null ? _b : `http://${source}${base}`;
1469
+ compiler.hooks.done.tap("unplugin-dingtalk", () => {
1470
+ var _a2;
1471
+ console.log(` ${c.green("\u279C")} ${c.bold(
1472
+ `Open in dingtalk${((_a2 = options == null ? void 0 : options.vueDevtools) == null ? void 0 : _a2.enable) ? " (with vue-devtools)" : ""}`
1473
+ )}: ${colorUrl(`http://${source}${base}open-dingtalk`)}`);
1474
+ if (enableChii) {
1475
+ console.log(` ${c.green("\u279C")} ${c.bold(
1476
+ "Click to open chrome devtools"
1477
+ )}: ${colorUrl(`http://${source}${base}__chrome_devtools`)}`);
1478
+ }
1479
+ });
1480
+ resovedInfo.targetURL = new URL(_targetUrl);
1481
+ resovedInfo.targetURL.searchParams.append("ddtab", "true");
1482
+ if (options == null ? void 0 : options.corpId) {
1483
+ resovedInfo.targetURL.searchParams.append("corpId", options.corpId);
1484
+ }
1485
+ }
1486
+ };
1487
+ plugins.push(unpluginDing);
1488
+ return plugins;
1489
+ };
1490
+ var unplugin = /* @__PURE__ */ createUnplugin(unpluginFactory);
1491
+ var src_default = unplugin;
1492
+
1493
+ export {
1494
+ fetch,
1495
+ resovedInfo,
1496
+ unpluginFactory,
1497
+ unplugin,
1498
+ src_default
1499
+ };